sema-browser 0.1.1
Drive a real browser over CDP: navigate, click, fill, wait, screenshot, and agent-facing page snapshots
package.sema
1415 lines
89c307a33b20
File details
Source stored with sema-browser 0.1.1. Line links refer to these exact bytes.
SHA-256 89c307a33b202858c832485cd0440aa708f788869149439093428841ea7de28a
1;; sema-browser — drive a real browser: navigate, click, fill, wait, screenshot, snapshot2;;3;; A Playwright-style layer over sema-cdp. Selectors auto-wait until the element4;; is actionable, clicks and keystrokes are real input events (not JS .click()),5;; and page/snapshot renders the accessibility tree as compact text with stable6;; refs — built for agent loops as much as for tests.78(module sema-browser9(export browser/launch10browser/connect11browser/close!12browser/page13browser/pages14browser/incognito-page15browser/new-context!16browser/context-page17browser/dispose-context!18browser/devices19browser/version20browser/with-page21page/goto22page/back23page/forward24page/reload25page/set-content26page/url27page/title28page/html29page/eval30page/text31page/texts32page/attr33page/count34page/exists?35page/click36page/dblclick37page/hover38page/focus39page/fill40page/type41page/press42page/select43page/check44page/uncheck45page/upload46page/wait-for47page/wait-for-function48page/scroll49page/drag50page/bounding-box51page/screenshot52page/pdf53page/add-init-script!54page/track-console!55page/console56page/clear-console!57page/downloads-to!58page/wait-for-download59page/set-viewport!60page/set-user-agent!61page/set-media!62page/set-offline!63page/set-geolocation!64page/set-timezone!65page/cookies66page/set-cookie!67page/clear-cookies!68page/on-dialog!69page/track-network!70page/requests71page/wait-for-response72page/websocket-frames73page/set-cpu-throttle!74page/start-js-coverage!75page/stop-js-coverage76page/clipboard-write!77page/clipboard-read78page/emulate-device!79page/start-screencast!80page/stop-screencast!81page/frames82page/frame83page/eval-in-frame84page/response-body85page/authenticate!86page/on-request!87page/block!88page/stop-intercept!89page/snapshot90page/click-ref91page/fill-ref92page/close!)9394(import "sema-cdp")9596(define default-timeout 30000)9798;; ---------------------------------------------------------------- browser99100(define (browser/launch . opts-rest)101"Launch a browser and return it. Options map: :headless (default #t), :chrome, :args, :user-data-dir — see cdp/launch."102(if (null? opts-rest) (cdp/launch) (cdp/launch (first opts-rest))))103104(define (browser/connect url)105"Attach to an already-running browser by its devtools address — see cdp/connect."106(cdp/connect url))107108(define (browser/close! b)109"Close the browser and release its process."110(cdp/close! b))111112(define (browser/page b)113"Open a new tab and return a page. The page doubles as a cdp session, so (cdp/send page ...) reaches the whole protocol."114(init-page (cdp/attach! b (cdp/new-target! b "about:blank"))))115116;; Enable the domains a page needs and hand it back. Also used when adopting117;; already-open tabs, so it must be idempotent.118(define (init-page sess)119(cdp/send sess "Page.enable")120(cdp/send sess "DOM.enable")121(cdp/send sess "DOM.getDocument" {:depth 0})122sess)123124(define (page/close! pg)125"Close the page's tab."126(cdp/send (:conn pg) "Target.closeTarget" {:targetId (:target-id pg)})127nil)128129(define (browser/pages b)130"Attach to every already-open tab and return them as pages, in target order. Useful after browser/connect to drive an existing session."131(map (fn (t) (init-page (cdp/attach! b (:targetId t))))132(filter (fn (t) (= "page" (:type t))) (cdp/targets b))))133134(define (browser/new-context! b)135"Create an isolated incognito browser context (own cookies and storage) and return its id. Open pages in it with browser/context-page."136(:browserContextId (cdp/send b "Target.createBrowserContext")))137138(define (browser/context-page b context-id)139"Open a new page inside a browser context from browser/new-context!. Pages in the same context share cookies and storage."140(let ((tid (:targetId (cdp/send b "Target.createTarget"141{:url "about:blank" :browserContextId context-id}))))142(init-page (cdp/attach! b tid))))143144(define (browser/dispose-context! b context-id)145"Dispose a browser context, closing its pages and discarding its state."146(cdp/send b "Target.disposeBrowserContext" {:browserContextId context-id})147nil)148149(define (browser/incognito-page b)150"Open a page in a fresh incognito browser context — isolated cookies and storage, discarded when the browser closes."151(browser/context-page b (browser/new-context! b)))152153(define (browser/version b)154"Return browser version info: :product, :userAgent, :protocolVersion, ..."155(cdp/version b))156157(define (browser/with-page f-or-opts . f-rest)158"Launch a browser, open a page, call f with it, and always close the browser. (browser/with-page f) or (browser/with-page opts f). Returns f's result."159(let* ((opts (if (null? f-rest) {} f-or-opts))160(f (if (null? f-rest) f-or-opts (first f-rest)))161(b (browser/launch opts)))162(try (let ((result (f (browser/page b))))163(browser/close! b)164result)165(catch e166(browser/close! b)167(raise e)))))168169;; ---------------------------------------------------------------- selectors170;;171;; A selector is CSS by default; "text=..." matches the last element whose own172;; text contains the string (case-insensitive); "xpath=..." is an XPath.173;; find-js compiles a selector into a JS expression evaluating to the element174;; (or null); the selector string is embedded via JSON so any quoting is safe.175176;; CSS and text= selectors pierce OPEN shadow roots: the query walks the177;; document plus every reachable shadow root, in tree-walk order. Closed178;; roots are unreachable by design; xpath= cannot pierce shadow DOM at all179;; (it only sees the light DOM).180(define shadow-roots-src181(string/join182["(scope => {"183" const roots = [scope];"184" const walk = (root) => {"185" for (const el of root.querySelectorAll('*'))"186" if (el.shadowRoot) { roots.push(el.shadowRoot); walk(el.shadowRoot); }"187" };"188" walk(scope);"189" return roots;"190" })(document.body || document)"]191"\n"))192193(define finder-src194(string/join195["(sel => {"196(format " const roots = ~a;" shadow-roots-src)197" if (sel.startsWith('text=')) {"198" const t = sel.slice(5).trim().toLowerCase();"199" let best = null;"200" for (const root of roots)"201" for (const el of root.querySelectorAll('*')) {"202" let own = '';"203" for (const n of el.childNodes) if (n.nodeType === 3) own += n.textContent;"204" if (own.trim().toLowerCase().includes(t)) best = el;"205" }"206" return best;"207" }"208" if (sel.startsWith('xpath='))"209" return document.evaluate(sel.slice(6), document, null,"210" XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;"211" for (const root of roots) {"212" const el = root.querySelector(sel);"213" if (el) return el;"214" }"215" return null;"216"})"]217"\n"))218219(define (find-js sel)220(format "(~a)(~a)" finder-src (json/encode sel)))221222;; All matches, in tree-walk order across the document and open shadow roots.223(define finder-all-src224(string/join225["(sel => {"226(format " const roots = ~a;" shadow-roots-src)227" if (sel.startsWith('text=')) {"228" const t = sel.slice(5).trim().toLowerCase();"229" const out = [];"230" for (const root of roots)"231" for (const el of root.querySelectorAll('*')) {"232" let own = '';"233" for (const n of el.childNodes) if (n.nodeType === 3) own += n.textContent;"234" if (own.trim().toLowerCase().includes(t)) out.push(el);"235" }"236" return out;"237" }"238" if (sel.startsWith('xpath=')) {"239" const r = document.evaluate(sel.slice(6), document, null,"240" XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);"241" const out = [];"242" for (let i = 0; i < r.snapshotLength; i++) out.push(r.snapshotItem(i));"243" return out;"244" }"245" return roots.flatMap(root => [...root.querySelectorAll(sel)]);"246"})"]247"\n"))248249(define (find-all-js sel)250(format "(~a)(~a)" finder-all-src (json/encode sel)))251252;; A frame handle (from page/frame) is the page map plus :frame-id and253;; :ctx-cell — a cached isolated-world execution context for that frame.254;; The world dies when the frame navigates, so it is recreated on demand.255(define (frame-context pg)256(let ((cached (mutable-cell/get (:ctx-cell pg))))257(or cached258(let ((ctx (:executionContextId259(cdp/send pg "Page.createIsolatedWorld"260{:frameId (:frame-id pg)}))))261(mutable-cell/set! (:ctx-cell pg) ctx)262ctx))))263264(define (context-gone? e)265(or (string/contains? (:message e) "Cannot find context")266(string/contains? (:message e) "Execution context was destroyed")267(string/contains? (:message e) "uniqueContextId not found")268(string/contains? (:message e) "Inspected target navigated")))269270(define (raw-eval-once pg js return-by-value)271(let* ((base {:expression js :returnByValue return-by-value :awaitPromise #t})272(params (if (:frame-id pg) (assoc base :contextId (frame-context pg)) base))273(r (cdp/send pg "Runtime.evaluate" params)))274(when (:exceptionDetails r)275(let ((d (:exceptionDetails r)))276(error (format "page/eval: page threw — ~a"277(or (:description (:exception d)) (:text d))))))278(:result r)))279280(define (raw-eval pg js return-by-value)281(if (:frame-id pg)282(try (raw-eval-once pg js return-by-value)283(catch e284(if (context-gone? e)285(begin (mutable-cell/set! (:ctx-cell pg) nil)286(raw-eval-once pg js return-by-value))287(raise e))))288(raw-eval-once pg js return-by-value)))289290(define (page/eval pg js)291"Evaluate a JS expression in the page (promises awaited) and return its value as data. Raises if the page throws."292(:value (raw-eval pg js #t)))293294;; Resolve a selector to a remote objectId, or nil if it matches nothing.295(define (resolve-object pg sel)296(:objectId (raw-eval pg (find-js sel) #f)))297298;; CDP keeps every returned objectId alive until released — free them after299;; each action so long sessions don't accumulate remote objects.300(define (release-object! pg object-id)301(try (cdp/send pg "Runtime.releaseObject" {:objectId object-id})302(catch e nil))303nil)304305;; Run f with the element's objectId, always releasing it afterwards.306(define (with-object pg object-id f)307(try (let ((result (f object-id)))308(release-object! pg object-id)309result)310(catch e311(release-object! pg object-id)312(raise e))))313314;; Call a JS function with the element as `this`; returns the value.315(define (call-on pg object-id fn-src)316(let ((r (cdp/send pg "Runtime.callFunctionOn"317{:objectId object-id :functionDeclaration fn-src :returnByValue #t})))318(when (:exceptionDetails r)319(error (format "sema-browser: in-page call threw — ~a"320(or (:description (:exception (:exceptionDetails r)))321(:text (:exceptionDetails r))))))322(:value (:result r))))323324;; ---------------------------------------------------------------- waiting325326(define (state-of pg sel)327(page/eval pg328(format329"(el => { if (!el) return {exists:false, visible:false, enabled:false};330const s = getComputedStyle(el);331const visible = el.getClientRects().length > 0332&& s.visibility !== 'hidden' && s.display !== 'none';333return {exists:true, visible, enabled: !el.disabled}; })(~a)"334(find-js sel))))335336(define (state-ok? state want)337(cond ((= want :attached) (:exists state))338((= want :visible) (:visible state))339((= want :hidden) (not (:visible state)))340((= want :detached) (not (:exists state)))341((= want :actionable) (and (:visible state) (:enabled state)))342(else (error (format "page/wait-for: unknown state ~a — use :attached, :visible, :hidden, or :detached" want)))))343344(define (wait-state pg sel want timeout)345(let ((deadline (+ (time-ms) timeout)))346(let loop ()347(if (state-ok? (state-of pg sel) want)348nil349(if (> (time-ms) deadline)350(error (format "sema-browser: timed out after ~ams waiting for ~a to be ~a"351timeout sel want))352(begin (sleep 100) (loop)))))))353354(define (page/wait-for pg sel . opts-rest)355"Wait until the element matching sel reaches a state. Options: :state (:visible default, :attached, :hidden, :detached), :timeout ms (default 30000)."356(let ((opts (if (null? opts-rest) {} (first opts-rest))))357(wait-state pg sel (get opts :state :visible) (get opts :timeout default-timeout))))358359(define (page/wait-for-function pg js . opts-rest)360"Poll a JS expression until it is truthy and return its value. Options: :timeout ms (default 30000), :interval ms (default 100)."361(let* ((opts (if (null? opts-rest) {} (first opts-rest)))362(deadline (+ (time-ms) (opt-timeout opts)))363(interval (get opts :interval 100)))364(let loop ()365(let ((v (page/eval pg js)))366(cond (v v)367((> (time-ms) deadline)368(error (format "page/wait-for-function: timed out after ~ams — ~a"369(opt-timeout opts) js)))370(else (sleep interval) (loop)))))))371372;; Wait until actionable, then resolve the element. The element can vanish373;; between the check and the resolve; treat that as the same timeout error.374(define (actionable-object pg sel timeout)375(wait-state pg sel :actionable timeout)376(let ((oid (resolve-object pg sel)))377(if (nil? oid)378(error (format "sema-browser: element ~a disappeared before the action" sel))379oid)))380381(define (opt-timeout opts) (get opts :timeout default-timeout))382383;; ---------------------------------------------------------------- reading384385(define (page/url pg)386"Return the page's current URL."387(page/eval pg "location.href"))388389(define (page/title pg)390"Return the page's document title."391(page/eval pg "document.title"))392393(define (page/html pg)394"Return the page's full HTML (document.documentElement.outerHTML)."395(page/eval pg "document.documentElement.outerHTML"))396397(define (page/text pg sel . opts-rest)398"Return the innerText of the element matching sel, auto-waiting for it to be attached. Options: :timeout ms."399(let ((opts (if (null? opts-rest) {} (first opts-rest))))400(wait-state pg sel :attached (opt-timeout opts))401(page/eval pg (format "(el => el ? el.innerText : null)(~a)" (find-js sel)))))402403(define (page/texts pg sel)404"Return the innerText of every element matching sel, in document order. Empty list when nothing matches — does not wait."405(page/eval pg (format "(~a).map(el => el.innerText)" (find-all-js sel))))406407(define (page/count pg sel)408"Return how many elements match sel right now — does not wait."409(page/eval pg (format "(~a).length" (find-all-js sel))))410411(define (page/exists? pg sel)412"Return whether any element matches sel right now — does not wait."413(> (page/count pg sel) 0))414415(define (page/attr pg sel name . opts-rest)416"Return an attribute value of the element matching sel (nil if absent), auto-waiting for the element. Options: :timeout ms."417(let ((opts (if (null? opts-rest) {} (first opts-rest))))418(wait-state pg sel :attached (opt-timeout opts))419(page/eval pg (format "(el => el ? el.getAttribute(~a) : null)(~a)"420(json/encode name) (find-js sel)))))421422;; ---------------------------------------------------------------- actions423424;; CDP modifier bitfield: Alt=1, Ctrl=2, Meta=4, Shift=8.425(define modifier-bits426{"Alt" 1 "Control" 2 "Ctrl" 2 "Meta" 4 "Cmd" 4 "Command" 4 "Shift" 8})427428(define (modifiers-mask mods)429(foldl (fn (acc m)430(+ acc (or (get modifier-bits m)431(error (format "sema-browser: unknown modifier ~a — use ~a"432m (string/join (keys modifier-bits) ", "))))))4330434mods))435436;; Scroll the element into view and return its center in MAIN-viewport437;; coordinates. DOM.getContentQuads reports quads in the top frame's space,438;; which makes clicks inside iframes land correctly; the JS bounding-rect439;; fallback covers elements the quads API rejects (e.g. some inline cases).440(define (element-center pg oid)441(call-on pg oid442"function(){ this.scrollIntoView({block:'center', inline:'center'}); }")443(let ((quads (try (:quads (cdp/send pg "DOM.getContentQuads" {:objectId oid}))444(catch e (list)))))445(if (null? quads)446(call-on pg oid447"function(){ const r = this.getBoundingClientRect();448return {x: r.x + r.width/2, y: r.y + r.height/2}; }")449(let ((q (first quads)))450;; q = [x1 y1 x2 y2 x3 y3 x4 y4] — average the four corners.451{:x (/ (+ (nth q 0) (nth q 2) (nth q 4) (nth q 6)) 4.0)452:y (/ (+ (nth q 1) (nth q 3) (nth q 5) (nth q 7)) 4.0)}))))453454(define (mouse-event pg type p opts)455(let ((button (get opts :button :left)))456(cdp/send pg "Input.dispatchMouseEvent"457{:type type :x (:x p) :y (:y p)458:button (if (keyword? button) (keyword/to-string button) button)459:clickCount (get opts :click-count 1)460:modifiers (modifiers-mask (get opts :modifiers (list)))})))461462;; A double click is two press/release pairs, the second with clickCount 2.463(define (click-object pg oid opts)464(let ((p (element-center pg oid)))465(cdp/send pg "Input.dispatchMouseEvent" {:type "mouseMoved" :x (:x p) :y (:y p)})466(let loop ((n 1))467(when (<= n (get opts :click-count 1))468(mouse-event pg "mousePressed" p (assoc opts :click-count n))469(mouse-event pg "mouseReleased" p (assoc opts :click-count n))470(loop (+ n 1))))471nil))472473(define (page/click pg sel . opts-rest)474"Click the element matching sel with a real mouse event, auto-waiting until it is visible and enabled. Options: :timeout ms, :button (:left default, :right, :middle), :click-count, :modifiers ([\"Shift\" \"Meta\" ...])."475(let ((opts (if (null? opts-rest) {} (first opts-rest))))476(with-object pg (actionable-object pg sel (opt-timeout opts))477(fn (oid) (click-object pg oid opts)))))478479(define (page/dblclick pg sel . opts-rest)480"Double-click the element matching sel. Options as page/click."481(let ((opts (if (null? opts-rest) {} (first opts-rest))))482(with-object pg (actionable-object pg sel (opt-timeout opts))483(fn (oid) (click-object pg oid (assoc opts :click-count 2))))))484485(define (page/hover pg sel . opts-rest)486"Move the mouse over the element matching sel (fires mouseover/mouseenter). Options: :timeout ms."487(let ((opts (if (null? opts-rest) {} (first opts-rest))))488(with-object pg (actionable-object pg sel (opt-timeout opts))489(fn (oid)490(let ((p (element-center pg oid)))491(cdp/send pg "Input.dispatchMouseEvent"492{:type "mouseMoved" :x (:x p) :y (:y p)})493nil)))))494495(define (page/focus pg sel . opts-rest)496"Focus the element matching sel. Options: :timeout ms."497(let ((opts (if (null? opts-rest) {} (first opts-rest))))498(with-object pg (actionable-object pg sel (opt-timeout opts))499(fn (oid) (call-on pg oid "function(){ this.focus(); }")))))500501(define (fill-object pg oid text)502(if (= text "")503(call-on pg oid504"function(){ this.focus();505if ('value' in this) { this.value = '';506this.dispatchEvent(new Event('input', {bubbles:true}));507this.dispatchEvent(new Event('change', {bubbles:true})); }508else this.textContent = ''; }")509(begin510(call-on pg oid511"function(){ this.focus();512if (this.select) this.select();513else if (this.isContentEditable) {514const r = document.createRange(); r.selectNodeContents(this);515const s = getSelection(); s.removeAllRanges(); s.addRange(r); } }")516(cdp/send pg "Input.insertText" {:text text})))517nil)518519(define (page/fill pg sel text . opts-rest)520"Focus the element matching sel and replace its contents with text (real text-input events). Works on inputs, textareas, and contenteditable. Options: :timeout ms."521(let ((opts (if (null? opts-rest) {} (first opts-rest))))522(with-object pg (actionable-object pg sel (opt-timeout opts))523(fn (oid) (fill-object pg oid text)))))524525;; keyCode is carried as windowsVirtualKeyCode/nativeVirtualKeyCode — those526;; are the CDP parameter names; DOM event.keyCode is derived from them.527(define named-keys528(foldl (fn (m i)529(let ((name (format "F~a" i)))530(assoc m name {:key name :code name :vk (+ 111 i)})))531{"Enter" {:key "Enter" :code "Enter" :vk 13 :text "\r"}532"Tab" {:key "Tab" :code "Tab" :vk 9}533"Escape" {:key "Escape" :code "Escape" :vk 27}534"Backspace" {:key "Backspace" :code "Backspace" :vk 8}535"Delete" {:key "Delete" :code "Delete" :vk 46}536"Insert" {:key "Insert" :code "Insert" :vk 45}537"Home" {:key "Home" :code "Home" :vk 36}538"End" {:key "End" :code "End" :vk 35}539"PageUp" {:key "PageUp" :code "PageUp" :vk 33}540"PageDown" {:key "PageDown" :code "PageDown" :vk 34}541"Space" {:key " " :code "Space" :vk 32 :text " "}542"ArrowLeft" {:key "ArrowLeft" :code "ArrowLeft" :vk 37}543"ArrowRight" {:key "ArrowRight" :code "ArrowRight" :vk 39}544"ArrowUp" {:key "ArrowUp" :code "ArrowUp" :vk 38}545"ArrowDown" {:key "ArrowDown" :code "ArrowDown" :vk 40}}546(range 1 13)))547548(define (key-spec key)549(let ((spec (or (get named-keys key)550(if (= (string-length key) 1)551;; Letters and digits get their US-layout virtual key code552;; (the uppercase char code) so pages reading event.keyCode work.553(let ((up (string/upper key)))554(if (regex/match "^[A-Z0-9]$" up)555{:key key :text key :vk (char->integer (first (string->list up)))}556{:key key :text key}))557(error (format "page/press: unknown key ~a — use a single character or one of: ~a"558key (string/join (keys named-keys) ", ")))))))559;; Only windowsVirtualKeyCode — event.keyCode derives from it. Never send560;; nativeVirtualKeyCode: on macOS Chrome reads it as a Mac hardware561;; keycode (65 = numpad-decimal, not "A"), and with modifiers set and no562;; text it triggers an infinite synthetic autorepeat in headless.563(let ((base (dissoc spec :vk)))564(if (:vk spec)565(assoc base :windowsVirtualKeyCode (:vk spec))566base))))567568;; "Control+a" / "Meta+Shift+r" — leading parts are modifiers, last is the key.569;; With Control or Meta held, the key produces no text (matching real keyboards).570(define (dispatch-key pg chord)571(let* ((parts (if (= (string-length chord) 1)572(list chord) ; a literal "+" is a key, not a chord573(string/split chord "+")))574(mods (if (> (count parts) 1) (take (- (count parts) 1) parts) (list)))575(spec (key-spec (last parts)))576(mask (modifiers-mask mods))577(down (assoc spec :type "keyDown" :modifiers mask))578(down (if (> (bit/and mask 6) 0) (dissoc down :text) down)))579(cdp/send pg "Input.dispatchKeyEvent" down)580(cdp/send pg "Input.dispatchKeyEvent"581(assoc (dissoc spec :text) :type "keyUp" :modifiers mask))582nil))583584(define (page/press pg sel key . opts-rest)585"Focus the element matching sel and press a key or chord: \"Enter\", \"Tab\", \"Escape\", arrows, any single character, or with modifiers (\"Control+a\", \"Meta+Shift+r\"). Options: :timeout ms."586(let ((opts (if (null? opts-rest) {} (first opts-rest))))587(with-object pg (actionable-object pg sel (opt-timeout opts))588(fn (oid) (call-on pg oid "function(){ this.focus(); }")))589(dispatch-key pg key)))590591(define (page/type pg sel text . opts-rest)592"Focus the element matching sel and type text character by character with real key events — for pages reacting to each keystroke (autocomplete, masked inputs). Appends; use page/fill to replace. Options: :timeout ms."593(let ((opts (if (null? opts-rest) {} (first opts-rest))))594(with-object pg (actionable-object pg sel (opt-timeout opts))595(fn (oid) (call-on pg oid "function(){ this.focus(); }")))596(for-each (fn (ch) (dispatch-key pg (char->string ch)))597(string->list text))598nil))599600(define (set-checked pg sel want opts)601(with-object pg (actionable-object pg sel (opt-timeout opts))602(fn (oid)603(when (not (= want (call-on pg oid "function(){ return !!this.checked; }")))604(click-object pg oid {}))))605nil)606607(define (page/check pg sel . opts-rest)608"Ensure the checkbox/radio matching sel is checked (clicks only when needed). Options: :timeout ms."609(set-checked pg sel #t (if (null? opts-rest) {} (first opts-rest))))610611(define (page/uncheck pg sel . opts-rest)612"Ensure the checkbox matching sel is unchecked (clicks only when needed). Options: :timeout ms."613(set-checked pg sel #f (if (null? opts-rest) {} (first opts-rest))))614615(define (page/scroll pg dx dy . opts-rest)616"Scroll with a mouse-wheel event: positive dy scrolls down. Options: :selector (wheel over that element instead of the viewport center), :timeout ms."617(let* ((opts (if (null? opts-rest) {} (first opts-rest)))618(p (if (get opts :selector)619(with-object pg (actionable-object pg (get opts :selector)620(opt-timeout opts))621(fn (oid) (element-center pg oid)))622(page/eval pg "({x: innerWidth/2, y: innerHeight/2})"))))623(cdp/send pg "Input.dispatchMouseEvent"624{:type "mouseWheel" :x (:x p) :y (:y p) :deltaX dx :deltaY dy})625nil))626627;; Mouse-based drag: press on the source, move in steps, release on the628;; target. Drives sliders, canvases, and pointer-event UIs. HTML5629;; draggable="true" drag-and-drop uses a separate DataTransfer pipeline that630;; synthetic mouse events do not trigger.631(define (page/drag pg from-sel to-sel . opts-rest)632"Drag from one element's center to another's with real mouse events (press, move in steps, release). Options: :steps (default 10), :timeout ms."633(let* ((opts (if (null? opts-rest) {} (first opts-rest)))634(steps (get opts :steps 10))635(from (with-object pg (actionable-object pg from-sel (opt-timeout opts))636(fn (oid) (element-center pg oid))))637(to (with-object pg (actionable-object pg to-sel (opt-timeout opts))638(fn (oid) (element-center pg oid)))))639(cdp/send pg "Input.dispatchMouseEvent"640{:type "mouseMoved" :x (:x from) :y (:y from)})641(cdp/send pg "Input.dispatchMouseEvent"642{:type "mousePressed" :x (:x from) :y (:y from)643:button "left" :clickCount 1})644(let loop ((i 1))645(when (<= i steps)646(cdp/send pg "Input.dispatchMouseEvent"647{:type "mouseMoved" :button "left"648:x (+ (:x from) (* (- (:x to) (:x from)) (/ i steps)))649:y (+ (:y from) (* (- (:y to) (:y from)) (/ i steps)))})650(loop (+ i 1))))651(cdp/send pg "Input.dispatchMouseEvent"652{:type "mouseReleased" :x (:x to) :y (:y to)653:button "left" :clickCount 1})654nil))655656(define (quads->box quads)657(let* ((q (first quads))658(xs (list (nth q 0) (nth q 2) (nth q 4) (nth q 6)))659(ys (list (nth q 1) (nth q 3) (nth q 5) (nth q 7)))660(x0 (apply min xs)) (y0 (apply min ys)))661{:x x0 :y y0662:width (- (apply max xs) x0)663:height (- (apply max ys) y0)}))664665(define (page/bounding-box pg sel . opts-rest)666"Return the element's bounding box in main-viewport coordinates: {:x :y :width :height}. Auto-waits for the element to be visible. Options: :timeout ms."667(let ((opts (if (null? opts-rest) {} (first opts-rest))))668(wait-state pg sel :visible (opt-timeout opts))669(let ((oid (resolve-object pg sel)))670(when (nil? oid)671(error (format "page/bounding-box: element ~a disappeared" sel)))672(with-object pg oid673(fn (o)674(call-on pg o675"function(){ this.scrollIntoView({block:'center', inline:'center'}); }")676(quads->box (:quads (cdp/send pg "DOM.getContentQuads" {:objectId o}))))))))677678(define (page/upload pg sel paths . opts-rest)679"Set the files of an <input type=file> matching sel. `paths` is a list of absolute file paths (or one path). Options: :timeout ms."680(let ((opts (if (null? opts-rest) {} (first opts-rest)))681(files (if (string? paths) (list paths) paths)))682(for-each (fn (p)683(when (not (file/exists? p))684(error (format "page/upload: file not found — ~a" p))))685files)686(with-object pg (actionable-object pg sel (opt-timeout opts))687(fn (oid)688(cdp/send pg "DOM.setFileInputFiles" {:files files :objectId oid})))689nil))690691(define (page/select pg sel value . opts-rest)692"Set a <select> and fire input/change events. `value` is an option value string, a list of values (multi-select), or {:label \"visible text\"}. Non-select elements get their value assigned directly. Options: :timeout ms."693(let* ((opts (if (null? opts-rest) {} (first opts-rest)))694(spec (cond ((string? value) {:values (list value)})695((map? value)696(if (:label value)697{:label (:label value)}698(error "page/select: map value must be {:label \"...\"}")))699(else {:values value}))))700(with-object pg (actionable-object pg sel (opt-timeout opts))701(fn (oid)702(call-on pg oid703(format "function(){ const spec = ~a;704if (this.options) {705for (const o of this.options)706o.selected = spec.label != null707? o.text.trim() === spec.label708: spec.values.includes(o.value);709} else {710this.value = spec.values ? spec.values[0] : spec.label;711}712this.dispatchEvent(new Event('input', {bubbles:true}));713this.dispatchEvent(new Event('change', {bubbles:true})); }"714(json/encode spec)))))715nil))716717;; ---------------------------------------------------------------- navigation718719;; In-flight request tracking per session, for :wait-until :networkidle.720;; Handlers install once per session and maintain a set of open request ids.721(define network-inflight (mutable-cell/new {}))722723(define (inflight-update! sid f)724(let ((all (mutable-cell/get network-inflight)))725(mutable-cell/set! network-inflight726(assoc all sid (f (get all sid {}))))))727728(define (ensure-network-counter! pg)729(let ((sid (:session-id pg)))730(when (nil? (get (mutable-cell/get network-inflight) sid))731(inflight-update! sid (fn (s) s))732(cdp/send pg "Network.enable")733(cdp/on! pg "Network.requestWillBeSent"734(fn (ev) (inflight-update! sid735(fn (s) (assoc s (get-in ev [:params :requestId]) #t)))))736(let ((done (fn (ev) (inflight-update! sid737(fn (s) (dissoc s (get-in ev [:params :requestId])))))))738(cdp/on! pg "Network.loadingFinished" done)739(cdp/on! pg "Network.loadingFailed" done)))740nil))741742(define (inflight-count pg)743(count (keys (get (mutable-cell/get network-inflight) (:session-id pg) {}))))744745;; Idle = no in-flight requests, twice in a row with a 500ms pump between —746;; a page holding a connection open (EventSource, WebSocket) never idles.747(define (wait-network-idle pg deadline)748(let loop ()749(when (> (time-ms) deadline)750(error "page/goto: timed out waiting for network idle"))751(if (= 0 (inflight-count pg))752(begin753(cdp/pump pg 500)754(when (> (inflight-count pg) 0) (loop)))755(begin (cdp/pump pg 250) (loop)))))756757(define (wait-navigated pg wait-until timeout)758(cond ((= wait-until :domcontentloaded)759(cdp/wait-event pg "Page.domContentEventFired" {:timeout timeout}))760((= wait-until :load)761(cdp/wait-event pg "Page.loadEventFired" {:timeout timeout}))762((= wait-until :networkidle)763(cdp/wait-event pg "Page.loadEventFired" {:timeout timeout})764(wait-network-idle pg (+ (time-ms) timeout)))765(else (error (format "sema-browser: unknown :wait-until ~a — use :load, :domcontentloaded, or :networkidle" wait-until))))766nil)767768(define (clear-nav-events! pg)769(cdp/clear-events! pg "Page.loadEventFired")770(cdp/clear-events! pg "Page.domContentEventFired"))771772(define (page/goto pg url . opts-rest)773"Navigate to url and wait for it. Options: :timeout ms (default 30000), :wait-until (:load default, :domcontentloaded, or :networkidle — no in-flight requests for 500ms)."774(let ((opts (if (null? opts-rest) {} (first opts-rest))))775(when (= (get opts :wait-until :load) :networkidle)776(ensure-network-counter! pg))777(clear-nav-events! pg)778(let ((r (cdp/send pg "Page.navigate" {:url url})))779(when (:errorText r)780(error (format "page/goto: navigation to ~a failed — ~a" url (:errorText r))))781;; A same-document navigation (e.g. "#anchor") has no loaderId and782;; fires no load event — there is nothing to wait for.783(when (:loaderId r)784(wait-navigated pg (get opts :wait-until :load) (opt-timeout opts)))785nil)))786787;; History entries: current index and the list. Back/forward navigate to the788;; adjacent entry and wait for load (skipping the wait for same-doc entries).789(define (history-step pg delta)790(let* ((h (cdp/send pg "Page.getNavigationHistory"))791(idx (+ (:currentIndex h) delta))792(entries (:entries h)))793(when (or (< idx 0) (>= idx (count entries)))794(error (format "sema-browser: no history entry to go ~a to"795(if (< delta 0) "back" "forward"))))796(cdp/clear-events! pg "Page.loadEventFired")797(cdp/send pg "Page.navigateToHistoryEntry" {:entryId (:id (nth entries idx))})798(try (cdp/wait-event pg "Page.loadEventFired" {:timeout 10000})799(catch e nil)) ; same-document history steps fire no load event800nil))801802(define (page/back pg)803"Go back one entry in the page's history, waiting for the load."804(history-step pg -1))805806(define (page/forward pg)807"Go forward one entry in the page's history, waiting for the load."808(history-step pg 1))809810(define (page/reload pg . opts-rest)811"Reload the page and wait for it. Options: :ignore-cache #t for a hard reload, :timeout ms, :wait-until (as page/goto)."812(let ((opts (if (null? opts-rest) {} (first opts-rest))))813(when (= (get opts :wait-until :load) :networkidle)814(ensure-network-counter! pg))815(clear-nav-events! pg)816(cdp/send pg "Page.reload" {:ignoreCache (get opts :ignore-cache #f)})817(wait-navigated pg (get opts :wait-until :load) (opt-timeout opts))818nil))819820(define (main-frame-id pg)821(get-in (cdp/send pg "Page.getFrameTree") [:frameTree :frame :id]))822823(define (page/set-content pg html)824"Replace the page's document with the given HTML string."825(cdp/send pg "Page.setDocumentContent" {:frameId (main-frame-id pg) :html html})826nil)827828;; ---------------------------------------------------------------- emulation829830(define (page/set-viewport! pg width height . opts-rest)831"Emulate a viewport of width x height CSS pixels. Options: :scale (deviceScaleFactor, default 1), :mobile #t."832(let ((opts (if (null? opts-rest) {} (first opts-rest))))833(cdp/send pg "Emulation.setDeviceMetricsOverride"834{:width width :height height835:deviceScaleFactor (get opts :scale 1)836:mobile (get opts :mobile #f)})837nil))838839(define (page/set-user-agent! pg ua)840"Override the page's User-Agent string for subsequent requests."841(cdp/send pg "Emulation.setUserAgentOverride" {:userAgent ua})842nil)843844(define (page/set-media! pg opts)845"Emulate media features: {:color-scheme \"dark\"|\"light\"} for prefers-color-scheme, {:media \"print\"} for print styles, {:reduced-motion \"reduce\"}. Pass {} to reset."846(let ((features (append847(if (:color-scheme opts)848(list {:name "prefers-color-scheme" :value (:color-scheme opts)})849(list))850(if (:reduced-motion opts)851(list {:name "prefers-reduced-motion" :value (:reduced-motion opts)})852(list)))))853(cdp/send pg "Emulation.setEmulatedMedia"854{:media (get opts :media "") :features features})855nil))856857(define (page/set-offline! pg offline)858"Emulate being offline (#t) or restore connectivity (#f)."859(cdp/send pg "Network.enable")860(cdp/send pg "Network.emulateNetworkConditions"861{:offline offline :latency 0862:downloadThroughput -1 :uploadThroughput -1})863nil)864865(define (page/set-geolocation! pg latitude longitude . opts-rest)866"Override geolocation (and grant the permission). Options: :accuracy meters (default 1)."867(let ((opts (if (null? opts-rest) {} (first opts-rest))))868(cdp/send (:conn pg) "Browser.grantPermissions" {:permissions ["geolocation"]})869(cdp/send pg "Emulation.setGeolocationOverride"870{:latitude latitude :longitude longitude871:accuracy (get opts :accuracy 1)})872nil))873874(define (page/set-timezone! pg timezone-id)875"Override the page's timezone, e.g. \"Europe/Oslo\" or \"America/New_York\"."876(cdp/send pg "Emulation.setTimezoneOverride" {:timezoneId timezone-id})877nil)878879;; ---------------------------------------------------------------- init scripts & console880881(define (page/add-init-script! pg js)882"Run js in every new document before any page script — polyfills, flags, stubs. Applies from the next navigation. Returns an identifier."883(:identifier (cdp/send pg "Page.addScriptToEvaluateOnNewDocument" {:source js})))884885(define (page/track-console! pg)886"Start recording console output and uncaught page errors; read them with page/console."887(cdp/send pg "Runtime.enable")888nil)889890(define (console-arg->string a)891(cond ((not (nil? (:value a))) (format "~a" (:value a)))892((:description a) (:description a))893(else (or (:type a) ""))))894895(define (console-event->map ev)896(cond ((= "Runtime.consoleAPICalled" (:method ev))897{:type (get-in ev [:params :type])898:text (string/join (map console-arg->string (get-in ev [:params :args])) " ")})899((= "Runtime.exceptionThrown" (:method ev))900{:type "error"901:text (let ((d (get-in ev [:params :exceptionDetails])))902(or (:description (:exception d)) (:text d)))})903(else nil)))904905(define (page/console pg)906"Return console messages and uncaught errors recorded since page/track-console!, as {:type :text}, oldest first."907(filter (fn (m) (not (nil? m)))908(map console-event->map (cdp/events pg))))909910(define (page/clear-console! pg)911"Drop the recorded console messages and page errors."912(cdp/clear-events! pg "Runtime.consoleAPICalled")913(cdp/clear-events! pg "Runtime.exceptionThrown")914nil)915916;; ---------------------------------------------------------------- downloads917918;; The download dir is browser-wide (Browser.setDownloadBehavior), so one919;; cell holds the last configured dir. ponytail: a second browser in the same920;; process sharing downloads would need a per-connection registry.921(define download-dir (mutable-cell/new nil))922923(define (page/downloads-to! pg dir)924"Send this browser's downloads to dir (created if missing) and enable download events for page/wait-for-download."925(file/mkdir dir)926(cdp/send (:conn pg) "Browser.setDownloadBehavior"927{:behavior "allow" :downloadPath dir :eventsEnabled #t})928(mutable-cell/set! download-dir dir)929nil)930931(define (page/wait-for-download pg . opts-rest)932"Wait for the next download to finish and return {:path :filename :url}. Call page/downloads-to! first, then trigger the download (a click, a goto). Options: :timeout ms."933(let* ((opts (if (null? opts-rest) {} (first opts-rest)))934(timeout (opt-timeout opts))935(conn (:conn pg))936(begin-ev (cdp/wait-event conn "Browser.downloadWillBegin" {:timeout timeout}))937(guid (get-in begin-ev [:params :guid])))938(cdp/wait-event conn "Browser.downloadProgress"939{:timeout timeout940:pred (fn (ev)941(and (= guid (get-in ev [:params :guid]))942(= "completed" (get-in ev [:params :state]))))})943{:filename (get-in begin-ev [:params :suggestedFilename])944:url (get-in begin-ev [:params :url])945:path (format "~a/~a"946(mutable-cell/get download-dir)947(get-in begin-ev [:params :suggestedFilename]))}))948949;; ---------------------------------------------------------------- cookies950951(define (page/cookies pg)952"Return the cookies visible to the page as maps with :name, :value, :domain, :path, :expires, :httpOnly, :secure."953(:cookies (cdp/send pg "Network.getCookies")))954955(define (page/set-cookie! pg cookie)956"Set one cookie. Map keys: :name and :value (required), plus :url or :domain, :path, :expires (unix seconds), :httpOnly, :secure, :sameSite. Raises when the browser rejects it."957(when (or (nil? (:name cookie)) (nil? (:value cookie)))958(error "page/set-cookie!: cookie needs :name and :value"))959(let ((c (if (or (:url cookie) (:domain cookie))960cookie961(assoc cookie :url (page/url pg)))))962(when (not (:success (cdp/send pg "Network.setCookie" c)))963(error (format "page/set-cookie!: browser rejected cookie ~a" (:name cookie))))964nil))965966(define (page/clear-cookies! pg)967"Delete all browser cookies."968(cdp/send pg "Network.clearBrowserCookies")969nil)970971;; ---------------------------------------------------------------- dialogs972973(define (page/on-dialog! pg action . prompt-rest)974"Auto-respond to alert/confirm/prompt dialogs: action is :accept or :dismiss, with an optional prompt-text answer for prompt(). Registers a handler; returns its id (cdp/off! to remove). Without a handler an open dialog blocks the page's JS."975(let ((accept (= action :accept))976(prompt-text (if (null? prompt-rest) nil (first prompt-rest))))977(cdp/on! pg "Page.javascriptDialogOpening"978(fn (ev)979(cdp/send pg "Page.handleJavaScriptDialog"980(if prompt-text981{:accept accept :promptText prompt-text}982{:accept accept}))))))983984;; ---------------------------------------------------------------- network985986(define (page/track-network! pg)987"Start recording the page's network traffic (enables the Network domain). Events accumulate while commands run; read them with page/requests."988(cdp/send pg "Network.enable")989nil)990991(define (response-event->map ev)992(let ((r (get-in ev [:params :response])))993{:url (:url r)994:status (:status r)995:mime-type (:mimeType r)996:request-id (get-in ev [:params :requestId])997:type (get-in ev [:params :type])}))998999(define (page/requests pg)1000"Return the responses recorded since page/track-network! as maps with :url, :status, :mime-type, :type, :request-id — oldest first."1001(map response-event->map1002(filter (fn (ev) (= "Network.responseReceived" (:method ev)))1003(cdp/events pg))))10041005(define (page/wait-for-response pg url-part . opts-rest)1006"Wait for a response whose URL contains url-part and return it as a map (see page/requests). Requires page/track-network!. Options: :timeout ms."1007(let ((opts (if (null? opts-rest) {} (first opts-rest))))1008(response-event->map1009(cdp/wait-event pg "Network.responseReceived"1010{:timeout (opt-timeout opts)1011:pred (fn (ev)1012(string/contains? (get-in ev [:params :response :url])1013url-part))}))))10141015(define (page/response-body pg request-id)1016"Return the body of a recorded response by its :request-id (from page/requests or page/wait-for-response). Text bodies come back as a string, binary ones as a bytevector. Requires page/track-network!, and the body must still be held by the browser (it is dropped on navigation). Retries briefly while the response is still streaming."1017;; responseReceived fires before the body finishes loading — retry until1018;; loadingFinished has landed (bounded, then surface the real error).1019(let loop ((tries 0))1020(let ((r (try (cdp/send pg "Network.getResponseBody" {:requestId request-id})1021(catch e1022(if (and (< tries 20)1023(string/contains? (:message e) "No data found"))1024:retry1025(raise e))))))1026(if (= r :retry)1027(begin (cdp/pump pg 100) (loop (+ tries 1)))1028(if (:base64Encoded r)1029(base64/decode-bytes (:body r))1030(:body r))))))10311032;; WebSocket traffic rides the same Network events as HTTP. Fold the buffered1033;; events once: creations map request ids to URLs, frame events become rows.1034(define (page/websocket-frames pg)1035"Return WebSocket frames recorded since page/track-network! as {:url :direction (:sent or :received) :opcode :payload}, oldest first."1036(let loop ((evs (cdp/events pg)) (urls {}) (acc (list)))1037(if (null? evs)1038acc1039(let* ((ev (first evs))1040(m (:method ev))1041(rid (get-in ev [:params :requestId])))1042(cond1043((= m "Network.webSocketCreated")1044(loop (rest evs) (assoc urls rid (get-in ev [:params :url])) acc))1045((or (= m "Network.webSocketFrameSent")1046(= m "Network.webSocketFrameReceived"))1047(loop (rest evs) urls1048(append acc1049(list {:url (get urls rid)1050:direction (if (= m "Network.webSocketFrameSent")1051:sent :received)1052:opcode (get-in ev [:params :response :opcode])1053:payload (get-in ev [:params :response :payloadData])}))))1054(else (loop (rest evs) urls acc)))))))10551056;; ---------------------------------------------------------------- profiling10571058(define (page/set-cpu-throttle! pg rate)1059"Slow the page's CPU by a factor (2 = half speed). 1 restores full speed."1060(cdp/send pg "Emulation.setCPUThrottlingRate" {:rate rate})1061nil)10621063(define (page/start-js-coverage! pg)1064"Start collecting JS coverage; navigate/run the code, then read it with page/stop-js-coverage."1065(cdp/send pg "Profiler.enable")1066(cdp/send pg "Profiler.startPreciseCoverage" {:callCount #f :detailed #f})1067nil)10681069;; Approximation: total = the largest end offset seen; used = total minus the1070;; spans of functions that never ran. Function ranges overlap (the top-level1071;; script encloses every function), so summing executed ranges would double1072;; count — subtracting the dead ones does not, except for functions nested1073;; inside other dead functions. Good for "how much of this file ran", not a1074;; substitute for exact line coverage.1075(define (script-coverage script)1076(let* ((ranges (foldl (fn (acc f) (append acc (:ranges f)))1077(list)1078(:functions script)))1079(total (foldl (fn (acc r) (max acc (:endOffset r))) 0 ranges))1080(dead (foldl (fn (acc r)1081(if (= (:count r) 0)1082(+ acc (- (:endOffset r) (:startOffset r)))1083acc))10840 ranges)))1085{:url (:url script)1086:used-bytes (max 0 (- total dead))1087:total-bytes total}))10881089(define (page/stop-js-coverage pg)1090"Stop coverage collection and return per-script {:url :used-bytes :total-bytes} (byte counts are an approximation from executed function ranges)."1091(let ((result (:result (cdp/send pg "Profiler.takePreciseCoverage"))))1092(cdp/send pg "Profiler.stopPreciseCoverage")1093(cdp/send pg "Profiler.disable")1094(map script-coverage1095(filter (fn (s) (not (= "" (or (:url s) "")))) result))))10961097;; ---------------------------------------------------------------- clipboard10981099(define (grant-clipboard! pg)1100(cdp/send (:conn pg) "Browser.grantPermissions"1101{:permissions ["clipboardReadWrite" "clipboardSanitizedWrite"]}))11021103(define (page/clipboard-write! pg text)1104"Write text to the clipboard (grants the permission). Requires a secure context — localhost or https, not data: URLs."1105(grant-clipboard! pg)1106(page/eval pg (format "navigator.clipboard.writeText(~a).then(() => true)"1107(json/encode text)))1108nil)11091110(define (page/clipboard-read pg)1111"Read the clipboard's text (grants the permission). Requires a secure context — localhost or https, not data: URLs."1112(grant-clipboard! pg)1113(page/eval pg "navigator.clipboard.readText()"))11141115;; ---------------------------------------------------------------- devices11161117(define device-presets1118{"iPhone 14"1119{:width 390 :height 844 :scale 3 :mobile #t1120:ua "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1"}1121"Pixel 7"1122{:width 412 :height 915 :scale 2.625 :mobile #t1123:ua "Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Mobile Safari/537.36"}1124"iPad Mini"1125{:width 768 :height 1024 :scale 2 :mobile #t1126:ua "Mozilla/5.0 (iPad; CPU OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1"}1127"Desktop 1080p"1128{:width 1920 :height 1080 :scale 1 :mobile #f1129:ua "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36"}})11301131(define (browser/devices)1132"List the device preset names usable with page/emulate-device!."1133(keys device-presets))11341135(define (page/emulate-device! pg name)1136"Emulate a device preset by name — viewport, scale, mobile flag, and User-Agent. See browser/devices for the names."1137(let ((d (get device-presets name)))1138(when (nil? d)1139(error (format "page/emulate-device!: unknown device ~a — known: ~a"1140name (string/join (keys device-presets) ", "))))1141(page/set-viewport! pg (:width d) (:height d)1142{:scale (:scale d) :mobile (:mobile d)})1143(page/set-user-agent! pg (:ua d))1144nil))11451146;; ---------------------------------------------------------------- screencast11471148;; Frames only arrive while the connection pumps (any page/* call or1149;; cdp/pump), and each one must be acked or Chrome stops sending more.1150(define (page/start-screencast! pg dir)1151"Record the page as numbered PNG frames into dir (created if missing) until page/stop-screencast!. Frames arrive while commands run — use (cdp/pump pg ms) to capture during idle stretches. Returns a handle for page/stop-screencast!."1152(file/mkdir dir)1153(let* ((counter (mutable-cell/new 0))1154(hid (cdp/on! pg "Page.screencastFrame"1155(fn (ev)1156(let ((n (mutable-cell/get counter)))1157(mutable-cell/set! counter (+ n 1))1158(file/write-bytes1159(format "~a/frame-~a.png" dir (+ 100000 n))1160(base64/decode-bytes (get-in ev [:params :data]))))1161(cdp/send pg "Page.screencastFrameAck"1162{:sessionId (get-in ev [:params :sessionId])})))))1163(cdp/send pg "Page.startScreencast" {:format "png"})1164{:handler-id hid :dir dir}))11651166(define (page/stop-screencast! pg handle)1167"Stop a screencast from page/start-screencast! and return the written frame paths, in order."1168(cdp/send pg "Page.stopScreencast")1169(cdp/off! pg (:handler-id handle))1170(sort (filter (fn (p) (string/contains? p "frame-"))1171(map (fn (f) (format "~a/~a" (:dir handle) f))1172(file/list (:dir handle))))))11731174;; ---------------------------------------------------------------- frames11751176(define (flatten-frames node parent-id acc)1177(let* ((f (:frame node))1178(acc2 (append acc (list {:id (:id f)1179:url (:url f)1180:name (or (:name f) "")1181:parent parent-id}))))1182(foldl (fn (a child) (flatten-frames child (:id f) a))1183acc21184(or (:childFrames node) (list)))))11851186(define (page/frames pg)1187"List the page's frames as maps with :id, :url, :name, :parent (nil for the main frame)."1188(flatten-frames (:frameTree (cdp/send pg "Page.getFrameTree")) nil (list)))11891190(define (frame-matches? f spec)1191(or (= spec (:id f))1192(= spec (:name f))1193(string/contains? (:url f) spec)))11941195(define (page/frame pg spec)1196"Return a frame handle for the child frame whose id, name, or URL (substring) matches spec. The handle works like a page for selector actions, page/eval, page/text, page/click, page/fill, page/snapshot, refs, ... — all scoped to that frame. Cross-origin frames that Chrome isolates into their own process (OOPIFs) are not in this page's tree; adopt those via browser/pages."1197(let ((match (first (filter (fn (f) (and (:parent f) (frame-matches? f spec)))1198(page/frames pg)))))1199(when (nil? match)1200(error (format "page/frame: no child frame matching ~a — frames: ~a"1201spec (map (fn (f) (:url f)) (page/frames pg)))))1202(assoc pg :frame-id (:id match) :ctx-cell (mutable-cell/new nil))))12031204(define (page/eval-in-frame pg frame-id js)1205"Evaluate a JS expression inside a specific frame by id (see page/frames) and return its value. Runs in an isolated world, so it sees the frame's DOM but not its page-script variables."1206(page/eval (assoc pg :frame-id frame-id :ctx-cell (mutable-cell/new nil)) js))12071208;; ---------------------------------------------------------------- interception1209;;1210;; Fetch-domain request interception. One interceptor at a time per page:1211;; the handler sees every request before it leaves and decides its fate.1212;; Decisions are made while the connection pumps (during any page/* call),1213;; the same way cdp/on! handlers run.12141215(define (headers->list headers)1216(map (fn (k) {:name (if (keyword? k) (keyword/to-string k) k)1217:value (get headers k)})1218(keys headers)))12191220(define (respond-to-request! pg request-id action)1221(cond1222((or (nil? action) (= action :continue))1223(cdp/send pg "Fetch.continueRequest" {:requestId request-id}))1224((= action :abort)1225(cdp/send pg "Fetch.failRequest" {:requestId request-id1226:errorReason "BlockedByClient"}))1227((map? action)1228(cond1229((:fulfill action)1230(let ((f (:fulfill action)))1231(cdp/send pg "Fetch.fulfillRequest"1232{:requestId request-id1233:responseCode (get f :status 200)1234:responseHeaders (headers->list (get f :headers {}))1235:body (base64/encode (get f :body ""))})))1236((:continue action)1237(let* ((c (:continue action))1238(base {:requestId request-id})1239(base (if (:url c) (assoc base :url (:url c)) base))1240(base (if (:method c) (assoc base :method (:method c)) base))1241(base (if (:headers c)1242(assoc base :headers (headers->list (:headers c)))1243base))1244(base (if (:post-data c)1245(assoc base :postData (base64/encode (:post-data c)))1246base)))1247(cdp/send pg "Fetch.continueRequest" base)))1248(else1249(error "page/on-request!: handler returned a map without :fulfill or :continue"))))1250(else1251(error (format "page/on-request!: handler must return :continue, :abort, {:fulfill ...}, or {:continue ...} — got ~a" action)))))12521253(define (page/on-request! pg handler)1254"Intercept every request the page makes. The handler receives {:url :method :resource-type :headers :request-id} and returns :continue (or nil) to let it through, :abort to block it, {:fulfill {:status :headers :body}} to answer it without the network, or {:continue {:url :method :headers :post-data}} to rewrite it. Returns an interceptor id for page/stop-intercept!. One interceptor per page — stop the old one first."1255(cdp/send pg "Fetch.enable" {:patterns [{:urlPattern "*"}]})1256(cdp/on! pg "Fetch.requestPaused"1257(fn (ev)1258(let* ((p (:params ev))1259(req {:request-id (:requestId p)1260:url (get-in p [:request :url])1261:method (get-in p [:request :method])1262:headers (get-in p [:request :headers])1263:resource-type (:resourceType p)}))1264;; A handler error must not leave the request hanging forever.1265(try (respond-to-request! pg (:requestId p) (handler req))1266(catch e1267(try (cdp/send pg "Fetch.continueRequest"1268{:requestId (:requestId p)})1269(catch e2 nil))1270(raise e)))))))12711272(define (page/block! pg patterns)1273"Block every request whose URL contains any of the given substrings; everything else continues. Returns an interceptor id for page/stop-intercept!."1274(let ((pats (if (string? patterns) (list patterns) patterns)))1275(page/on-request! pg1276(fn (req)1277(if (first (filter (fn (p) (string/contains? (:url req) p)) pats))1278:abort1279:continue)))))12801281(define (page/authenticate! pg username password)1282"Answer HTTP basic/proxy auth challenges with these credentials. Returns an interceptor id for page/stop-intercept!. Owns the Fetch domain like page/on-request! — the two are mutually exclusive until stopped. A challenge the credentials already failed once is cancelled rather than re-answered, so a wrong password fails instead of looping."1283(cdp/send pg "Fetch.enable" {:handleAuthRequests #t :patterns [{:urlPattern "*"}]})1284(let ((answered (mutable-cell/new {}))1285(pass-id (cdp/on! pg "Fetch.requestPaused"1286(fn (ev)1287(try (cdp/send pg "Fetch.continueRequest"1288{:requestId (get-in ev [:params :requestId])})1289(catch e nil))))))1290(let ((auth-id (cdp/on! pg "Fetch.authRequired"1291(fn (ev)1292(let ((rid (get-in ev [:params :requestId])))1293(if (get (mutable-cell/get answered) rid)1294(cdp/send pg "Fetch.continueWithAuth"1295{:requestId rid1296:authChallengeResponse {:response "CancelAuth"}})1297(begin1298(mutable-cell/set! answered1299(assoc (mutable-cell/get answered) rid #t))1300(cdp/send pg "Fetch.continueWithAuth"1301{:requestId rid1302:authChallengeResponse1303{:response "ProvideCredentials"1304:username username1305:password password}}))))))))1306(list pass-id auth-id))))13071308(define (page/stop-intercept! pg interceptor-id)1309"Remove an interceptor from page/on-request!, page/block!, or page/authenticate! (a single id or a list of ids) and stop intercepting."1310(for-each (fn (id) (cdp/off! pg id))1311(if (list? interceptor-id) interceptor-id (list interceptor-id)))1312(cdp/send pg "Fetch.disable")1313nil)13141315;; ---------------------------------------------------------------- capture13161317(define (page/screenshot pg . opts-rest)1318"Capture a screenshot as PNG bytes. Options: :path (write to file and return the path instead), :format (\"png\" default, \"jpeg\", \"webp\"), :quality (0-100, jpeg/webp), :full-page (capture beyond the viewport), :selector (capture just that element)."1319(let* ((opts (if (null? opts-rest) {} (first opts-rest)))1320(params (assoc (if (get opts :quality)1321{:quality (get opts :quality)}1322{})1323:format (get opts :format "png")1324:captureBeyondViewport (get opts :full-page #f)))1325(params (if (get opts :selector)1326(assoc params :clip1327(assoc (page/bounding-box pg (get opts :selector)1328{:timeout (opt-timeout opts)})1329:scale 1))1330params))1331(r (cdp/send pg "Page.captureScreenshot" params))1332(bytes (base64/decode-bytes (:data r))))1333(if (get opts :path)1334(begin (file/write-bytes (get opts :path) bytes) (get opts :path))1335bytes)))13361337(define (page/pdf pg . opts-rest)1338"Print the page to PDF (headless only). Returns the bytes, or writes to :path and returns the path. Options: :path, :landscape #t, :scale (0.1-2), :page-ranges (\"1-3\")."1339(let* ((opts (if (null? opts-rest) {} (first opts-rest)))1340(params (foldl (fn (m kv)1341(if (nil? (first (rest kv))) m (apply assoc m kv)))1342{:landscape (get opts :landscape #f)}1343(list (list :scale (get opts :scale))1344(list :pageRanges (get opts :page-ranges)))))1345(bytes (base64/decode-bytes (:data (cdp/send pg "Page.printToPDF" params)))))1346(if (get opts :path)1347(begin (file/write-bytes (get opts :path) bytes) (get opts :path))1348bytes)))13491350;; ---------------------------------------------------------------- snapshot (agent-facing)1351;;1352;; page/snapshot renders the accessibility tree the way a screen reader sees1353;; the page: one line per node, "- role \"name\" [ref=eNNN]". The ref is the1354;; element's backend DOM node id — pass it to page/click-ref / page/fill-ref1355;; to act on it. Orders of magnitude smaller than HTML; grep it, don't parse it.13561357(define always-skip-roles {"InlineTextBox" #t "LineBreak" #t})1358(define anonymous-skip-roles {"none" #t "generic" #t})13591360(define (ax-value node key)1361(get (or (get node key) {}) :value ""))13621363;; Skip nodes that add no information: layout wrappers with no name, and text1364;; leaves that just repeat their parent's accessible name.1365(define (ax-line node depth parent-name)1366(let ((role (ax-value node :role))1367(name (ax-value node :name))1368(ref (:backendDOMNodeId node)))1369(cond ((get always-skip-roles role) nil)1370((and (get anonymous-skip-roles role) (= name "")) nil)1371((and (= role "StaticText") (= name parent-name)) nil)1372(else1373(string/join1374(list (string/join (map (fn (_) " ") (range depth)) "")1375"- " role1376(if (= name "") "" (format " ~s" name))1377(if (nil? ref) "" (format " [ref=e~a]" ref)))1378"")))))13791380(define (render-ax by-id node depth parent-name acc)1381(let* ((name (ax-value node :name))1382(line (if (:ignored node) nil (ax-line node depth parent-name)))1383(next-depth (if (nil? line) depth (+ depth 1)))1384(next-parent (if (nil? line) parent-name name))1385(acc2 (if (nil? line) acc (append acc (list line)))))1386(let loop ((ids (or (:childIds node) (list))) (a acc2))1387(if (null? ids)1388a1389(loop (rest ids)1390(let ((child (get by-id (first ids))))1391(if (nil? child) a (render-ax by-id child next-depth next-parent a))))))))13921393(define (page/snapshot pg)1394"Render the page's accessibility tree as compact text, one node per line with a [ref=eNNN] handle usable with page/click-ref and page/fill-ref. On a frame handle, renders that frame's tree."1395(cdp/send pg "Accessibility.enable")1396(let* ((nodes (:nodes (cdp/send pg "Accessibility.getFullAXTree"1397(if (:frame-id pg)1398{:frameId (:frame-id pg)}1399{}))))1400(by-id (foldl (fn (m n) (assoc m (:nodeId n) n)) {} nodes)))1401(if (null? nodes)1402""1403(string/join (render-ax by-id (first nodes) 0 "" (list)) "\n"))))14041405(define (ref-object pg ref)1406(let ((bid (string->number (substring ref 1 (string-length ref)))))1407(:objectId (:object (cdp/send pg "DOM.resolveNode" {:backendNodeId bid})))))14081409(define (page/click-ref pg ref)1410"Click the element behind a [ref=eNNN] handle from page/snapshot."1411(with-object pg (ref-object pg ref) (fn (oid) (click-object pg oid {}))))14121413(define (page/fill-ref pg ref text)1414"Fill the element behind a [ref=eNNN] handle from page/snapshot."1415(with-object pg (ref-object pg ref) (fn (oid) (fill-object pg oid text)))))