From e49c10ed7c96e285bfa930b936ba113e5fd64d60 Mon Sep 17 00:00:00 2001 From: Nathan Fallet Date: Thu, 19 Nov 2026 10:32:55 +0100 Subject: [PATCH 01/16] perf: opt-in lookups run by the page instead of reading the whole document With Config.lookupsInPage (off by default), select, selectAll, querySelector and querySelectorAll without a node ask the page to run document.querySelector / querySelectorAll (Runtime.evaluate) and describe only the matches (DOM.describeNode, depth -1, pierce), instead of reading the whole document (DOM.getDocument, depth -1, pierce) and querying it. - The selector enters the script only as a JSON string literal. - The element keeps the remote object of the lookup, so its first call needs no DOM.resolveNode; it carries no node id nor tree until update(). - Waiting, timeouts and errors keep their behaviour: an invalid selector throws the page's SyntaxError as an EvaluateException. - Lookups under a node or an element, find and findAll are unchanged. - KDoc of the setting, README and quickstart list every difference between on and off. --- README.md | 2 + .../kotlin/dev/kdriver/core/browser/Config.kt | 40 ++ .../dev/kdriver/core/browser/ConfigBuilder.kt | 7 + .../dev/kdriver/core/dom/DefaultElement.kt | 9 + .../kotlin/dev/kdriver/core/tab/DefaultTab.kt | 71 +++- .../kotlin/dev/kdriver/core/tab/Tab.kt | 12 + .../dev/kdriver/core/browser/ConfigTest.kt | 11 + .../core/tab/LookupsInPageBehaviourTest.kt | 132 +++++++ .../dev/kdriver/core/tab/LookupsInPageTest.kt | 351 ++++++++++++++++++ docs/home/quickstart.md | 37 ++ 10 files changed, 670 insertions(+), 2 deletions(-) create mode 100644 core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt create mode 100644 core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt diff --git a/README.md b/README.md index dbdf2a057..77f743e13 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,8 @@ to heavy tools like Selenium or Puppeteer — all without relying on WebDriver. * **No external dependencies** – kdriver interacts directly with the browser using WebSockets and JSON — no need for Chromium wrappers or native libraries. * **Session and cookie management** – Start with a clean profile every time or load/save cookies between runs. +* **Remote browsers** – Attach to a browser behind a reverse proxy, and, with `lookupsInPage`, look elements up without + transferring the whole document (see [the quickstart](docs/home/quickstart.md#lookups-on-a-remote-browser)). * **Element utilities** – Coming soon: intuitive APIs to query, interact with, and wait for DOM elements. ## Motivation diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt index a0eed7272..72d820c19 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt @@ -48,6 +48,42 @@ class Config( * in front of the browser, e.g. `mapOf("Authorization" to "Bearer …")`. Empty by default. */ val connectionHeaders: Map = emptyMap(), + /** + * Whether a CSS selector lookup on the whole page asks the page itself instead of reading the whole document. + * + * Concerns [dev.kdriver.core.tab.Tab.select], [dev.kdriver.core.tab.Tab.selectAll], + * [dev.kdriver.core.tab.Tab.querySelector] and [dev.kdriver.core.tab.Tab.querySelectorAll] called without a node. + * Off (the default), each of these reads the whole document (`DOM.getDocument`, depth -1, piercing) whenever the + * page changed since the last read, which is after every navigation and on any live page, then queries it by node + * id. On a large page that is a transfer of the size of the whole DOM (often a megabyte) per lookup. + * + * On, the page runs the selector (`Runtime.evaluate` of `document.querySelector` / `querySelectorAll`, the + * selector passed as a JSON string literal) and only the match is described (`DOM.describeNode`, depth -1, + * piercing). What changes for the caller: + * + * - **Elements**: they carry their node and its subtree (so [dev.kdriver.core.dom.Element.text], + * [dev.kdriver.core.dom.Element.textAll], attributes and children read the same), but no node id + * (`node.nodeId` is 0) and no [dev.kdriver.core.dom.Element.tree]: [dev.kdriver.core.dom.Element.parent] + * throws until [dev.kdriver.core.dom.Element.update] is called, which reads the document as before. Each element + * keeps the remote object the page returned, so its first call (`click`, `apply`, …) needs no `DOM.resolveNode`. + * - **Shadow DOM and iframes**: same results as off: neither `document.querySelector` nor `DOM.querySelector` on + * the document looks inside a shadow root or an iframe. `selectAll(includeFrames = true)` still finds the iframes + * in the page, then reads the document to search inside each one. + * - **Waiting**: `select` and `selectAll` poll and time out as before. Until something reads the document again + * (a lookup under an element, `find`, `update`…), the browser sends no `DOM.*` mutation events for the page, so + * on a busy page the connection may count as idle sooner. + * - **Errors**: an invalid selector throws an [dev.kdriver.core.exceptions.EvaluateException] (the page's + * `SyntaxError`) instead of a [dev.kdriver.cdp.CDPException]. The page's own `document.querySelector` is used: + * a page that replaces it changes the result. + * - **Round trips**: `querySelector` costs two small ones (evaluate, describe) instead of a document read and a + * query; `querySelectorAll` costs one when nothing matches, three otherwise (evaluate, the array's properties, + * then every match described in parallel). Each match is described with its subtree: many matches, or nested + * ones, can transfer more than the document would. + * + * Lookups under a node or an element ([dev.kdriver.core.dom.Element.querySelector], `find`, `findAll`, `xpath`) + * are unchanged and still read the document. Off by default. + */ + val lookupsInPage: Boolean = Defaults.LOOKUPS_IN_PAGE, ) { private val logger = KtorSimpleLogger("Config") @@ -168,6 +204,7 @@ class Config( debugStringLimit = debugStringLimit, browserUrl = browserUrl, connectionHeaders = connectionHeaders, + lookupsInPage = lookupsInPage, ).also { copy -> // Copy the backing field, never the userDataDir getter: reading it would materialise a // temporary profile directory on a config that may never be started. @@ -214,6 +251,9 @@ class Config( const val IDLE_WAIT_TIMEOUT: Long = 10_000 const val AUTO_DISCOVER_TARGETS: Boolean = true const val DEBUG_STRING_LIMIT: Int = 128 + + /** See [Config.lookupsInPage]: off by default, lookups read the whole document. */ + const val LOOKUPS_IN_PAGE: Boolean = false } } diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/ConfigBuilder.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/ConfigBuilder.kt index 9371a2a34..cbd32082d 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/ConfigBuilder.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/ConfigBuilder.kt @@ -47,6 +47,12 @@ class ConfigBuilder { */ var connectionHeaders: Map = emptyMap() + /** + * Whether selector lookups on the whole page ask the page instead of reading the whole document. See + * [Config.lookupsInPage] for what changes. + */ + var lookupsInPage: Boolean = Defaults.LOOKUPS_IN_PAGE + /** * Builds the Config instance with the configured parameters. */ @@ -70,6 +76,7 @@ class ConfigBuilder { debugStringLimit = debugStringLimit, browserUrl = browserUrl, connectionHeaders = connectionHeaders, + lookupsInPage = lookupsInPage, ) } } diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt b/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt index ec98cef4c..342539df8 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt @@ -90,6 +90,15 @@ open class DefaultElement( override val attrs: List get() = node.attributes?.chunked(2)?.map { it.first() } ?: emptyList() + /** + * Keeps [found], the remote object a lookup in the page already returned for [node], so that the first call on this + * element needs no `DOM.resolveNode`. Calls fall back on resolving the node again when the browser rejects it. + */ + internal fun keepRemoteObject(found: Runtime.RemoteObject) { + remoteObject = found + remoteObjectBackendNodeId = node.backendNodeId + } + override suspend fun updateRemoteObject(): Runtime.RemoteObject? { val resolvedFor = backendNodeId remoteObject = tab.dom.resolveNode(backendNodeId = resolvedFor).`object` diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt index 3cc9ead1c..c2abc7108 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt @@ -26,6 +26,7 @@ import kotlinx.coroutines.delay import kotlinx.io.buffered import kotlinx.io.files.Path import kotlinx.io.files.SystemFileSystem +import kotlinx.serialization.builtins.serializer import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.decodeFromJsonElement import kotlin.concurrent.Volatile @@ -443,9 +444,73 @@ open class DefaultTab( selector: String, node: NodeOrElement?, ): List = - if (node == null) onDocument { doc -> querySelectorAllInternal(selector, null, retried = false, doc) } + if (node == null && lookupsInPage) querySelectorAllInPage(selector) + else if (node == null) onDocument { doc -> querySelectorAllInternal(selector, null, retried = false, doc) } else querySelectorAllInternal(selector, node, retried = false, rootOf(node)) + // Config.lookupsInPage of the browser this tab belongs to; off for a tab without one. + private val lookupsInPage: Boolean + get() = owner?.let { browser -> browser.config.lookupsInPage } == true + + /** + * `document.querySelectorAll(selector)` run by the page, each match then described with its subtree: see + * [dev.kdriver.core.browser.Config.lookupsInPage]. One round trip when nothing matches (the page answers `null`), + * otherwise three: the evaluation, the array's own properties, and the descriptions, sent together. + */ + private suspend fun querySelectorAllInPage(selector: String): List { + val array = evaluateLookup( + "(() => { const all = Array.from(document.querySelectorAll(${jsStringLiteral(selector)}));" + + " return all.length ? all : null; })()" + ) ?: return emptyList() + val matches = runtime.getProperties(objectId = array.objectId!!, ownProperties = true).result + .mapNotNull { property -> property.name.toIntOrNull()?.let { index -> index to property.value } } + .sortedBy { it.first } + .mapNotNull { (_, value) -> value?.takeIf { it.objectId != null } } + return coroutineScope { + matches.map { match -> async { describeMatch(match) } }.awaitAll().filterNotNull() + } + } + + /** + * `document.querySelector(selector)` run by the page, the match then described with its subtree: see + * [dev.kdriver.core.browser.Config.lookupsInPage]. Two round trips when something matches, one otherwise. + */ + private suspend fun querySelectorInPage(selector: String): Element? { + val match = evaluateLookup("document.querySelector(${jsStringLiteral(selector)})") ?: return null + return describeMatch(match) + } + + /** + * Evaluates [expression] in the page and returns the object it yields, or null when it yields no object (`null`). + * An exception thrown by the page (an invalid selector) is thrown as an [EvaluateException]. + */ + private suspend fun evaluateLookup(expression: String): Runtime.RemoteObject? { + val evaluated = runtime.evaluate(expression = expression) + evaluated.exceptionDetails?.let { throw EvaluateException(it) } + return evaluated.result.takeIf { it.objectId != null } + } + + /** + * The element of [match], a remote object the page returned: its node and subtree (`DOM.describeNode`, depth -1, + * piercing), with [match] kept so its first call needs no `DOM.resolveNode`. Null when the browser no longer knows + * the object (the page navigated in between): the match is gone, and `select` tries again as for no match. + */ + private suspend fun describeMatch(match: Runtime.RemoteObject): Element? { + val node = try { + dom.describeNode(objectId = match.objectId, depth = -1, pierce = true).node + } catch (e: CancellationException) { + throw e + } catch (_: CDPException) { + return null + } + return DefaultElement(this, node).also { it.keepRemoteObject(match) } + } + + // A JavaScript string literal for [value]: its JSON encoding, which escapes quotes, backslashes and control + // characters, so the value can only ever be read as one string. + private fun jsStringLiteral(value: String): String = + Serialization.json.encodeToString(String.serializer(), value) + // `retried` carries the "already retried once" state across the recursive call. It must be a // parameter, not a local: a local would be reset on every recursion and the guard would never // trip, recursing without bound on a persistent "could not find node" (ISSUE-7). @@ -486,7 +551,9 @@ open class DefaultTab( node: NodeOrElement?, ): Element? { val trimmedSelector = selector.trim() - return if (node == null) { + return if (node == null && lookupsInPage) { + querySelectorInPage(trimmedSelector) + } else if (node == null) { onDocument { doc -> querySelectorInternal(trimmedSelector, null, retried = false, doc) } } else { querySelectorInternal(trimmedSelector, node, retried = false, rootOf(node)) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt b/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt index e8b74fd6a..57b650c7a 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt @@ -294,6 +294,9 @@ interface Tab : Connection { * * This method waits for the element to appear in the DOM, retrying every 500 milliseconds until the timeout is reached. * + * With [dev.kdriver.core.browser.Config.lookupsInPage], the page runs the selector instead of the whole document + * being read; the elements then carry no node id nor tree. See that setting for every difference. + * * @param selector The CSS selector of the element to select. * @param timeout The maximum time in milliseconds to wait for the element to appear. Defaults to 10 seconds. * @@ -329,6 +332,9 @@ interface Tab : Connection { * * Can also be used to wait for such elements to appear. Optionally includes results from iframes. * + * With [dev.kdriver.core.browser.Config.lookupsInPage], the page runs the selector instead of the whole document + * being read; the elements then carry no node id nor tree. See that setting for every difference. + * * @param selector CSS selector, e\.g\., `a[href]`, `button[class*=close]`, `a > img[src]` * @param timeout Raise timeout exception when after this many milliseconds nothing is found. * @param includeFrames Whether to include results in iframes. @@ -375,6 +381,9 @@ interface Tab : Connection { * * It returns all matching [Element] objects. * + * With [dev.kdriver.core.browser.Config.lookupsInPage], the page runs the selector instead of the whole document + * being read; the elements then carry no node id nor tree. See that setting for every difference. + * * @param selector CSS selector. (first time? See https://www.w3schools.com/cssref/css_selectors.php) * @param node For internal use. The node to start the search from. Defaults to the document root. * @@ -388,6 +397,9 @@ interface Tab : Connection { /** * Finds a single element based on a CSS selector string. * + * With [dev.kdriver.core.browser.Config.lookupsInPage], the page runs the selector instead of the whole document + * being read; the elements then carry no node id nor tree. See that setting for every difference. + * * @param selector CSS selector(s). * @param node For internal use. The node to start the search from. Defaults to the document root. * diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/ConfigTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/ConfigTest.kt index 87b7a4a19..1b925f782 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/ConfigTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/ConfigTest.kt @@ -184,4 +184,15 @@ class ConfigTest { assertTrue(args.contains("--disable-site-isolation-trials")) } + @Test + fun lookupsInPage_isOffByDefault_andKeptByCopyAndTheBuilder() { + assertFalse(Config(browserExecutablePath = Path("/usr/bin/chromium")).lookupsInPage) + + val on = Config(browserExecutablePath = Path("/usr/bin/chromium"), lookupsInPage = true) + assertTrue(on.copy().lookupsInPage) + + assertTrue(config { browserExecutablePath = Path("/usr/bin/chromium"); lookupsInPage = true }.lookupsInPage) + assertFalse(config { browserExecutablePath = Path("/usr/bin/chromium") }.lookupsInPage) + } + } diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt new file mode 100644 index 000000000..0ebd17be4 --- /dev/null +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt @@ -0,0 +1,132 @@ +package dev.kdriver.core.tab + +import dev.kdriver.cdp.CDPException +import dev.kdriver.core.browser.Browser +import dev.kdriver.core.browser.createBrowser +import dev.kdriver.core.exceptions.EvaluateException +import dev.kdriver.core.exceptions.TimeoutWaitingForElementException +import dev.kdriver.core.sampleFile +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.runBlocking +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * On a real page, the same lookups with [dev.kdriver.core.browser.Config.lookupsInPage] off and on find the same + * elements, with the same text, attributes, children and order, the same absence inside shadow roots and frames, and + * elements that can be clicked; what differs is documented on the setting (no node id, no tree, the error type). + */ +class LookupsInPageBehaviourTest { + + private fun onPage(lookupsInPage: Boolean, block: suspend Tab.() -> T): T = runBlocking { + val browser: Browser = createBrowser(this as CoroutineScope) { + headless = true + sandbox = false + this.lookupsInPage = lookupsInPage + } + try { + browser.get(sampleFile("lookup-test.html")).block() + } finally { + browser.stop() + } + } + + /** Runs [block] with the setting off then on, and checks both give the same answer. */ + private fun sameInBothModes(block: suspend Tab.() -> T): T { + val off = onPage(lookupsInPage = false, block) + val on = onPage(lookupsInPage = true, block) + assertEquals(off, on) + return on + } + + @Test + fun select_findsTheSameElement() { + val seen = sameInBothModes { + val item = select("li[data-rank='2']", timeout = 5_000) + listOf(item.tag, item.text, item.textAll, item["data-rank"], item.attrs.joinToString()) + } + assertEquals(listOf("li", "Beta", "Beta", "2", "class, data-rank"), seen) + } + + @Test + fun select_findsTheSameChildren() { + val seen = sameInBothModes { select("#list", timeout = 5_000).children.filter { it.tag == "li" }.map { it.text } } + assertEquals(listOf("Alpha", "Beta", "Gamma"), seen) + } + + @Test + fun selectAll_findsTheSameElements_inTheSameOrder() { + val seen = sameInBothModes { selectAll(".item", timeout = 5_000).map { it.text to (it.backendNodeId > 0) } } + assertEquals(listOf("Alpha" to true, "Beta" to true, "Gamma" to true), seen) + } + + @Test + fun querySelectorAll_returnsNothing_forNoMatch() { + assertEquals(emptyList(), sameInBothModes { querySelectorAll(".nowhere").map { it.text } }) + assertNull(sameInBothModes { querySelector(".nowhere")?.text }) + } + + @Test + fun select_doesNotPierceShadowRoots_inEitherMode() { + sameInBothModes { + assertFailsWith { select("#shadowed", timeout = 0) } + querySelectorAll("#shadowed").size + } + } + + @Test + fun select_doesNotLookInsideFrames_butSelectAllWithFramesDoes_inEitherMode() { + val seen = sameInBothModes { + assertNull(querySelector("p.inner")) + selectAll("p.inner", timeout = 5_000, includeFrames = true).map { it.text } + } + assertEquals(listOf("Inside the frame"), seen) + } + + @Test + fun aFoundElementCanBeClickedAndRead_inEitherMode() { + val seen = sameInBothModes { + rawEvaluate("document.getElementById('panel').onclick = () => document.getElementById('panel').dataset.state = 'open'") + select("#panel", timeout = 5_000).click() + select("#panel", timeout = 5_000)["data-state"] + } + assertEquals("open", seen) + } + + @Test + fun select_seesTheNewDocumentAfterANavigation_inEitherMode() { + val seen = sameInBothModes { + rawEvaluate("document.getElementById('title').textContent = 'Changed'") + val before = select("#title", timeout = 5_000).text + reload() + before to select("#title", timeout = 5_000).text + } + assertEquals("Changed" to "Lookup", seen) + } + + @Test + fun withTheSettingOn_anElementHasNoTreeUntilUpdated() = onPage(lookupsInPage = true) { + val item = select("li[data-rank='3']", timeout = 5_000) + assertNull(item.tree) + assertEquals(0, item.node.nodeId) + assertNotNull(item.objectId, "the element keeps the object the page returned") + assertFailsWith { item.parent } + + item.update() + + assertNotNull(item.tree) + assertEquals("ul", item.parent?.tag) + } + + @Test + fun anInvalidSelector_throwsTheBrowserErrorOff_andThePageErrorOn() { + onPage(lookupsInPage = false) { assertFailsWith { select("li[", timeout = 0) } } + val error = onPage(lookupsInPage = true) { assertFailsWith { select("li[", timeout = 0) } } + assertTrue(error.jsError.contains("SyntaxError"), error.jsError) + } + +} diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt new file mode 100644 index 000000000..bed9ab0a0 --- /dev/null +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt @@ -0,0 +1,351 @@ +@file:OptIn(dev.kdriver.cdp.InternalCdpApi::class) + +package dev.kdriver.core.tab + +import dev.kdriver.core.ScriptedTab +import dev.kdriver.core.ScriptedTransport +import dev.kdriver.core.ScriptedTransport.Reply +import dev.kdriver.core.browser.Browser +import dev.kdriver.core.browser.Config +import dev.kdriver.core.exceptions.EvaluateException +import dev.kdriver.core.exceptions.TimeoutWaitingForElementException +import dev.kdriver.core.objectIdsOf +import dev.kdriver.core.param +import dev.kdriver.core.valueReply +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * With [Config.lookupsInPage], `select`, `selectAll`, `querySelector` and `querySelectorAll` without a node ask the page + * (`Runtime.evaluate`) and describe the matches (`DOM.describeNode`) instead of reading the whole document; without it + * they read the document as before. + */ +class LookupsInPageTest { + + private val button = + """{"node":{"nodeId":0,"backendNodeId":70,"nodeType":1,"nodeName":"BUTTON","localName":"button",""" + + """"nodeValue":"","attributes":["id","go"],"childNodeCount":1,"children":[{"nodeId":0,""" + + """"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"","nodeValue":"Send"}]}}""" + + private fun item(backendNodeId: Int, text: String) = + """{"node":{"nodeId":0,"backendNodeId":$backendNodeId,"nodeType":1,"nodeName":"LI","localName":"li",""" + + """"nodeValue":"","childNodeCount":1,"children":[{"nodeId":0,"backendNodeId":${backendNodeId + 1},""" + + """"nodeType":3,"nodeName":"#text","localName":"","nodeValue":"$text"}]}}""" + + private val nothing = """{"result":{"type":"object","subtype":"null","value":null}}""" + + private fun found(objectId: String, subtype: String = "node") = + """{"result":{"type":"object","subtype":"$subtype","objectId":"$objectId"}}""" + + private val document = + """{"root":{"nodeId":1,"backendNodeId":1,"nodeType":9,"nodeName":"#document","localName":"","nodeValue":"",""" + + """"childNodeCount":1,"children":[{"nodeId":7,"backendNodeId":70,"nodeType":1,"nodeName":"BUTTON",""" + + """"localName":"button","nodeValue":"","attributes":["id","go"],"childNodeCount":1,"children":[""" + + """{"nodeId":8,"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"","nodeValue":"Send"}]}]}}""" + + private fun TestScope.tab(lookupsInPage: Boolean, answer: (ScriptedTransport.Sent) -> Reply): ScriptedTab { + val config = mockk(relaxed = true) + every { config.lookupsInPage } returns lookupsInPage + every { config.commandTimeout } returns Config.Defaults.COMMAND_TIMEOUT + val browser = mockk(relaxed = true) + every { browser.config } returns config + return ScriptedTab(this, ScriptedTransport(this, answer)).also { it.owner = browser } + } + + private val ScriptedTab.sent get() = transport.methods + + @Test + fun select_asksThePage_andDescribesTheMatch_withoutReadingTheDocument() = runTest(StandardTestDispatcher()) { + val tab = tab(lookupsInPage = true) { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-1")) + "DOM.describeNode" -> Reply.ok(button) + "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) + else -> Reply.ok() + } + } + + val element = tab.select(" #go ", timeout = 1_000) + + assertEquals("button", element.tag) + assertEquals("Send", element.text) + assertEquals("go", element["id"]) + assertEquals(0, element.node.nodeId, "no node id: no document was requested") + assertNull(element.tree) + assertEquals(listOf("Runtime.evaluate", "DOM.describeNode"), tab.sent.filter { it != "Target.getTargetInfo" }) + val evaluate = tab.transport.sent.first { it.method == "Runtime.evaluate" } + assertEquals("document.querySelector(\"#go\")", evaluate.param("expression")) + val describe = tab.transport.sent.first { it.method == "DOM.describeNode" } + assertEquals("obj-1", describe.param("objectId")) + assertEquals("-1", describe.param("depth")) + assertEquals("true", describe.param("pierce")) + tab.close() + } + + @Test + fun select_firstCallUsesTheObjectOfTheLookup_withoutResolvingTheNode() = runTest(StandardTestDispatcher()) { + val tab = tab(lookupsInPage = true) { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-1")) + "DOM.describeNode" -> Reply.ok(button) + "Runtime.callFunctionOn" -> Reply.ok(valueReply("null")) + "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) + else -> Reply.ok() + } + } + + tab.select("#go", timeout = 1_000).click() + + assertEquals(listOf("obj-1"), tab.transport.objectIdsOf()) + assertTrue("DOM.resolveNode" !in tab.sent) + tab.close() + } + + @Test + fun select_resolvesTheNodeAgain_whenTheObjectOfTheLookupIsStale() = runTest(StandardTestDispatcher()) { + var calls = 0 + val tab = tab(lookupsInPage = true) { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-1")) + "DOM.describeNode" -> Reply.ok(button) + "Runtime.callFunctionOn" -> + if (calls++ == 0) Reply.error("Could not find object with given id") else Reply.ok(valueReply("null")) + "DOM.resolveNode" -> Reply.ok("""{"object":{"type":"object","objectId":"obj-2"}}""") + "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) + else -> Reply.ok() + } + } + + tab.select("#go", timeout = 1_000).click() + + assertEquals(listOf("obj-1", "obj-2"), tab.transport.objectIdsOf()) + assertEquals("70", tab.transport.sent.single { it.method == "DOM.resolveNode" }.param("backendNodeId")) + tab.close() + } + + @Test + fun select_triesAgain_whileThePageHasNoMatch_thenTimesOut() = runTest(StandardTestDispatcher()) { + val tab = tab(lookupsInPage = true) { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(nothing) + "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) + else -> Reply.ok() + } + } + + assertFailsWith { tab.select("#missing", timeout = 1_200) } + + assertTrue(tab.sent.count { it == "Runtime.evaluate" } >= 3, "polled every 500 ms") + assertTrue("DOM.describeNode" !in tab.sent && "DOM.getDocument" !in tab.sent) + tab.close() + } + + @Test + fun select_triesAgain_whenTheMatchIsGoneBeforeItIsDescribed() = runTest(StandardTestDispatcher()) { + var describes = 0 + val tab = tab(lookupsInPage = true) { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-${describes + 1}")) + "DOM.describeNode" -> + if (describes++ == 0) Reply.error("Could not find object with given id") else Reply.ok(button) + "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) + else -> Reply.ok() + } + } + + val element = tab.select("#go", timeout = 5_000) + + assertEquals("button", element.tag) + assertEquals(2, tab.sent.count { it == "Runtime.evaluate" }) + tab.close() + } + + @Test + fun select_withAnInvalidSelector_throwsThePageError() = runTest(StandardTestDispatcher()) { + val tab = tab(lookupsInPage = true) { + when (it.method) { + "Runtime.evaluate" -> Reply.ok( + """{"result":{"type":"object","subtype":"error","objectId":"err"},"exceptionDetails":""" + + """{"exceptionId":1,"text":"Uncaught","lineNumber":0,"columnNumber":9,"exception":""" + + """{"type":"object","subtype":"error","description":"SyntaxError: 'li[' is not a valid selector."}}}""" + ) + "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) + else -> Reply.ok() + } + } + + val error = assertFailsWith { tab.select("li[", timeout = 0) } + + assertTrue(error.jsError.startsWith("SyntaxError"), error.jsError) + tab.close() + } + + @Test + fun querySelector_passesTheSelectorAsOneJsonStringLiteral() = runTest(StandardTestDispatcher()) { + val tab = tab(lookupsInPage = true) { Reply.ok(nothing) } + val selector = "a[title=\"x\\\") + alert(1) + (\"\n\u2028\"]" + + assertNull(tab.querySelector(selector)) + + val expression = tab.transport.sent.single().param("expression")!! + assertEquals( + "document.querySelector(\"a[title=\\\"x\\\\\\\") + alert(1) + (\\\"\\n\u2028\\\"]\")", + expression, + ) + tab.close() + } + + @Test + fun querySelectorAll_withNoMatch_costsOneRoundTrip() = runTest(StandardTestDispatcher()) { + val tab = tab(lookupsInPage = true) { Reply.ok(nothing) } + + assertEquals(emptyList(), tab.querySelectorAll(".item")) + + assertEquals(listOf("Runtime.evaluate"), tab.sent) + assertEquals( + "(() => { const all = Array.from(document.querySelectorAll(\".item\")); return all.length ? all : null; })()", + tab.transport.sent.single().param("expression"), + ) + tab.close() + } + + @Test + fun querySelectorAll_describesEveryMatch_inDocumentOrder() = runTest(StandardTestDispatcher()) { + val items = mapOf("li-0" to item(10, "Alpha"), "li-1" to item(20, "Beta"), "li-2" to item(30, "Gamma")) + val tab = tab(lookupsInPage = true) { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) + "Runtime.getProperties" -> Reply.ok( + """{"result":[""" + + """{"name":"2","configurable":true,"enumerable":true,"value":{"type":"object","subtype":"node","objectId":"li-2"}},""" + + """{"name":"0","configurable":true,"enumerable":true,"value":{"type":"object","subtype":"node","objectId":"li-0"}},""" + + """{"name":"1","configurable":true,"enumerable":true,"value":{"type":"object","subtype":"node","objectId":"li-1"}},""" + + """{"name":"3","configurable":true,"enumerable":true,"get":{"type":"function","objectId":"getter"}},""" + + """{"name":"4","configurable":true,"enumerable":true,"value":{"type":"number","value":4}},""" + + """{"name":"length","configurable":false,"enumerable":false,"value":{"type":"number","value":3}},""" + + """{"name":"__proto__","configurable":true,"enumerable":false,"value":{"type":"object","objectId":"proto"}}""" + + """]}""" + ) + "DOM.describeNode" -> Reply.ok(items.getValue(it.param("objectId")!!), latency = 100) + else -> Reply.ok() + } + } + + val found = tab.querySelectorAll(".item") + + assertEquals(listOf("Alpha", "Beta", "Gamma"), found.map { it.text }) + assertEquals(listOf(10, 20, 30), found.map { it.backendNodeId }) + assertEquals("array", tab.transport.sent.single { it.method == "Runtime.getProperties" }.param("objectId")) + assertEquals("true", tab.transport.sent.single { it.method == "Runtime.getProperties" }.param("ownProperties")) + assertEquals(100, testScheduler.currentTime, "the descriptions are sent together, one round trip for all") + assertTrue("DOM.getDocument" !in tab.sent) + tab.close() + } + + @Test + fun querySelectorAll_leavesOutAMatchGoneBeforeItIsDescribed() = runTest(StandardTestDispatcher()) { + val tab = tab(lookupsInPage = true) { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) + "Runtime.getProperties" -> Reply.ok( + """{"result":[""" + + """{"name":"0","configurable":true,"enumerable":true,"value":{"type":"object","subtype":"node","objectId":"li-0"}},""" + + """{"name":"1","configurable":true,"enumerable":true,"value":{"type":"object","subtype":"node","objectId":"li-1"}}""" + + """]}""" + ) + "DOM.describeNode" -> + if (it.param("objectId") == "li-0") Reply.error("Could not find object with given id") + else Reply.ok(item(20, "Beta")) + else -> Reply.ok() + } + } + + assertEquals(listOf("Beta"), tab.querySelectorAll(".item").map { it.text }) + tab.close() + } + + @Test + fun selectAll_asksThePage_andTimesOutWhenNothingMatches() = runTest(StandardTestDispatcher()) { + val tab = tab(lookupsInPage = true) { Reply.ok(nothing) } + + assertFailsWith { tab.selectAll(".item", timeout = 1_200) } + + assertTrue(tab.sent.isNotEmpty() && tab.sent.all { it == "Runtime.evaluate" }, tab.sent.toString()) + tab.close() + } + + @Test + fun withTheSettingOff_selectReadsTheDocumentAsBefore() = runTest(StandardTestDispatcher()) { + val tab = tab(lookupsInPage = false) { + when (it.method) { + "DOM.getDocument" -> Reply.ok(document) + "DOM.querySelector" -> Reply.ok("""{"nodeId":7}""") + "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) + else -> Reply.ok() + } + } + + val element = tab.select("#go", timeout = 1_000) + + assertEquals(7, element.node.nodeId) + assertEquals(listOf("DOM.getDocument", "DOM.querySelector"), tab.sent.filter { it != "Target.getTargetInfo" }) + tab.close() + } + + @Test + fun withTheSettingOff_querySelectorAllReadsTheDocumentAsBefore() = runTest(StandardTestDispatcher()) { + val tab = tab(lookupsInPage = false) { + when (it.method) { + "DOM.getDocument" -> Reply.ok(document) + "DOM.querySelectorAll" -> Reply.ok("""{"nodeIds":[7]}""") + else -> Reply.ok() + } + } + + assertEquals(listOf(7), tab.querySelectorAll("#go").map { it.node.nodeId }) + assertEquals(listOf("DOM.getDocument", "DOM.querySelectorAll"), tab.sent) + tab.close() + } + + @Test + fun withoutABrowser_lookupsReadTheDocument() = runTest(StandardTestDispatcher()) { + val transport = ScriptedTransport(this) { + when (it.method) { + "DOM.getDocument" -> Reply.ok(document) + "DOM.querySelector" -> Reply.ok("""{"nodeId":7}""") + else -> Reply.ok() + } + } + val tab = ScriptedTab(this, transport) + + assertEquals(7, tab.querySelector("#go")!!.node.nodeId) + assertEquals(listOf("DOM.getDocument", "DOM.querySelector"), transport.methods) + tab.close() + } + + @Test + fun underANode_lookupsAreUnchanged_evenWithTheSettingOn() = runTest(StandardTestDispatcher()) { + val tab = tab(lookupsInPage = true) { + when (it.method) { + "DOM.querySelector" -> Reply.ok("""{"nodeId":8}""") + else -> Reply.ok() + } + } + val parent = dev.kdriver.core.scriptedNode(7, name = "DIV", children = listOf(dev.kdriver.core.scriptedNode(8))) + + val child = tab.querySelector("input", dev.kdriver.core.dom.NodeOrElement.WrappedNode(parent)) + + assertEquals(8, child!!.node.nodeId) + assertEquals(listOf("DOM.querySelector"), tab.sent) + tab.close() + } + +} diff --git a/docs/home/quickstart.md b/docs/home/quickstart.md index d0c0e8de9..97070ac0e 100644 --- a/docs/home/quickstart.md +++ b/docs/home/quickstart.md @@ -188,3 +188,40 @@ fun main() = runBlocking { The browser advertises its own, internal, address in `webSocketDebuggerUrl`; when `browserUrl` is set, kdriver keeps only the path of that URL and connects to it on `browserUrl`. Without `browserUrl`, `host` and `port` keep working as before. + +## Lookups on a remote browser + +By default, `select`, `selectAll`, `querySelector` and `querySelectorAll` read the whole document +(`DOM.getDocument`) each time the page changed since the last read, then query it. That read is the +size of the whole DOM, often a megabyte, and it happens after every navigation and on any page that +keeps changing. When the browser is far away, it is usually the largest transfer of a script. + +With `lookupsInPage`, these lookups ask the page instead: the page runs the selector and only the +matching elements are sent back. + +```kotlin +val browser = createBrowser(this) { + browserUrl = "https://browsers.example.com/team/one" + lookupsInPage = true +} +``` + +The setting is off by default. What changes when it is on: + +| | Off (default) | On | +| --- | --- | --- | +| Commands for `select` / `querySelector` | `DOM.getDocument` (whole document, unless the page has not changed since the last read), then `DOM.querySelector` | `Runtime.evaluate` (`document.querySelector`), then `DOM.describeNode` of the match | +| Commands for `selectAll` / `querySelectorAll` | `DOM.getDocument`, then `DOM.querySelectorAll` | one `Runtime.evaluate` when nothing matches; otherwise also `Runtime.getProperties`, then one `DOM.describeNode` per match, sent together | +| Data received per lookup | the whole document | the matches and their subtrees (many or nested matches can add up to more than the document) | +| First call on a found element (`click`, `apply`, …) | resolves the node first (`DOM.resolveNode`) | uses the object the page returned, no extra command | +| `element.node.nodeId` | the node id | 0: no document was requested | +| `element.tree`, `element.parent` | the document, the parent | `null`, and `parent` throws until `element.update()`, which reads the document | +| Text, attributes, children of an element | read from the node and its subtree | the same | +| Shadow roots | not searched | not searched | +| Iframes | not searched; `selectAll(includeFrames = true)` searches inside each one | the same: the iframes are found in the page, then the document is read to search inside each one | +| Waiting | `select` / `selectAll` retry every 500 ms until the timeout | the same; with no document requested, the browser sends fewer `DOM.*` events, so a busy page may count as idle sooner | +| Invalid selector | `CDPException` | `EvaluateException` (the page's `SyntaxError`) | +| A page that replaces `document.querySelector` | not affected | the page's own function runs | + +Lookups under an element (`element.querySelector`, `element.querySelectorAll`), `find`, `findAll` +and `xpath` are the same in both modes: they still read the document. From d4208ba5f2348383e3b8a0a5b956a82e90ae5955 Mon Sep 17 00:00:00 2001 From: Nathan Fallet Date: Thu, 19 Nov 2026 10:43:57 +0100 Subject: [PATCH 02/16] fix: in-page lookups survive a navigation and release what they no longer need - An object or execution context dropped by a navigation during an in-page lookup counts as no match (select tries again); any other protocol error is thrown instead of being read as no match. - querySelectorAll releases the array of matches while they are described. - selectAll(includeFrames = true) finds the iframes through the document, which the search inside each one reads anyway. - A lookup under an element found in the page updates it from the document first, as it has no node id yet. --- .../kotlin/dev/kdriver/core/browser/Config.kt | 13 +- .../kotlin/dev/kdriver/core/tab/DefaultTab.kt | 57 ++++++-- .../dev/kdriver/core/tab/LookupsInPageTest.kt | 136 ++++++++++++++++++ docs/home/quickstart.md | 4 +- 4 files changed, 193 insertions(+), 17 deletions(-) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt index 72d820c19..607300fce 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt @@ -67,18 +67,25 @@ class Config( * throws until [dev.kdriver.core.dom.Element.update] is called, which reads the document as before. Each element * keeps the remote object the page returned, so its first call (`click`, `apply`, …) needs no `DOM.resolveNode`. * - **Shadow DOM and iframes**: same results as off: neither `document.querySelector` nor `DOM.querySelector` on - * the document looks inside a shadow root or an iframe. `selectAll(includeFrames = true)` still finds the iframes - * in the page, then reads the document to search inside each one. + * the document looks inside a shadow root or an iframe. `selectAll(includeFrames = true)` reads the document to + * find the iframes and search inside each one, as off; only its lookup on the page itself runs in the page. * - **Waiting**: `select` and `selectAll` poll and time out as before. Until something reads the document again * (a lookup under an element, `find`, `update`…), the browser sends no `DOM.*` mutation events for the page, so * on a busy page the connection may count as idle sooner. + * - **Navigation**: an object or execution context dropped by a navigation during the lookup counts as no match + * (`select` tries again), as a node gone from a document read does off. * - **Errors**: an invalid selector throws an [dev.kdriver.core.exceptions.EvaluateException] (the page's * `SyntaxError`) instead of a [dev.kdriver.cdp.CDPException]. The page's own `document.querySelector` is used: * a page that replaces it changes the result. * - **Round trips**: `querySelector` costs two small ones (evaluate, describe) instead of a document read and a * query; `querySelectorAll` costs one when nothing matches, three otherwise (evaluate, the array's properties, * then every match described in parallel). Each match is described with its subtree: many matches, or nested - * ones, can transfer more than the document would. + * ones, can transfer more than the document would: leave the setting off for a selector that matches most of + * the page. Each element holds its remote object until the page navigates, as one used off does after its first + * call; the array of `querySelectorAll` is released. + * - **Elements passed back**: a lookup under such an element ([dev.kdriver.core.dom.Element.querySelector], or a + * [dev.kdriver.core.dom.NodeOrElement.WrappedElement] passed to `querySelector`) updates it from the document + * first. * * Lookups under a node or an element ([dev.kdriver.core.dom.Element.querySelector], `find`, `findAll`, `xpath`) * are unchanged and still read the document. Off by default. diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt index c2abc7108..5a3c3aa9a 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt @@ -405,7 +405,10 @@ open class DefaultTab( while (true) { val items = mutableListOf() if (includeFrames) { - val frames = querySelectorAll("iframe") + // The frames are searched through the document (Element.querySelectorAll reads it anyway), so they + // are found there too: with Config.lookupsInPage, describing them in the page would add their + // whole content to that read. + val frames = onDocument { doc -> querySelectorAllInternal("iframe", null, retried = false, doc) } for (fr in frames) items.addAll(fr.querySelectorAll(trimmedSelector)) } items.addAll(querySelectorAll(trimmedSelector)) @@ -446,7 +449,7 @@ open class DefaultTab( ): List = if (node == null && lookupsInPage) querySelectorAllInPage(selector) else if (node == null) onDocument { doc -> querySelectorAllInternal(selector, null, retried = false, doc) } - else querySelectorAllInternal(selector, node, retried = false, rootOf(node)) + else querySelectorAllInternal(selector, node, retried = false, boundRootOf(node)) // Config.lookupsInPage of the browser this tab belongs to; off for a tab without one. private val lookupsInPage: Boolean @@ -462,12 +465,19 @@ open class DefaultTab( "(() => { const all = Array.from(document.querySelectorAll(${jsStringLiteral(selector)}));" + " return all.length ? all : null; })()" ) ?: return emptyList() - val matches = runtime.getProperties(objectId = array.objectId!!, ownProperties = true).result + val arrayId = array.objectId!! + val properties = unlessGone { runtime.getProperties(objectId = arrayId, ownProperties = true).result } + ?: return emptyList() + val matches = properties .mapNotNull { property -> property.name.toIntOrNull()?.let { index -> index to property.value } } .sortedBy { it.first } .mapNotNull { (_, value) -> value?.takeIf { it.objectId != null } } return coroutineScope { - matches.map { match -> async { describeMatch(match) } }.awaitAll().filterNotNull() + // The array is no longer needed: released while the matches are described, at no extra wait. + val release = async { unlessGone { runtime.releaseObject(arrayId) } } + val found = matches.map { match -> async { describeMatch(match) } }.awaitAll().filterNotNull() + release.await() + found } } @@ -485,7 +495,7 @@ open class DefaultTab( * An exception thrown by the page (an invalid selector) is thrown as an [EvaluateException]. */ private suspend fun evaluateLookup(expression: String): Runtime.RemoteObject? { - val evaluated = runtime.evaluate(expression = expression) + val evaluated = unlessGone { runtime.evaluate(expression = expression) } ?: return null evaluated.exceptionDetails?.let { throw EvaluateException(it) } return evaluated.result.takeIf { it.objectId != null } } @@ -496,16 +506,23 @@ open class DefaultTab( * the object (the page navigated in between): the match is gone, and `select` tries again as for no match. */ private suspend fun describeMatch(match: Runtime.RemoteObject): Element? { - val node = try { - dom.describeNode(objectId = match.objectId, depth = -1, pierce = true).node - } catch (e: CancellationException) { - throw e - } catch (_: CDPException) { - return null - } + val node = unlessGone { dom.describeNode(objectId = match.objectId, depth = -1, pierce = true).node } + ?: return null return DefaultElement(this, node).also { it.keepRemoteObject(match) } } + /** + * Runs [command] of an in-page lookup, or returns null when the browser no longer knows what it refers to: the + * object or the execution context was dropped by a navigation in between, so the lookup found nothing and `select` + * tries again. Any other protocol error is thrown. + */ + private suspend fun unlessGone(command: suspend () -> T): T? = + try { + command() + } catch (e: CDPException) { + if (GONE.any { e.originalMessage.contains(it, ignoreCase = true) }) null else throw e + } + // A JavaScript string literal for [value]: its JSON encoding, which escapes quotes, backslashes and control // characters, so the value can only ever be read as one string. private fun jsStringLiteral(value: String): String = @@ -556,10 +573,17 @@ open class DefaultTab( } else if (node == null) { onDocument { doc -> querySelectorInternal(trimmedSelector, null, retried = false, doc) } } else { - querySelectorInternal(trimmedSelector, node, retried = false, rootOf(node)) + querySelectorInternal(trimmedSelector, node, retried = false, boundRootOf(node)) } } + // rootOf for a lookup under [node], once an element found with Config.lookupsInPage (no node id yet) has been + // updated from the document. + private suspend fun boundRootOf(node: NodeOrElement): DOM.Node { + if (node is NodeOrElement.WrappedElement && node.node.nodeId == 0) node.element.update() + return rootOf(node) + } + // The node a lookup under [node] queries: the document of a frame, the node itself otherwise. private fun rootOf(node: NodeOrElement): DOM.Node = if (node.node.nodeName == "IFRAME") node.node.contentDocument ?: node.node else node.node @@ -902,3 +926,10 @@ open class DefaultTab( } } + +/** + * Error texts of the browser for an object, a node or an execution context it no longer knows (a navigation dropped + * it): "Could not find object with given id", "No node with given id found", "Cannot find context with specified id", + * "Execution context was destroyed". + */ +private val GONE = listOf("could not find", "no node with given id", "cannot find context", "context was destroyed") diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt index bed9ab0a0..c94489faa 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt @@ -246,6 +246,10 @@ class LookupsInPageTest { assertEquals("array", tab.transport.sent.single { it.method == "Runtime.getProperties" }.param("objectId")) assertEquals("true", tab.transport.sent.single { it.method == "Runtime.getProperties" }.param("ownProperties")) assertEquals(100, testScheduler.currentTime, "the descriptions are sent together, one round trip for all") + assertEquals( + "array", tab.transport.sent.single { it.method == "Runtime.releaseObject" }.param("objectId"), + "the array is released while the matches are described" + ) assertTrue("DOM.getDocument" !in tab.sent) tab.close() } @@ -264,6 +268,7 @@ class LookupsInPageTest { "DOM.describeNode" -> if (it.param("objectId") == "li-0") Reply.error("Could not find object with given id") else Reply.ok(item(20, "Beta")) + "Runtime.releaseObject" -> Reply.error("Could not find object with given id") else -> Reply.ok() } } @@ -348,4 +353,135 @@ class LookupsInPageTest { tab.close() } + private val arrayOfOne = """{"result":[""" + + """{"name":"0","configurable":true,"enumerable":true,"value":{"type":"object","subtype":"node","objectId":"li-0"}}""" + + """]}""" + + @Test + fun querySelectorAll_findsNothing_whenTheArrayIsGoneBeforeItIsRead() = runTest(StandardTestDispatcher()) { + val tab = tab(lookupsInPage = true) { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) + "Runtime.getProperties" -> Reply.error("Could not find object with given id") + else -> Reply.ok() + } + } + + assertEquals(emptyList(), tab.querySelectorAll(".item")) + assertEquals(listOf("Runtime.evaluate", "Runtime.getProperties"), tab.sent) + tab.close() + } + + @Test + fun querySelector_findsNothing_whenTheContextIsGone() = runTest(StandardTestDispatcher()) { + for (error in listOf("Cannot find context with specified id", "Execution context was destroyed.")) { + val tab = tab(lookupsInPage = true) { + when (it.method) { + "Runtime.evaluate" -> Reply.error(error) + else -> Reply.ok() + } + } + + assertNull(tab.querySelector("#go"), error) + assertEquals(listOf("Runtime.evaluate"), tab.sent) + tab.close() + } + } + + @Test + fun querySelector_findsNothing_whenTheNodeIsGoneBeforeItIsDescribed() = runTest(StandardTestDispatcher()) { + val tab = tab(lookupsInPage = true) { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-1")) + "DOM.describeNode" -> Reply.error("No node with given id found") + else -> Reply.ok() + } + } + + assertNull(tab.querySelector("#go")) + tab.close() + } + + @Test + fun anyOtherProtocolError_isThrown() = runTest(StandardTestDispatcher()) { + val describing = tab(lookupsInPage = true) { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-1")) + "DOM.describeNode" -> Reply.error("Message is too large") + else -> Reply.ok() + } + } + assertEquals( + "Message is too large", + assertFailsWith { describing.querySelector("#go") }.originalMessage + ) + describing.close() + + val listing = tab(lookupsInPage = true) { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) + "Runtime.getProperties" -> Reply.ok(arrayOfOne) + "DOM.describeNode" -> Reply.ok(item(10, "Alpha")) + "Runtime.releaseObject" -> Reply.error("Session closed") + else -> Reply.ok() + } + } + assertEquals("Session closed", assertFailsWith { listing.querySelectorAll(".item") }.originalMessage) + listing.close() + + val evaluating = tab(lookupsInPage = true) { + when (it.method) { + "Runtime.evaluate" -> Reply.error("Session closed") + else -> Reply.ok() + } + } + assertFailsWith { evaluating.querySelectorAll(".item") } + evaluating.close() + } + + @Test + fun selectAllWithFrames_findsTheFramesInTheDocument_andTheMatchesInThePage() = runTest(StandardTestDispatcher()) { + val tab = tab(lookupsInPage = true) { + when (it.method) { + "DOM.getDocument" -> Reply.ok(document) + "DOM.querySelectorAll" -> Reply.ok("""{"nodeIds":[]}""") + "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) + "Runtime.getProperties" -> Reply.ok(arrayOfOne) + "DOM.describeNode" -> Reply.ok(item(10, "Alpha")) + else -> Reply.ok() + } + } + + assertEquals(listOf("Alpha"), tab.selectAll(".item", timeout = 1_000, includeFrames = true).map { it.text }) + assertEquals("iframe", tab.transport.sent.single { it.method == "DOM.querySelectorAll" }.param("selector")) + assertTrue("DOM.getDocument" in tab.sent) + tab.close() + } + + @Test + fun aLookupUnderAnElementFoundInThePage_updatesItFromTheDocumentFirst() = runTest(StandardTestDispatcher()) { + val tab = tab(lookupsInPage = true) { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-1")) + "DOM.describeNode" -> Reply.ok(button) + "DOM.getDocument" -> Reply.ok(document) + "DOM.querySelector" -> Reply.ok("""{"nodeId":8}""") + "DOM.resolveNode" -> Reply.ok("""{"object":{"type":"object","subtype":"node","objectId":"obj-2"}}""") + else -> Reply.ok() + } + } + val button = tab.querySelector("#go")!! + + val text = tab.querySelector("*", dev.kdriver.core.dom.NodeOrElement.WrappedElement(button)) + + assertEquals(7, button.node.nodeId, "updated from the document") + assertEquals("7", tab.transport.sent.single { it.method == "DOM.querySelector" }.param("nodeId")) + assertEquals(8, text!!.node.nodeId) + val resolvesBefore = tab.sent.count { it == "DOM.resolveNode" } + tab.querySelector("*", dev.kdriver.core.dom.NodeOrElement.WrappedElement(button)) + assertEquals(resolvesBefore, tab.sent.count { it == "DOM.resolveNode" }, "a bound element is not updated again") + assertEquals(2, tab.sent.count { it == "DOM.querySelector" }) + tab.close() + } + } diff --git a/docs/home/quickstart.md b/docs/home/quickstart.md index 97070ac0e..c183be040 100644 --- a/docs/home/quickstart.md +++ b/docs/home/quickstart.md @@ -218,9 +218,11 @@ The setting is off by default. What changes when it is on: | `element.tree`, `element.parent` | the document, the parent | `null`, and `parent` throws until `element.update()`, which reads the document | | Text, attributes, children of an element | read from the node and its subtree | the same | | Shadow roots | not searched | not searched | -| Iframes | not searched; `selectAll(includeFrames = true)` searches inside each one | the same: the iframes are found in the page, then the document is read to search inside each one | +| Iframes | not searched; `selectAll(includeFrames = true)` searches inside each one | the same: the document is read to find the iframes and search inside each one | | Waiting | `select` / `selectAll` retry every 500 ms until the timeout | the same; with no document requested, the browser sends fewer `DOM.*` events, so a busy page may count as idle sooner | +| A navigation during the lookup | a node gone from the document read counts as no match | an object or context dropped by the navigation counts as no match: `select` tries again | | Invalid selector | `CDPException` | `EvaluateException` (the page's `SyntaxError`) | +| Remote objects held | one per element used, from its first call | one per match, until the page navigates; the array of `selectAll` is released | | A page that replaces `document.querySelector` | not affected | the page's own function runs | Lookups under an element (`element.querySelector`, `element.querySelectorAll`), `find`, `findAll` From e734a549746741f9a9d867956d9ea827069a1279 Mon Sep 17 00:00:00 2001 From: Nathan Fallet Date: Thu, 19 Nov 2026 10:56:14 +0100 Subject: [PATCH 03/16] fix: all-or-nothing in-page results, best-effort release, frames through the document - A match gone before it is described means the page navigated: querySelectorAll in the page returns no match rather than part of the old page's matches. - Releasing the array is a cleanup: its failure never fails the lookup, and the array is also released when reading its properties fails. - "Inspected target navigated or closed" counts as gone; "could not find" is narrowed to objects and nodes. - selectAll(includeFrames = true) reads the document for the page's own matches too, so frames and page come from one read in both modes. --- .../kotlin/dev/kdriver/core/browser/Config.kt | 9 ++-- .../kotlin/dev/kdriver/core/tab/DefaultTab.kt | 46 ++++++++++++---- .../dev/kdriver/core/tab/LookupsInPageTest.kt | 54 ++++++++++++++----- docs/home/quickstart.md | 6 +-- 4 files changed, 84 insertions(+), 31 deletions(-) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt index 607300fce..e844868d4 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt @@ -67,13 +67,14 @@ class Config( * throws until [dev.kdriver.core.dom.Element.update] is called, which reads the document as before. Each element * keeps the remote object the page returned, so its first call (`click`, `apply`, …) needs no `DOM.resolveNode`. * - **Shadow DOM and iframes**: same results as off: neither `document.querySelector` nor `DOM.querySelector` on - * the document looks inside a shadow root or an iframe. `selectAll(includeFrames = true)` reads the document to - * find the iframes and search inside each one, as off; only its lookup on the page itself runs in the page. + * the document looks inside a shadow root or an iframe. `selectAll(includeFrames = true)` reads the document as + * off (searching inside the iframes needs it), for the page's own matches too. * - **Waiting**: `select` and `selectAll` poll and time out as before. Until something reads the document again * (a lookup under an element, `find`, `update`…), the browser sends no `DOM.*` mutation events for the page, so * on a busy page the connection may count as idle sooner. * - **Navigation**: an object or execution context dropped by a navigation during the lookup counts as no match - * (`select` tries again), as a node gone from a document read does off. + * (`select` tries again), as a node gone from a document read does off; when only some matches of + * `querySelectorAll` are gone, none is returned rather than part of the old page's. * - **Errors**: an invalid selector throws an [dev.kdriver.core.exceptions.EvaluateException] (the page's * `SyntaxError`) instead of a [dev.kdriver.cdp.CDPException]. The page's own `document.querySelector` is used: * a page that replaces it changes the result. @@ -82,7 +83,7 @@ class Config( * then every match described in parallel). Each match is described with its subtree: many matches, or nested * ones, can transfer more than the document would: leave the setting off for a selector that matches most of * the page. Each element holds its remote object until the page navigates, as one used off does after its first - * call; the array of `querySelectorAll` is released. + * call; the array of `querySelectorAll` is released (one more command, sent with the descriptions). * - **Elements passed back**: a lookup under such an element ([dev.kdriver.core.dom.Element.querySelector], or a * [dev.kdriver.core.dom.NodeOrElement.WrappedElement] passed to `querySelector`) updates it from the document * first. diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt index 5a3c3aa9a..869d277f0 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt @@ -405,13 +405,14 @@ open class DefaultTab( while (true) { val items = mutableListOf() if (includeFrames) { - // The frames are searched through the document (Element.querySelectorAll reads it anyway), so they - // are found there too: with Config.lookupsInPage, describing them in the page would add their - // whole content to that read. + // Searching inside the frames reads the document (Element.querySelectorAll), so the whole lookup goes + // through it, Config.lookupsInPage or not: the frames and the page's own matches come from one read. val frames = onDocument { doc -> querySelectorAllInternal("iframe", null, retried = false, doc) } for (fr in frames) items.addAll(fr.querySelectorAll(trimmedSelector)) + items.addAll(onDocument { doc -> querySelectorAllInternal(trimmedSelector, null, retried = false, doc) }) + } else { + items.addAll(querySelectorAll(trimmedSelector)) } - items.addAll(querySelectorAll(trimmedSelector)) items.takeIf { it.isNotEmpty() }?.let { return it } val elapsed = Clock.System.now().toEpochMilliseconds() - startTime @@ -466,18 +467,34 @@ open class DefaultTab( " return all.length ? all : null; })()" ) ?: return emptyList() val arrayId = array.objectId!! - val properties = unlessGone { runtime.getProperties(objectId = arrayId, ownProperties = true).result } - ?: return emptyList() + val properties = try { + unlessGone { runtime.getProperties(objectId = arrayId, ownProperties = true).result } ?: return emptyList() + } catch (e: CDPException) { + releaseQuietly(arrayId) + throw e + } val matches = properties .mapNotNull { property -> property.name.toIntOrNull()?.let { index -> index to property.value } } .sortedBy { it.first } .mapNotNull { (_, value) -> value?.takeIf { it.objectId != null } } return coroutineScope { // The array is no longer needed: released while the matches are described, at no extra wait. - val release = async { unlessGone { runtime.releaseObject(arrayId) } } - val found = matches.map { match -> async { describeMatch(match) } }.awaitAll().filterNotNull() + val release = async { releaseQuietly(arrayId) } + val described = matches.map { match -> async { describeMatch(match) } }.awaitAll() release.await() - found + // A match gone before it was described means the page navigated during the lookup: no match at all, as + // for one lookup, rather than a part of the old page's matches. + if (null in described) emptyList() else described.filterNotNull() + } + } + + // Releases a remote object the lookup no longer needs. A cleanup: its failure never fails the lookup (the page + // drops the object at its next navigation anyway). + private suspend fun releaseQuietly(objectId: String) { + try { + runtime.releaseObject(objectId) + } catch (_: CDPException) { + // Already gone, or the session is closing: nothing to clean up. } } @@ -930,6 +947,13 @@ open class DefaultTab( /** * Error texts of the browser for an object, a node or an execution context it no longer knows (a navigation dropped * it): "Could not find object with given id", "No node with given id found", "Cannot find context with specified id", - * "Execution context was destroyed". + * "Execution context was destroyed", "Inspected target navigated or closed". */ -private val GONE = listOf("could not find", "no node with given id", "cannot find context", "context was destroyed") +private val GONE = listOf( + "could not find object", + "could not find node", + "no node with given id", + "cannot find context", + "context was destroyed", + "inspected target navigated or closed", +) diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt index c94489faa..86aeec886 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt @@ -255,7 +255,7 @@ class LookupsInPageTest { } @Test - fun querySelectorAll_leavesOutAMatchGoneBeforeItIsDescribed() = runTest(StandardTestDispatcher()) { + fun querySelectorAll_findsNothing_whenAMatchIsGoneBeforeItIsDescribed() = runTest(StandardTestDispatcher()) { val tab = tab(lookupsInPage = true) { when (it.method) { "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) @@ -273,7 +273,8 @@ class LookupsInPageTest { } } - assertEquals(listOf("Beta"), tab.querySelectorAll(".item").map { it.text }) + assertEquals(emptyList(), tab.querySelectorAll(".item"), "the page navigated: none of its old matches") + assertTrue("Runtime.releaseObject" in tab.sent) tab.close() } @@ -374,7 +375,11 @@ class LookupsInPageTest { @Test fun querySelector_findsNothing_whenTheContextIsGone() = runTest(StandardTestDispatcher()) { - for (error in listOf("Cannot find context with specified id", "Execution context was destroyed.")) { + for (error in listOf( + "Cannot find context with specified id", + "Execution context was destroyed.", + "Inspected target navigated or closed", + )) { val tab = tab(lookupsInPage = true) { when (it.method) { "Runtime.evaluate" -> Reply.error(error) @@ -420,13 +425,18 @@ class LookupsInPageTest { val listing = tab(lookupsInPage = true) { when (it.method) { "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) - "Runtime.getProperties" -> Reply.ok(arrayOfOne) - "DOM.describeNode" -> Reply.ok(item(10, "Alpha")) - "Runtime.releaseObject" -> Reply.error("Session closed") + "Runtime.getProperties" -> Reply.error("Message is too large") else -> Reply.ok() } } - assertEquals("Session closed", assertFailsWith { listing.querySelectorAll(".item") }.originalMessage) + assertEquals( + "Message is too large", + assertFailsWith { listing.querySelectorAll(".item") }.originalMessage + ) + assertEquals( + "array", listing.transport.sent.single { it.method == "Runtime.releaseObject" }.param("objectId"), + "the array is released before the error is thrown" + ) listing.close() val evaluating = tab(lookupsInPage = true) { @@ -440,21 +450,39 @@ class LookupsInPageTest { } @Test - fun selectAllWithFrames_findsTheFramesInTheDocument_andTheMatchesInThePage() = runTest(StandardTestDispatcher()) { + fun querySelectorAll_keepsItsMatches_whenTheReleaseOfTheArrayFails() = runTest(StandardTestDispatcher()) { val tab = tab(lookupsInPage = true) { when (it.method) { - "DOM.getDocument" -> Reply.ok(document) - "DOM.querySelectorAll" -> Reply.ok("""{"nodeIds":[]}""") "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) "Runtime.getProperties" -> Reply.ok(arrayOfOne) "DOM.describeNode" -> Reply.ok(item(10, "Alpha")) + "Runtime.releaseObject" -> Reply.error("Session closed") else -> Reply.ok() } } - assertEquals(listOf("Alpha"), tab.selectAll(".item", timeout = 1_000, includeFrames = true).map { it.text }) - assertEquals("iframe", tab.transport.sent.single { it.method == "DOM.querySelectorAll" }.param("selector")) - assertTrue("DOM.getDocument" in tab.sent) + assertEquals(listOf("Alpha"), tab.querySelectorAll(".item").map { it.text }) + tab.close() + } + + @Test + fun selectAllWithFrames_readsTheDocumentAsOff() = runTest(StandardTestDispatcher()) { + val tab = tab(lookupsInPage = true) { + when (it.method) { + "DOM.getDocument" -> Reply.ok(document) + "DOM.querySelectorAll" -> + if (it.param("selector") == "iframe") Reply.ok("""{"nodeIds":[]}""") else Reply.ok("""{"nodeIds":[7]}""") + else -> Reply.ok() + } + } + + assertEquals(listOf("Send"), tab.selectAll("#go", timeout = 1_000, includeFrames = true).map { it.text }) + assertEquals( + listOf("iframe", "#go"), + tab.transport.sent.filter { it.method == "DOM.querySelectorAll" }.map { it.param("selector") } + ) + assertEquals(1, tab.sent.count { it == "DOM.getDocument" }, "one read for the frames and the page") + assertTrue("Runtime.evaluate" !in tab.sent) tab.close() } diff --git a/docs/home/quickstart.md b/docs/home/quickstart.md index c183be040..c7476674c 100644 --- a/docs/home/quickstart.md +++ b/docs/home/quickstart.md @@ -218,11 +218,11 @@ The setting is off by default. What changes when it is on: | `element.tree`, `element.parent` | the document, the parent | `null`, and `parent` throws until `element.update()`, which reads the document | | Text, attributes, children of an element | read from the node and its subtree | the same | | Shadow roots | not searched | not searched | -| Iframes | not searched; `selectAll(includeFrames = true)` searches inside each one | the same: the document is read to find the iframes and search inside each one | +| Iframes | not searched; `selectAll(includeFrames = true)` searches inside each one | the same: with `includeFrames = true`, `selectAll` reads the document as off, for the page's own matches too | | Waiting | `select` / `selectAll` retry every 500 ms until the timeout | the same; with no document requested, the browser sends fewer `DOM.*` events, so a busy page may count as idle sooner | -| A navigation during the lookup | a node gone from the document read counts as no match | an object or context dropped by the navigation counts as no match: `select` tries again | +| A navigation during the lookup | a node gone from the document read counts as no match | an object or context dropped by the navigation counts as no match (all of them, even if only some matches are gone): `select` tries again | | Invalid selector | `CDPException` | `EvaluateException` (the page's `SyntaxError`) | -| Remote objects held | one per element used, from its first call | one per match, until the page navigates; the array of `selectAll` is released | +| Remote objects held | one per element used, from its first call | one per match, until the page navigates; the array of `selectAll` is released (one more command, sent with the descriptions) | | A page that replaces `document.querySelector` | not affected | the page's own function runs | Lookups under an element (`element.querySelector`, `element.querySelectorAll`), `find`, `findAll` From bdbe3aaf45488b05237e4e58ce0154e3116e9145 Mon Sep 17 00:00:00 2001 From: Nathan Fallet Date: Thu, 19 Nov 2026 11:01:19 +0100 Subject: [PATCH 04/16] fix: a closed target is an error, and the array is released on every path - "Inspected target navigated or closed" no longer counts as gone: Chrome also sends it for a closed tab, which must fail rather than poll. - The descriptions run in a supervisorScope, so one that fails no longer cancels the release of the array; the release swallows any error but a cancellation. - selectAll(includeFrames = true) shares one helper for its document lookups; its KDoc says the document is read as without the setting. --- .../kotlin/dev/kdriver/core/tab/DefaultTab.kt | 32 +++++---- .../kotlin/dev/kdriver/core/tab/Tab.kt | 2 +- .../dev/kdriver/core/tab/LookupsInPageTest.kt | 65 ++++++++++++++++++- 3 files changed, 86 insertions(+), 13 deletions(-) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt index 869d277f0..7dc03a783 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt @@ -23,6 +23,7 @@ import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay +import kotlinx.coroutines.supervisorScope import kotlinx.io.buffered import kotlinx.io.files.Path import kotlinx.io.files.SystemFileSystem @@ -407,9 +408,8 @@ open class DefaultTab( if (includeFrames) { // Searching inside the frames reads the document (Element.querySelectorAll), so the whole lookup goes // through it, Config.lookupsInPage or not: the frames and the page's own matches come from one read. - val frames = onDocument { doc -> querySelectorAllInternal("iframe", null, retried = false, doc) } - for (fr in frames) items.addAll(fr.querySelectorAll(trimmedSelector)) - items.addAll(onDocument { doc -> querySelectorAllInternal(trimmedSelector, null, retried = false, doc) }) + for (fr in querySelectorAllInDocument("iframe")) items.addAll(fr.querySelectorAll(trimmedSelector)) + items.addAll(querySelectorAllInDocument(trimmedSelector)) } else { items.addAll(querySelectorAll(trimmedSelector)) } @@ -449,9 +449,13 @@ open class DefaultTab( node: NodeOrElement?, ): List = if (node == null && lookupsInPage) querySelectorAllInPage(selector) - else if (node == null) onDocument { doc -> querySelectorAllInternal(selector, null, retried = false, doc) } + else if (node == null) querySelectorAllInDocument(selector) else querySelectorAllInternal(selector, node, retried = false, boundRootOf(node)) + // querySelectorAll on the whole document read (kept while the page has not changed), whatever Config.lookupsInPage. + private suspend fun querySelectorAllInDocument(selector: String): List = + onDocument { doc -> querySelectorAllInternal(selector, null, retried = false, doc) } + // Config.lookupsInPage of the browser this tab belongs to; off for a tab without one. private val lookupsInPage: Boolean get() = owner?.let { browser -> browser.config.lookupsInPage } == true @@ -477,11 +481,15 @@ open class DefaultTab( .mapNotNull { property -> property.name.toIntOrNull()?.let { index -> index to property.value } } .sortedBy { it.first } .mapNotNull { (_, value) -> value?.takeIf { it.objectId != null } } - return coroutineScope { + // supervisorScope: a description that fails does not cancel the release, which is a cleanup that never fails. + return supervisorScope { // The array is no longer needed: released while the matches are described, at no extra wait. val release = async { releaseQuietly(arrayId) } - val described = matches.map { match -> async { describeMatch(match) } }.awaitAll() - release.await() + val described = try { + matches.map { match -> async { describeMatch(match) } }.awaitAll() + } finally { + release.await() + } // A match gone before it was described means the page navigated during the lookup: no match at all, as // for one lookup, rather than a part of the old page's matches. if (null in described) emptyList() else described.filterNotNull() @@ -493,8 +501,10 @@ open class DefaultTab( private suspend fun releaseQuietly(objectId: String) { try { runtime.releaseObject(objectId) - } catch (_: CDPException) { - // Already gone, or the session is closing: nothing to clean up. + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + // Already gone, or the connection is closing: nothing to clean up. } } @@ -947,7 +957,8 @@ open class DefaultTab( /** * Error texts of the browser for an object, a node or an execution context it no longer knows (a navigation dropped * it): "Could not find object with given id", "No node with given id found", "Cannot find context with specified id", - * "Execution context was destroyed", "Inspected target navigated or closed". + * "Execution context was destroyed". Not "Inspected target navigated or closed", also sent for a closed tab, which is an + * error and not a lookup to try again. */ private val GONE = listOf( "could not find object", @@ -955,5 +966,4 @@ private val GONE = listOf( "no node with given id", "cannot find context", "context was destroyed", - "inspected target navigated or closed", ) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt b/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt index 57b650c7a..47e4f410c 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt @@ -333,7 +333,7 @@ interface Tab : Connection { * Can also be used to wait for such elements to appear. Optionally includes results from iframes. * * With [dev.kdriver.core.browser.Config.lookupsInPage], the page runs the selector instead of the whole document - * being read; the elements then carry no node id nor tree. See that setting for every difference. + * being read; the elements then carry no node id nor tree. See that setting for every difference. With [includeFrames], the document is read as without that setting. * * @param selector CSS selector, e\.g\., `a[href]`, `button[class*=close]`, `a > img[src]` * @param timeout Raise timeout exception when after this many milliseconds nothing is found. diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt index 86aeec886..3b7f3ca5a 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt @@ -378,7 +378,6 @@ class LookupsInPageTest { for (error in listOf( "Cannot find context with specified id", "Execution context was destroyed.", - "Inspected target navigated or closed", )) { val tab = tab(lookupsInPage = true) { when (it.method) { @@ -407,6 +406,37 @@ class LookupsInPageTest { tab.close() } + @Test + fun aClosedTarget_isAnError_notANoMatch() = runTest(StandardTestDispatcher()) { + val tab = tab(lookupsInPage = true) { + when (it.method) { + "Runtime.evaluate" -> Reply.error("Inspected target navigated or closed") + else -> Reply.ok() + } + } + + assertFailsWith { tab.querySelector("#go") } + tab.close() + } + + @Test + fun aDescriptionThatFails_isThrown_andTheArrayIsStillReleased() = runTest(StandardTestDispatcher()) { + val tab = tab(lookupsInPage = true) { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) + "Runtime.getProperties" -> Reply.ok(arrayOfOne) + "DOM.describeNode" -> Reply.error("Message is too large") + "Runtime.releaseObject" -> Reply.ok(latency = 50) + else -> Reply.ok() + } + } + + assertFailsWith { tab.querySelectorAll(".item") } + assertEquals("array", tab.transport.sent.single { it.method == "Runtime.releaseObject" }.param("objectId")) + assertEquals(50, testScheduler.currentTime, "the release was awaited, not cancelled") + tab.close() + } + @Test fun anyOtherProtocolError_isThrown() = runTest(StandardTestDispatcher()) { val describing = tab(lookupsInPage = true) { @@ -465,6 +495,39 @@ class LookupsInPageTest { tab.close() } + private val documentWithAFrame = + """{"root":{"nodeId":1,"backendNodeId":1,"nodeType":9,"nodeName":"#document","localName":"","nodeValue":"",""" + + """"childNodeCount":2,"children":[{"nodeId":7,"backendNodeId":70,"nodeType":1,"nodeName":"P",""" + + """"localName":"p","nodeValue":"","childNodeCount":1,"children":[""" + + """{"nodeId":8,"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"","nodeValue":"Outer"}]},""" + + """{"nodeId":9,"backendNodeId":90,"nodeType":1,"nodeName":"IFRAME","localName":"iframe","nodeValue":"",""" + + """"childNodeCount":0,"contentDocument":{"nodeId":10,"backendNodeId":100,"nodeType":9,""" + + """"nodeName":"#document","localName":"","nodeValue":"","childNodeCount":1,"children":[""" + + """{"nodeId":11,"backendNodeId":110,"nodeType":1,"nodeName":"P","localName":"p","nodeValue":"",""" + + """"childNodeCount":1,"children":[{"nodeId":12,"backendNodeId":120,"nodeType":3,"nodeName":"#text",""" + + """"localName":"","nodeValue":"Inner"}]}]}}]}}""" + + @Test + fun selectAllWithAFrame_findsInsideItAndInThePage_fromOneDocumentRead() = runTest(StandardTestDispatcher()) { + val tab = tab(lookupsInPage = true) { + when (it.method) { + "DOM.getDocument" -> Reply.ok(documentWithAFrame) + "DOM.querySelectorAll" -> when (it.param("nodeId")) { + "1" -> if (it.param("selector") == "iframe") Reply.ok("""{"nodeIds":[9]}""") else Reply.ok("""{"nodeIds":[7]}""") + "10" -> Reply.ok("""{"nodeIds":[11]}""") + else -> Reply.error("Could not find node with given id") + } + "DOM.resolveNode" -> Reply.ok("""{"object":{"type":"object","subtype":"node","objectId":"frame"}}""") + else -> Reply.ok() + } + } + + assertEquals(listOf("Inner", "Outer"), tab.selectAll("p", timeout = 1_000, includeFrames = true).map { it.text }) + assertEquals(1, tab.sent.count { it == "DOM.getDocument" }, "one read for the frame and the page") + assertTrue("Runtime.evaluate" !in tab.sent) + tab.close() + } + @Test fun selectAllWithFrames_readsTheDocumentAsOff() = runTest(StandardTestDispatcher()) { val tab = tab(lookupsInPage = true) { From 8c1d1029da20ccf66153081ced006b931398d928 Mon Sep 17 00:00:00 2001 From: Nathan Fallet Date: Thu, 19 Nov 2026 11:05:58 +0100 Subject: [PATCH 05/16] fix: release the array of an in-page lookup on cancellation too - The release runs under NonCancellable, in parallel with the descriptions, and in a finally block on every other path (a failed or cancelled read of the array included); a failing description cancels the others again. - The release never fails the lookup, its own timeout included. - KDoc: what includeFrames reads with the setting on, and that a command cut with "Inspected target navigated or closed" is thrown, as off. --- .../kotlin/dev/kdriver/core/browser/Config.kt | 3 +- .../kotlin/dev/kdriver/core/tab/DefaultTab.kt | 59 ++++++++++--------- .../kotlin/dev/kdriver/core/tab/Tab.kt | 4 +- .../dev/kdriver/core/tab/LookupsInPageTest.kt | 38 ++++++++++-- 4 files changed, 71 insertions(+), 33 deletions(-) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt index e844868d4..21739fe70 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt @@ -74,7 +74,8 @@ class Config( * on a busy page the connection may count as idle sooner. * - **Navigation**: an object or execution context dropped by a navigation during the lookup counts as no match * (`select` tries again), as a node gone from a document read does off; when only some matches of - * `querySelectorAll` are gone, none is returned rather than part of the old page's. + * `querySelectorAll` are gone, none is returned rather than part of the old page's. A command Chrome cuts with + * "Inspected target navigated or closed" (also sent for a closed tab) is thrown, as off. * - **Errors**: an invalid selector throws an [dev.kdriver.core.exceptions.EvaluateException] (the page's * `SyntaxError`) instead of a [dev.kdriver.cdp.CDPException]. The page's own `document.querySelector` is used: * a page that replaces it changes the result. diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt index 7dc03a783..43151415e 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt @@ -19,11 +19,13 @@ import io.ktor.util.logging.* import io.ktor.utils.io.core.* import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay -import kotlinx.coroutines.supervisorScope +import kotlinx.coroutines.withContext import kotlinx.io.buffered import kotlinx.io.files.Path import kotlinx.io.files.SystemFileSystem @@ -471,40 +473,43 @@ open class DefaultTab( " return all.length ? all : null; })()" ) ?: return emptyList() val arrayId = array.objectId!! - val properties = try { - unlessGone { runtime.getProperties(objectId = arrayId, ownProperties = true).result } ?: return emptyList() - } catch (e: CDPException) { - releaseQuietly(arrayId) - throw e - } - val matches = properties - .mapNotNull { property -> property.name.toIntOrNull()?.let { index -> index to property.value } } - .sortedBy { it.first } - .mapNotNull { (_, value) -> value?.takeIf { it.objectId != null } } - // supervisorScope: a description that fails does not cancel the release, which is a cleanup that never fails. - return supervisorScope { - // The array is no longer needed: released while the matches are described, at no extra wait. - val release = async { releaseQuietly(arrayId) } - val described = try { - matches.map { match -> async { describeMatch(match) } }.awaitAll() - } finally { - release.await() + // The array is a cleanup to release on every path, cancellation included (NonCancellable); while the matches + // are described, in parallel with them, at no extra wait. Gone with the page, it needs no release. + var release: Deferred? = null + var gone = false + try { + val properties = unlessGone { runtime.getProperties(objectId = arrayId, ownProperties = true).result } + if (properties == null) { + gone = true + return emptyList() + } + val matches = properties + .mapNotNull { property -> property.name.toIntOrNull()?.let { index -> index to property.value } } + .sortedBy { it.first } + .mapNotNull { (_, value) -> value?.takeIf { it.objectId != null } } + return coroutineScope { + release = async(NonCancellable) { releaseQuietly(arrayId) } + val described = matches.map { match -> async { describeMatch(match) } }.awaitAll() + // A match gone before it was described means the page navigated during the lookup: no match at all, + // as for one lookup, rather than a part of the old page's matches. + if (null in described) emptyList() else described.filterNotNull() + } + } finally { + val pending = release + withContext(NonCancellable) { + if (pending != null) pending.await() else if (!gone) releaseQuietly(arrayId) } - // A match gone before it was described means the page navigated during the lookup: no match at all, as - // for one lookup, rather than a part of the old page's matches. - if (null in described) emptyList() else described.filterNotNull() } } - // Releases a remote object the lookup no longer needs. A cleanup: its failure never fails the lookup (the page - // drops the object at its next navigation anyway). + // Releases a remote object the lookup no longer needs. A cleanup, always run under NonCancellable, so a + // CancellationException here is the command's own timeout, never the caller's cancellation: no failure of it ever + // fails the lookup (the page drops the object at its next navigation anyway). private suspend fun releaseQuietly(objectId: String) { try { runtime.releaseObject(objectId) - } catch (e: CancellationException) { - throw e } catch (_: Exception) { - // Already gone, or the connection is closing: nothing to clean up. + // Already gone, timed out, or the connection is closing: nothing to clean up. } } diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt b/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt index 47e4f410c..614ab2c6b 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt @@ -333,7 +333,9 @@ interface Tab : Connection { * Can also be used to wait for such elements to appear. Optionally includes results from iframes. * * With [dev.kdriver.core.browser.Config.lookupsInPage], the page runs the selector instead of the whole document - * being read; the elements then carry no node id nor tree. See that setting for every difference. With [includeFrames], the document is read as without that setting. + * being read; the elements then carry no node id nor tree. See that setting for every difference. + * With [includeFrames], `selectAll` reads the document even with that setting on, for the page's own matches too: + * they then carry a node id and a tree, as without it. * * @param selector CSS selector, e\.g\., `a[href]`, `button[class*=close]`, `a > img[src]` * @param timeout Raise timeout exception when after this many milliseconds nothing is found. diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt index 3b7f3ca5a..c12690a68 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt @@ -14,7 +14,10 @@ import dev.kdriver.core.param import dev.kdriver.core.valueReply import io.mockk.every import io.mockk.mockk +import kotlinx.coroutines.launch import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.runTest import kotlin.test.Test @@ -420,12 +423,19 @@ class LookupsInPageTest { } @Test - fun aDescriptionThatFails_isThrown_andTheArrayIsStillReleased() = runTest(StandardTestDispatcher()) { + fun aDescriptionThatFails_isThrown_stopsTheOthers_andTheArrayIsStillReleased() = runTest(StandardTestDispatcher()) { val tab = tab(lookupsInPage = true) { when (it.method) { "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) - "Runtime.getProperties" -> Reply.ok(arrayOfOne) - "DOM.describeNode" -> Reply.error("Message is too large") + "Runtime.getProperties" -> Reply.ok( + """{"result":[""" + + """{"name":"0","configurable":true,"enumerable":true,"value":{"type":"object","subtype":"node","objectId":"li-0"}},""" + + """{"name":"1","configurable":true,"enumerable":true,"value":{"type":"object","subtype":"node","objectId":"li-1"}}""" + + """]}""" + ) + "DOM.describeNode" -> + if (it.param("objectId") == "li-0") Reply.error("Message is too large", latency = 10) + else Reply.ok(item(20, "Beta"), latency = 1_000) "Runtime.releaseObject" -> Reply.ok(latency = 50) else -> Reply.ok() } @@ -433,7 +443,27 @@ class LookupsInPageTest { assertFailsWith { tab.querySelectorAll(".item") } assertEquals("array", tab.transport.sent.single { it.method == "Runtime.releaseObject" }.param("objectId")) - assertEquals(50, testScheduler.currentTime, "the release was awaited, not cancelled") + assertEquals(50, testScheduler.currentTime, "the release was awaited, the other description was not") + tab.close() + } + + @Test + fun aLookupCancelledWhileTheArrayIsRead_stillReleasesIt() = runTest(StandardTestDispatcher()) { + val tab = tab(lookupsInPage = true) { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) + "Runtime.getProperties" -> Reply.ok(arrayOfOne, latency = 1_000) + else -> Reply.ok() + } + } + + val lookup = launch { tab.querySelectorAll(".item") } + advanceTimeBy(100) + lookup.cancel() + advanceUntilIdle() + + assertTrue(lookup.isCancelled) + assertEquals("array", tab.transport.sent.single { it.method == "Runtime.releaseObject" }.param("objectId")) tab.close() } From ed8b3f7e5f7d5fc401794ca81de2cac0c3b94467 Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Fri, 20 Nov 2026 15:02:39 +0100 Subject: [PATCH 06/16] perf: page-wide lookups always run in the page, without a setting Config.lookupsInPage, ConfigBuilder.lookupsInPage and Config.Defaults.LOOKUPS_IN_PAGE are removed (never released): select, selectAll, querySelector and querySelectorAll without a node always run the selector in the page and describe only the matches. - An invalid selector throws the same CDPException as the document lookup did (DOM.querySelector or DOM.querySelectorAll, code -32000, "DOM Error while querying"), after disabling the DOM agent as before; any other exception of the page stays an EvaluateException. - A lookup under an element or a bare node found in the page binds it to the document first (node ids, tree), without resolving its object again. - The KDoc of Tab.querySelector and the quickstart describe how lookups work. --- README.md | 4 +- .../kotlin/dev/kdriver/core/browser/Config.kt | 49 --- .../dev/kdriver/core/browser/ConfigBuilder.kt | 7 - .../dev/kdriver/core/dom/DefaultElement.kt | 11 + .../kotlin/dev/kdriver/core/tab/DefaultTab.kt | 94 +++-- .../kotlin/dev/kdriver/core/tab/Tab.kt | 49 ++- .../dev/kdriver/core/browser/ConfigTest.kt | 11 - .../dev/kdriver/core/tab/DocumentReuseTest.kt | 82 +++-- .../kdriver/core/tab/LookupBehaviourTest.kt | 8 +- .../core/tab/LookupsInPageBehaviourTest.kt | 204 +++++++---- .../dev/kdriver/core/tab/LookupsInPageTest.kt | 325 ++++++++++++------ .../dev/kdriver/core/tab/SettledLookupTest.kt | 17 +- docs/home/quickstart.md | 66 ++-- 13 files changed, 566 insertions(+), 361 deletions(-) diff --git a/README.md b/README.md index 77f743e13..652f885f6 100644 --- a/README.md +++ b/README.md @@ -30,8 +30,8 @@ to heavy tools like Selenium or Puppeteer — all without relying on WebDriver. * **No external dependencies** – kdriver interacts directly with the browser using WebSockets and JSON — no need for Chromium wrappers or native libraries. * **Session and cookie management** – Start with a clean profile every time or load/save cookies between runs. -* **Remote browsers** – Attach to a browser behind a reverse proxy, and, with `lookupsInPage`, look elements up without - transferring the whole document (see [the quickstart](docs/home/quickstart.md#lookups-on-a-remote-browser)). +* **Remote browsers** – Attach to a browser behind a reverse proxy; CSS lookups run in the page and never transfer the + whole document (see [how lookups work](docs/home/quickstart.md#how-lookups-work)). * **Element utilities** – Coming soon: intuitive APIs to query, interact with, and wait for DOM elements. ## Motivation diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt index 21739fe70..a0eed7272 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/Config.kt @@ -48,51 +48,6 @@ class Config( * in front of the browser, e.g. `mapOf("Authorization" to "Bearer …")`. Empty by default. */ val connectionHeaders: Map = emptyMap(), - /** - * Whether a CSS selector lookup on the whole page asks the page itself instead of reading the whole document. - * - * Concerns [dev.kdriver.core.tab.Tab.select], [dev.kdriver.core.tab.Tab.selectAll], - * [dev.kdriver.core.tab.Tab.querySelector] and [dev.kdriver.core.tab.Tab.querySelectorAll] called without a node. - * Off (the default), each of these reads the whole document (`DOM.getDocument`, depth -1, piercing) whenever the - * page changed since the last read, which is after every navigation and on any live page, then queries it by node - * id. On a large page that is a transfer of the size of the whole DOM (often a megabyte) per lookup. - * - * On, the page runs the selector (`Runtime.evaluate` of `document.querySelector` / `querySelectorAll`, the - * selector passed as a JSON string literal) and only the match is described (`DOM.describeNode`, depth -1, - * piercing). What changes for the caller: - * - * - **Elements**: they carry their node and its subtree (so [dev.kdriver.core.dom.Element.text], - * [dev.kdriver.core.dom.Element.textAll], attributes and children read the same), but no node id - * (`node.nodeId` is 0) and no [dev.kdriver.core.dom.Element.tree]: [dev.kdriver.core.dom.Element.parent] - * throws until [dev.kdriver.core.dom.Element.update] is called, which reads the document as before. Each element - * keeps the remote object the page returned, so its first call (`click`, `apply`, …) needs no `DOM.resolveNode`. - * - **Shadow DOM and iframes**: same results as off: neither `document.querySelector` nor `DOM.querySelector` on - * the document looks inside a shadow root or an iframe. `selectAll(includeFrames = true)` reads the document as - * off (searching inside the iframes needs it), for the page's own matches too. - * - **Waiting**: `select` and `selectAll` poll and time out as before. Until something reads the document again - * (a lookup under an element, `find`, `update`…), the browser sends no `DOM.*` mutation events for the page, so - * on a busy page the connection may count as idle sooner. - * - **Navigation**: an object or execution context dropped by a navigation during the lookup counts as no match - * (`select` tries again), as a node gone from a document read does off; when only some matches of - * `querySelectorAll` are gone, none is returned rather than part of the old page's. A command Chrome cuts with - * "Inspected target navigated or closed" (also sent for a closed tab) is thrown, as off. - * - **Errors**: an invalid selector throws an [dev.kdriver.core.exceptions.EvaluateException] (the page's - * `SyntaxError`) instead of a [dev.kdriver.cdp.CDPException]. The page's own `document.querySelector` is used: - * a page that replaces it changes the result. - * - **Round trips**: `querySelector` costs two small ones (evaluate, describe) instead of a document read and a - * query; `querySelectorAll` costs one when nothing matches, three otherwise (evaluate, the array's properties, - * then every match described in parallel). Each match is described with its subtree: many matches, or nested - * ones, can transfer more than the document would: leave the setting off for a selector that matches most of - * the page. Each element holds its remote object until the page navigates, as one used off does after its first - * call; the array of `querySelectorAll` is released (one more command, sent with the descriptions). - * - **Elements passed back**: a lookup under such an element ([dev.kdriver.core.dom.Element.querySelector], or a - * [dev.kdriver.core.dom.NodeOrElement.WrappedElement] passed to `querySelector`) updates it from the document - * first. - * - * Lookups under a node or an element ([dev.kdriver.core.dom.Element.querySelector], `find`, `findAll`, `xpath`) - * are unchanged and still read the document. Off by default. - */ - val lookupsInPage: Boolean = Defaults.LOOKUPS_IN_PAGE, ) { private val logger = KtorSimpleLogger("Config") @@ -213,7 +168,6 @@ class Config( debugStringLimit = debugStringLimit, browserUrl = browserUrl, connectionHeaders = connectionHeaders, - lookupsInPage = lookupsInPage, ).also { copy -> // Copy the backing field, never the userDataDir getter: reading it would materialise a // temporary profile directory on a config that may never be started. @@ -260,9 +214,6 @@ class Config( const val IDLE_WAIT_TIMEOUT: Long = 10_000 const val AUTO_DISCOVER_TARGETS: Boolean = true const val DEBUG_STRING_LIMIT: Int = 128 - - /** See [Config.lookupsInPage]: off by default, lookups read the whole document. */ - const val LOOKUPS_IN_PAGE: Boolean = false } } diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/browser/ConfigBuilder.kt b/core/src/commonMain/kotlin/dev/kdriver/core/browser/ConfigBuilder.kt index cbd32082d..9371a2a34 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/browser/ConfigBuilder.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/browser/ConfigBuilder.kt @@ -47,12 +47,6 @@ class ConfigBuilder { */ var connectionHeaders: Map = emptyMap() - /** - * Whether selector lookups on the whole page ask the page instead of reading the whole document. See - * [Config.lookupsInPage] for what changes. - */ - var lookupsInPage: Boolean = Defaults.LOOKUPS_IN_PAGE - /** * Builds the Config instance with the configured parameters. */ @@ -76,7 +70,6 @@ class ConfigBuilder { debugStringLimit = debugStringLimit, browserUrl = browserUrl, connectionHeaders = connectionHeaders, - lookupsInPage = lookupsInPage, ) } } diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt b/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt index 342539df8..8f9e44ea0 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt @@ -99,6 +99,17 @@ open class DefaultElement( remoteObjectBackendNodeId = node.backendNodeId } + /** + * Binds an element found in the page (no node id, no [tree]) to the whole document, as [update] does, without + * resolving its object again: [node] becomes the document's node of the same backend node id, with its node ids, + * and [tree] the document. Used before a lookup under this element, which queries it by node id. + */ + internal suspend fun bindToDocument() { + val doc = currentDocument() + doc.filterRecurse { it.backendNodeId == node.backendNodeId }?.let { node = it } + tree = doc + } + override suspend fun updateRemoteObject(): Runtime.RemoteObject? { val resolvedFor = backendNodeId remoteObject = tab.dom.resolveNode(backendNodeId = resolvedFor).`object` diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt index 43151415e..395323d70 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt @@ -409,7 +409,7 @@ open class DefaultTab( val items = mutableListOf() if (includeFrames) { // Searching inside the frames reads the document (Element.querySelectorAll), so the whole lookup goes - // through it, Config.lookupsInPage or not: the frames and the page's own matches come from one read. + // through it: the frames and the page's own matches come from one read. for (fr in querySelectorAllInDocument("iframe")) items.addAll(fr.querySelectorAll(trimmedSelector)) items.addAll(querySelectorAllInDocument(trimmedSelector)) } else { @@ -450,27 +450,24 @@ open class DefaultTab( selector: String, node: NodeOrElement?, ): List = - if (node == null && lookupsInPage) querySelectorAllInPage(selector) - else if (node == null) querySelectorAllInDocument(selector) - else querySelectorAllInternal(selector, node, retried = false, boundRootOf(node)) + if (node == null) querySelectorAllInPage(selector) + else bound(node).let { querySelectorAllInternal(selector, it, retried = false, rootOf(it)) } - // querySelectorAll on the whole document read (kept while the page has not changed), whatever Config.lookupsInPage. + // querySelectorAll on the whole document read (kept while the page has not changed): the frames of + // selectAll(includeFrames = true), which need the document to be searched. private suspend fun querySelectorAllInDocument(selector: String): List = onDocument { doc -> querySelectorAllInternal(selector, null, retried = false, doc) } - // Config.lookupsInPage of the browser this tab belongs to; off for a tab without one. - private val lookupsInPage: Boolean - get() = owner?.let { browser -> browser.config.lookupsInPage } == true - /** * `document.querySelectorAll(selector)` run by the page, each match then described with its subtree: see - * [dev.kdriver.core.browser.Config.lookupsInPage]. One round trip when nothing matches (the page answers `null`), - * otherwise three: the evaluation, the array's own properties, and the descriptions, sent together. + * [Tab.querySelector]. One round trip when nothing matches (the page answers `null`), otherwise three: the + * evaluation, the array's own properties, and the descriptions, sent together. */ private suspend fun querySelectorAllInPage(selector: String): List { val array = evaluateLookup( "(() => { const all = Array.from(document.querySelectorAll(${jsStringLiteral(selector)}));" + - " return all.length ? all : null; })()" + " return all.length ? all : null; })()", + protocolMethod = "DOM.querySelectorAll", ) ?: return emptyList() val arrayId = array.objectId!! // The array is a cleanup to release on every path, cancellation included (NonCancellable); while the matches @@ -515,23 +512,41 @@ open class DefaultTab( /** * `document.querySelector(selector)` run by the page, the match then described with its subtree: see - * [dev.kdriver.core.browser.Config.lookupsInPage]. Two round trips when something matches, one otherwise. + * [Tab.querySelector]. Two round trips when something matches, one otherwise. */ private suspend fun querySelectorInPage(selector: String): Element? { - val match = evaluateLookup("document.querySelector(${jsStringLiteral(selector)})") ?: return null + val match = evaluateLookup( + "document.querySelector(${jsStringLiteral(selector)})", + protocolMethod = "DOM.querySelector", + ) ?: return null return describeMatch(match) } /** * Evaluates [expression] in the page and returns the object it yields, or null when it yields no object (`null`). - * An exception thrown by the page (an invalid selector) is thrown as an [EvaluateException]. + * + * An invalid selector makes the page throw a `SyntaxError`: it is thrown as the error the browser gives + * [protocolMethod] (`DOM.querySelector` or `DOM.querySelectorAll`) for that selector, a [CDPException] with code + * -32000 and the message "DOM Error while querying", after disabling the DOM agent, as a lookup on the document + * did. Any other exception of the page (a page that replaced `document.querySelector`) is thrown as an + * [EvaluateException]. */ - private suspend fun evaluateLookup(expression: String): Runtime.RemoteObject? { + private suspend fun evaluateLookup(expression: String, protocolMethod: String): Runtime.RemoteObject? { val evaluated = unlessGone { runtime.evaluate(expression = expression) } ?: return null - evaluated.exceptionDetails?.let { throw EvaluateException(it) } + evaluated.exceptionDetails?.let { details -> + if (details.isSyntaxError()) { + disableDomAgent() + throw CDPException(protocolMethod, INVALID_SELECTOR_CODE, INVALID_SELECTOR_MESSAGE, null) + } + throw EvaluateException(details) + } return evaluated.result.takeIf { it.objectId != null } } + // The `SyntaxError` (a DOMException) the page throws for a selector it cannot parse. + private fun Runtime.ExceptionDetails.isSyntaxError(): Boolean = + exception?.description?.startsWith("SyntaxError") == true + /** * The element of [match], a remote object the page returned: its node and subtree (`DOM.describeNode`, depth -1, * piercing), with [match] kept so its first call needs no `DOM.resolveNode`. Null when the browser no longer knows @@ -600,43 +615,53 @@ open class DefaultTab( node: NodeOrElement?, ): Element? { val trimmedSelector = selector.trim() - return if (node == null && lookupsInPage) { + return if (node == null) { querySelectorInPage(trimmedSelector) - } else if (node == null) { - onDocument { doc -> querySelectorInternal(trimmedSelector, null, retried = false, doc) } } else { - querySelectorInternal(trimmedSelector, node, retried = false, boundRootOf(node)) + bound(node).let { querySelectorInternal(trimmedSelector, it, retried = false, rootOf(it)) } } } - // rootOf for a lookup under [node], once an element found with Config.lookupsInPage (no node id yet) has been - // updated from the document. - private suspend fun boundRootOf(node: NodeOrElement): DOM.Node { - if (node is NodeOrElement.WrappedElement && node.node.nodeId == 0) node.element.update() - return rootOf(node) + /** + * [node] ready for a lookup under it, which queries it by node id. A node found in the page has none yet (see + * [Tab.querySelector]): it is first bound to the document, an element filled from it + * ([DefaultElement.bindToDocument], [Element.update] for another implementation), a bare node replaced by the + * document's node of the same backend node id. + */ + private suspend fun bound(node: NodeOrElement): NodeOrElement { + if (node.node.nodeId != 0) return node + return when (node) { + is NodeOrElement.WrappedElement -> { + val element = node.element + if (element is DefaultElement) element.bindToDocument() else element.update() + node + } + + is NodeOrElement.WrappedNode -> currentDocument().first + .filterRecurse { it.backendNodeId == node.node.backendNodeId } + ?.let { NodeOrElement.WrappedNode(it) } ?: node + } } // The node a lookup under [node] queries: the document of a frame, the node itself otherwise. private fun rootOf(node: NodeOrElement): DOM.Node = if (node.node.nodeName == "IFRAME") node.node.contentDocument ?: node.node else node.node - // See querySelectorAllInternal: `retried` must be a parameter so the retry-once guard survives - // the recursive call (ISSUE-7). + // A lookup under [node] (the page runs the lookups on the whole document). See querySelectorAllInternal: + // `retried` must be a parameter so the retry-once guard survives the recursive call (ISSUE-7). private suspend fun querySelectorInternal( selector: String, - node: NodeOrElement?, + node: NodeOrElement, retried: Boolean, doc: DOM.Node, ): Element? { val nodeId = try { dom.querySelector(doc.nodeId, selector) } catch (e: Exception) { - if (node != null && e.message?.contains("could not find node", ignoreCase = true) == true) { + if (e.message?.contains("could not find node", ignoreCase = true) == true) { if (retried) return null if (node is NodeOrElement.WrappedElement) node.element.update() return querySelectorInternal(selector, node, retried = true, rootOf(node)) - } else if (e.message?.contains("could not find node", ignoreCase = true) == true) { - return null } else { disableDomAgent() throw e @@ -972,3 +997,8 @@ private val GONE = listOf( "cannot find context", "context was destroyed", ) + +/** The code and message Chrome answers `DOM.querySelector(All)` with for a selector it cannot parse. */ +private const val INVALID_SELECTOR_CODE = -32000 +private const val INVALID_SELECTOR_MESSAGE = "DOM Error while querying" + diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt b/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt index 614ab2c6b..88622b2fb 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt @@ -294,8 +294,8 @@ interface Tab : Connection { * * This method waits for the element to appear in the DOM, retrying every 500 milliseconds until the timeout is reached. * - * With [dev.kdriver.core.browser.Config.lookupsInPage], the page runs the selector instead of the whole document - * being read; the elements then carry no node id nor tree. See that setting for every difference. + * The page runs the selector, and the element has no node id nor tree until [Element.update]: see + * [querySelector] for how lookups work. * * @param selector The CSS selector of the element to select. * @param timeout The maximum time in milliseconds to wait for the element to appear. Defaults to 10 seconds. @@ -332,10 +332,9 @@ interface Tab : Connection { * * Can also be used to wait for such elements to appear. Optionally includes results from iframes. * - * With [dev.kdriver.core.browser.Config.lookupsInPage], the page runs the selector instead of the whole document - * being read; the elements then carry no node id nor tree. See that setting for every difference. - * With [includeFrames], `selectAll` reads the document even with that setting on, for the page's own matches too: - * they then carry a node id and a tree, as without it. + * The page runs the selector, and the elements have no node id nor tree until [Element.update]: see + * [querySelector] for how lookups work. With [includeFrames], `selectAll` reads the whole document instead + * (searching inside the frames needs it), for the page's own matches too: they then have a node id and a tree. * * @param selector CSS selector, e\.g\., `a[href]`, `button[class*=close]`, `a > img[src]` * @param timeout Raise timeout exception when after this many milliseconds nothing is found. @@ -383,8 +382,10 @@ interface Tab : Connection { * * It returns all matching [Element] objects. * - * With [dev.kdriver.core.browser.Config.lookupsInPage], the page runs the selector instead of the whole document - * being read; the elements then carry no node id nor tree. See that setting for every difference. + * Without [node], the page runs `document.querySelectorAll` and the matches are described together, in document + * order: one round trip when nothing matches, three otherwise (the evaluation, the list of matches, then every + * description at once, with the release of the list). Each match is described with its subtree, so many matches, + * or nested ones, can add up to more than the document would. The elements are as for [querySelector]. * * @param selector CSS selector. (first time? See https://www.w3schools.com/cssref/css_selectors.php) * @param node For internal use. The node to start the search from. Defaults to the document root. @@ -399,8 +400,36 @@ interface Tab : Connection { /** * Finds a single element based on a CSS selector string. * - * With [dev.kdriver.core.browser.Config.lookupsInPage], the page runs the selector instead of the whole document - * being read; the elements then carry no node id nor tree. See that setting for every difference. + * ## How lookups work + * + * Without [node] (and in [select], [selectAll] and [querySelectorAll] without it), the page runs the selector: + * `document.querySelector` is evaluated (`Runtime.evaluate`, the selector entering the script only as a JSON string + * literal), then only the match is described, with its subtree (`DOM.describeNode`, depth -1, piercing). The + * whole document is never read: two small round trips when something matches, one otherwise, whatever the size of + * the page. + * + * The element found: + * - has its node and subtree: [Element.tag], [Element.text], [Element.textAll], attributes, + * [Element.children] and [Element.backendNodeId] read as from a document; + * - keeps the object the page returned, so its first call (`click`, `apply`, …) needs no `DOM.resolveNode`; + * - has no node id yet: `node.nodeId` and the node ids of its subtree are 0, [Element.parentId] and + * [Element.tree] are null and [Element.parent] throws, until [Element.update] reads the document, which also + * binds it. A lookup under the element ([Element.querySelector], or a [NodeOrElement] passed back here) binds it + * first by itself. These are plain properties, so the first read of one cannot fetch the document on its own. + * + * What else differs from reading the document: + * - the page's own `document.querySelector` runs: a page that replaces it changes the result; + * - each element holds the remote object of its match until the page navigates (an element read from the document + * holds one only after its first call); + * - until something reads the document (a lookup under an element, [find], [Element.update]…), the browser sends + * no `DOM.*` mutation events for the page, so on a busy page the connection may count as idle sooner. + * + * Unchanged: shadow roots and iframes are not searched; an invalid selector throws the [dev.kdriver.cdp.CDPException] + * the browser gives `DOM.querySelector` (code -32000, "DOM Error while querying"), `DOM.querySelectorAll` for the + * other methods; a node or execution context dropped by a navigation during the lookup counts as no match, so + * [select] tries again (for [querySelectorAll], none of the old page's matches is returned). + * + * Lookups under a node or an element, [find], [findAll] and [xpath] read the document, as before. * * @param selector CSS selector(s). * @param node For internal use. The node to start the search from. Defaults to the document root. diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/ConfigTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/ConfigTest.kt index 1b925f782..87b7a4a19 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/browser/ConfigTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/browser/ConfigTest.kt @@ -184,15 +184,4 @@ class ConfigTest { assertTrue(args.contains("--disable-site-isolation-trials")) } - @Test - fun lookupsInPage_isOffByDefault_andKeptByCopyAndTheBuilder() { - assertFalse(Config(browserExecutablePath = Path("/usr/bin/chromium")).lookupsInPage) - - val on = Config(browserExecutablePath = Path("/usr/bin/chromium"), lookupsInPage = true) - assertTrue(on.copy().lookupsInPage) - - assertTrue(config { browserExecutablePath = Path("/usr/bin/chromium"); lookupsInPage = true }.lookupsInPage) - assertFalse(config { browserExecutablePath = Path("/usr/bin/chromium") }.lookupsInPage) - } - } diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/DocumentReuseTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/DocumentReuseTest.kt index b4f5bdbf9..f81db5f9d 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/DocumentReuseTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/DocumentReuseTest.kt @@ -25,11 +25,10 @@ import kotlin.test.assertSame import kotlin.test.assertTrue /** - * A lookup on the whole document ([DefaultTab.select], [DefaultTab.selectAll], [DefaultTab.find], - * [DefaultTab.findAll], [DefaultTab.querySelector], [DefaultTab.querySelectorAll], `Element.update`) reads the document - * again only when the page may have changed since the last read: a `DOM.*` event, a command that makes the browser - * forget its node ids, or a reconnect. Otherwise a new read would return the same tree, and the round trip (the whole - * tree, often a megabyte) is saved. + * A lookup that reads the whole document ([DefaultTab.selectAll] with frames, [DefaultTab.find], [DefaultTab.findAll], + * `Element.update`, a lookup under an element found in the page) reads it again only when the page may have changed + * since the last read: a `DOM.*` event, a command that makes the browser forget its node ids, or a reconnect. + * Otherwise a new read would return the same tree, and the round trip (the whole tree, often a megabyte) is saved. */ class DocumentReuseTest { @@ -53,7 +52,9 @@ class DocumentReuseTest { "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO, latency = 10) "DOM.getDocument" -> Reply.ok(document, latency = 10) "DOM.querySelector" -> Reply.ok("""{"nodeId":7}""", latency = 10) - "DOM.querySelectorAll" -> Reply.ok("""{"nodeIds":[7,9]}""", latency = 10) + "DOM.querySelectorAll" -> + if (it.params.toString().contains("iframe")) Reply.ok("""{"nodeIds":[]}""", latency = 10) + else Reply.ok("""{"nodeIds":[7,9]}""", latency = 10) "DOM.performSearch" -> Reply.ok("""{"searchId":"s1","resultCount":1}""", latency = 10) "DOM.getSearchResults" -> Reply.ok("""{"nodeIds":[8]}""", latency = 10) "DOM.resolveNode" -> Reply.ok(objectReply("obj-${it.id}"), latency = 10) @@ -70,15 +71,18 @@ class DocumentReuseTest { private val ScriptedTransport.documentReads get() = methods.count { it == "DOM.getDocument" } + // A selector lookup that reads the document: selectAll with frames (no frame on this page), then the page's matches. + private suspend fun ScriptedTab.lookUp() = selectAll("#go", timeout = 1_000, includeFrames = true).first() + @Test - fun select_onAnUnchangedPage_readsTheDocumentOnce() = runTest(StandardTestDispatcher()) { + fun aLookup_onAnUnchangedPage_readsTheDocumentOnce() = runTest(StandardTestDispatcher()) { val (tab, transport) = scripted() - val first = tab.select("#go", timeout = 1_000) - val second = tab.select("#go", timeout = 1_000) + val first = tab.lookUp() + val second = tab.lookUp() assertEquals(1, transport.documentReads) - assertEquals(2, transport.methods.count { it == "DOM.querySelector" }) + assertEquals(4, transport.methods.count { it == "DOM.querySelectorAll" }, "frames, then the page, twice") assertEquals("Send", second.text) assertEquals(first.backendNodeId, second.backendNodeId) assertSame(first.tree, second.tree, "both elements sit in the same, unchanged tree") @@ -89,7 +93,7 @@ class DocumentReuseTest { fun selectAll_findAll_andUpdate_shareTheDocumentOfAnUnchangedPage() = runTest(StandardTestDispatcher()) { val (tab, transport) = scripted() - val all = tab.selectAll("button, li", timeout = 1_000) + val all = tab.selectAll("button, li", timeout = 1_000, includeFrames = true) val found = tab.findAll("Send", timeout = 1_000) all.first().update() @@ -103,10 +107,10 @@ class DocumentReuseTest { fun aDomEventBetweenLookups_makesTheNextOneReadTheDocumentAgain() = runTest(StandardTestDispatcher()) { val (tab, transport) = scripted() - tab.select("#go", timeout = 1_000) + tab.lookUp() transport.event("DOM.attributeModified", """{"nodeId":7,"name":"class","value":"busy"}""") runCurrent() - tab.select("#go", timeout = 1_000) + tab.lookUp() assertEquals(2, transport.documentReads) tab.close() @@ -116,10 +120,10 @@ class DocumentReuseTest { fun otherEvents_doNotMakeTheDocumentStale() = runTest(StandardTestDispatcher()) { val (tab, transport) = scripted() - tab.select("#go", timeout = 1_000) + tab.lookUp() transport.event("Network.dataReceived", """{"requestId":"r","timestamp":1,"dataLength":1}""") runCurrent() - tab.select("#go", timeout = 1_000) + tab.lookUp() assertEquals(1, transport.documentReads) tab.close() @@ -129,11 +133,11 @@ class DocumentReuseTest { fun disablingTheDomAgent_makesTheNextLookupReadTheDocumentAgain() = runTest(StandardTestDispatcher()) { val (tab, transport) = scripted() - tab.select("#go", timeout = 1_000) + tab.lookUp() tab.dom.disable() - tab.select("#go", timeout = 1_000) + tab.lookUp() tab.find("Send", timeout = 1_000) // disables the agent when it is done - tab.select("#go", timeout = 1_000) + tab.lookUp() assertEquals(3, transport.documentReads, "the find used the document kept since the second select") tab.close() @@ -143,9 +147,9 @@ class DocumentReuseTest { fun aDocumentReadByHand_makesTheNextLookupReadItAgain() = runTest(StandardTestDispatcher()) { val (tab, transport) = scripted() - tab.select("#go", timeout = 1_000) + tab.lookUp() tab.dom.getDocument(depth = 1) - tab.select("#go", timeout = 1_000) + tab.lookUp() assertEquals(3, transport.documentReads) tab.close() @@ -162,9 +166,9 @@ class DocumentReuseTest { } transport = t - assertEquals("Send", tab.select("#go", timeout = 1_000).text) - tab.select("#go", timeout = 1_000) - tab.select("#go", timeout = 1_000) + assertEquals("Send", tab.lookUp().text) + tab.lookUp() + tab.lookUp() assertEquals(2, transport.documentReads, "read again once, then kept") tab.close() @@ -175,7 +179,7 @@ class DocumentReuseTest { var queries = 0 lateinit var transport: ScriptedTransport val (tab, t) = scripted { - if (it.method == "DOM.querySelector" && ++queries == 2) { + if (it.method == "DOM.querySelectorAll" && ++queries == 3) { transport.event( "DOM.childNodeInserted", """{"parentNodeId":1,"previousNodeId":7,"node":{"nodeId":11,"backendNodeId":110,"nodeType":1,""" + @@ -185,12 +189,15 @@ class DocumentReuseTest { } transport = t - tab.select("#go", timeout = 1_000) - val again = tab.select("#go", timeout = 1_000) + tab.lookUp() + val again = tab.lookUp() assertEquals("Send", again.text) assertEquals( - listOf("DOM.getDocument", "DOM.querySelector", "DOM.querySelector", "DOM.getDocument", "DOM.querySelector"), + listOf( + "DOM.getDocument", "DOM.querySelectorAll", "DOM.querySelectorAll", + "DOM.querySelectorAll", "DOM.getDocument", "DOM.querySelectorAll", "DOM.querySelectorAll", + ), transport.methods.filter { it.startsWith("DOM.") }, ) tab.close() @@ -199,16 +206,21 @@ class DocumentReuseTest { @Test fun aChangeReportedDuringALookupOnAFreshRead_doesNotRepeatIt() = runTest(StandardTestDispatcher()) { lateinit var transport: ScriptedTransport + var queries = 0 val (tab, t) = scripted { - if (it.method == "DOM.querySelector") { + if (it.method == "DOM.querySelectorAll" && ++queries == 1) { transport.event("DOM.attributeModified", """{"nodeId":7,"name":"a","value":"b"}""") } } transport = t - tab.select("#go", timeout = 1_000) + tab.lookUp() - assertEquals(listOf("DOM.getDocument", "DOM.querySelector"), transport.methods.filter { it.startsWith("DOM.") }) + assertEquals( + listOf("DOM.getDocument", "DOM.querySelectorAll", "DOM.getDocument", "DOM.querySelectorAll"), + transport.methods.filter { it.startsWith("DOM.") }, + "the query of the frames, on a fresh read, is not repeated; the next query reads the changed page", + ) tab.close() } @@ -226,10 +238,10 @@ class DocumentReuseTest { override fun createTransport(): WebSocketTransport = if (opened++ == 0) transports[0] else next() } - tab.select("#go", timeout = 1_000) + tab.lookUp() transports[0].close() runCurrent() - tab.select("#go", timeout = 1_000) + tab.lookUp() assertEquals(2, transports.size, "the second lookup ran on a new session") assertEquals(1, transports[1].documentReads) @@ -240,14 +252,14 @@ class DocumentReuseTest { fun anInvalidSelector_onAKeptDocument_stillThrowsTheBrowserError() = runTest(StandardTestDispatcher()) { val normal = page() val transport = ScriptedTransport(this) { - if (it.method == "DOM.querySelector" && it.params.toString().contains("li[")) { + if (it.method == "DOM.querySelectorAll" && it.params.toString().contains("li[")) { Reply.error("DOM Error while querying", latency = 10) } else normal(it) } val tab = ScriptedTab(this, transport) - tab.select("#go", timeout = 1_000) - assertFailsWith { tab.select("li[", timeout = 0) } + tab.lookUp() + assertFailsWith { tab.selectAll("li[", timeout = 0, includeFrames = true) } assertEquals(1, transport.documentReads, "the failing lookup used the kept document") assertTrue(transport.methods.contains("DOM.disable"), "and the agent is disabled on the error, as before") diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupBehaviourTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupBehaviourTest.kt index 23d7a4d26..5cd9edf5f 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupBehaviourTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupBehaviourTest.kt @@ -33,14 +33,16 @@ class LookupBehaviourTest { } @Test - fun select_returnsTheElementWithItsTextAttributesTreeAndParent() = withPage { + fun select_returnsTheElementWithItsTextAttributes_andTreeAndParentOnceUpdated() = withPage { val item = select("li[data-rank='2']", timeout = 5_000) assertEquals("li", item.tag) assertEquals("Beta", item.text) assertEquals("2", item["data-rank"]) assertEquals(listOf("class", "data-rank"), item.attrs) - assertNotNull(item.tree, "a looked-up element knows the document it is in") + assertNull(item.tree, "the page ran the lookup: no document was read") + item.update() + assertNotNull(item.tree, "an updated element knows the document it is in") assertEquals("ul", item.parent?.tag) assertEquals("list", item.parent?.get("id")) assertEquals(listOf("Alpha", "Beta", "Gamma"), item.parent!!.children.filter { it.tag == "li" }.map { it.text }) @@ -215,6 +217,6 @@ class LookupBehaviourTest { val again = select("li[data-rank='1']", timeout = 5_000) assertEquals("Alpha", again.text) - assertTrue(again.tree != null) + assertTrue(again.update().tree != null) } } diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt index 0ebd17be4..6a7be813f 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt @@ -1,9 +1,12 @@ package dev.kdriver.core.tab import dev.kdriver.cdp.CDPException +import dev.kdriver.cdp.domain.DOM +import dev.kdriver.cdp.domain.dom import dev.kdriver.core.browser.Browser import dev.kdriver.core.browser.createBrowser -import dev.kdriver.core.exceptions.EvaluateException +import dev.kdriver.core.dom.Element +import dev.kdriver.core.dom.NodeOrElement import dev.kdriver.core.exceptions.TimeoutWaitingForElementException import dev.kdriver.core.sampleFile import kotlinx.coroutines.CoroutineScope @@ -11,23 +14,21 @@ import kotlinx.coroutines.runBlocking import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith +import kotlin.test.assertNotEquals import kotlin.test.assertNotNull import kotlin.test.assertNull -import kotlin.test.assertTrue /** - * On a real page, the same lookups with [dev.kdriver.core.browser.Config.lookupsInPage] off and on find the same - * elements, with the same text, attributes, children and order, the same absence inside shadow roots and frames, and - * elements that can be clicked; what differs is documented on the setting (no node id, no tree, the error type). + * On a real page, the lookups the page runs (`select`, `selectAll`, `querySelector`, `querySelectorAll` without a + * node) find what a lookup on the whole document finds (`DOM.getDocument`, then `DOM.querySelector(All)` on it, as + * these methods did before): the same elements, text, attributes, children and order, the same absence inside shadow + * roots and frames, elements that can be clicked; once updated, the same node ids, tree and parent; and for an invalid + * selector, the same exception. */ class LookupsInPageBehaviourTest { - private fun onPage(lookupsInPage: Boolean, block: suspend Tab.() -> T): T = runBlocking { - val browser: Browser = createBrowser(this as CoroutineScope) { - headless = true - sandbox = false - this.lookupsInPage = lookupsInPage - } + private fun onPage(block: suspend Tab.() -> Unit) = runBlocking { + val browser: Browser = createBrowser(this as CoroutineScope, headless = true, sandbox = false) try { browser.get(sampleFile("lookup-test.html")).block() } finally { @@ -35,98 +36,167 @@ class LookupsInPageBehaviourTest { } } - /** Runs [block] with the setting off then on, and checks both give the same answer. */ - private fun sameInBothModes(block: suspend Tab.() -> T): T { - val off = onPage(lookupsInPage = false, block) - val on = onPage(lookupsInPage = true, block) - assertEquals(off, on) - return on - } + // A lookup on the whole document, as these methods did before: the document read, then queried by node id. + private suspend fun Tab.allOnTheDocument(selector: String): List = + querySelectorAll(selector, NodeOrElement.WrappedNode(dom.getDocument(depth = -1, pierce = true).root)) + + private suspend fun Tab.oneOnTheDocument(selector: String): Element? = + querySelector(selector, NodeOrElement.WrappedNode(dom.getDocument(depth = -1, pierce = true).root)) + + private fun Element.seen() = listOf(tag, text, textAll, attrs.joinToString(), backendNodeId.toString()) @Test - fun select_findsTheSameElement() { - val seen = sameInBothModes { - val item = select("li[data-rank='2']", timeout = 5_000) - listOf(item.tag, item.text, item.textAll, item["data-rank"], item.attrs.joinToString()) - } - assertEquals(listOf("li", "Beta", "Beta", "2", "class, data-rank"), seen) + fun select_findsWhatTheDocumentLookupFinds() = onPage { + val before = oneOnTheDocument("li[data-rank='2']")!! + + val item = select("li[data-rank='2']", timeout = 5_000) + + assertEquals(before.seen(), item.seen()) + assertEquals(listOf("li", "Beta", "Beta", "class, data-rank"), item.seen().take(4)) + assertNotNull(item.objectId, "the element keeps the object the page returned") } @Test - fun select_findsTheSameChildren() { - val seen = sameInBothModes { select("#list", timeout = 5_000).children.filter { it.tag == "li" }.map { it.text } } - assertEquals(listOf("Alpha", "Beta", "Gamma"), seen) + fun select_findsTheSameChildren() = onPage { + val before = oneOnTheDocument("#list")!!.children.map { it.seen() } + + val children = select("#list", timeout = 5_000).children.map { it.seen() } + + assertEquals(before, children) + assertEquals(3, children.count { it.first() == "li" }) } @Test - fun selectAll_findsTheSameElements_inTheSameOrder() { - val seen = sameInBothModes { selectAll(".item", timeout = 5_000).map { it.text to (it.backendNodeId > 0) } } - assertEquals(listOf("Alpha" to true, "Beta" to true, "Gamma" to true), seen) + fun selectAll_findsTheSameElements_inTheSameOrder() = onPage { + val before = allOnTheDocument(".item").map { it.seen() } + + val items = selectAll(".item", timeout = 5_000).map { it.seen() } + + assertEquals(before, items) + assertEquals(listOf("Alpha", "Beta", "Gamma"), items.map { it[1] }) } @Test - fun querySelectorAll_returnsNothing_forNoMatch() { - assertEquals(emptyList(), sameInBothModes { querySelectorAll(".nowhere").map { it.text } }) - assertNull(sameInBothModes { querySelector(".nowhere")?.text }) + fun noMatch_isNoMatch() = onPage { + assertEquals(emptyList(), allOnTheDocument(".nowhere")) + assertEquals(emptyList(), querySelectorAll(".nowhere")) + assertNull(oneOnTheDocument(".nowhere")) + assertNull(querySelector(".nowhere")) } @Test - fun select_doesNotPierceShadowRoots_inEitherMode() { - sameInBothModes { - assertFailsWith { select("#shadowed", timeout = 0) } - querySelectorAll("#shadowed").size - } + fun shadowRoots_areNotPierced() = onPage { + assertEquals(emptyList(), allOnTheDocument("#shadowed")) + assertEquals(emptyList(), querySelectorAll("#shadowed")) + assertFailsWith { select("#shadowed", timeout = 0) } } @Test - fun select_doesNotLookInsideFrames_butSelectAllWithFramesDoes_inEitherMode() { - val seen = sameInBothModes { - assertNull(querySelector("p.inner")) - selectAll("p.inner", timeout = 5_000, includeFrames = true).map { it.text } - } - assertEquals(listOf("Inside the frame"), seen) + fun frames_areNotSearched_butSelectAllWithFramesSearchesThem() = onPage { + assertNull(oneOnTheDocument("p.inner")) + assertNull(querySelector("p.inner")) + assertEquals(listOf("Inside the frame"), selectAll("p.inner", timeout = 5_000, includeFrames = true).map { it.text }) } @Test - fun aFoundElementCanBeClickedAndRead_inEitherMode() { - val seen = sameInBothModes { - rawEvaluate("document.getElementById('panel').onclick = () => document.getElementById('panel').dataset.state = 'open'") - select("#panel", timeout = 5_000).click() - select("#panel", timeout = 5_000)["data-state"] - } - assertEquals("open", seen) + fun aFoundElementCanBeClickedAndRead() = onPage { + rawEvaluate("document.getElementById('panel').onclick = () => document.getElementById('panel').dataset.state = 'open'") + + select("#panel", timeout = 5_000).click() + + assertEquals("open", select("#panel", timeout = 5_000)["data-state"]) } @Test - fun select_seesTheNewDocumentAfterANavigation_inEitherMode() { - val seen = sameInBothModes { - rawEvaluate("document.getElementById('title').textContent = 'Changed'") - val before = select("#title", timeout = 5_000).text - reload() - before to select("#title", timeout = 5_000).text - } - assertEquals("Changed" to "Lookup", seen) + fun select_seesTheNewDocumentAfterANavigation() = onPage { + rawEvaluate("document.getElementById('title').textContent = 'Changed'") + assertEquals("Changed", select("#title", timeout = 5_000).text) + + reload() + + assertEquals("Lookup", select("#title", timeout = 5_000).text) } @Test - fun withTheSettingOn_anElementHasNoTreeUntilUpdated() = onPage(lookupsInPage = true) { + fun anElementFoundInThePage_hasNoNodeIdTreeNorParent_untilUpdated() = onPage { val item = select("li[data-rank='3']", timeout = 5_000) - assertNull(item.tree) + assertEquals(0, item.node.nodeId) - assertNotNull(item.objectId, "the element keeps the object the page returned") + assertNull(item.parentId) + assertNull(item.tree) assertFailsWith { item.parent } item.update() - assertNotNull(item.tree) + assertNotEquals(0, item.node.nodeId) assertEquals("ul", item.parent?.tag) } @Test - fun anInvalidSelector_throwsTheBrowserErrorOff_andThePageErrorOn() { - onPage(lookupsInPage = false) { assertFailsWith { select("li[", timeout = 0) } } - val error = onPage(lookupsInPage = true) { assertFailsWith { select("li[", timeout = 0) } } - assertTrue(error.jsError.contains("SyntaxError"), error.jsError) + fun update_givesTheNodeIdsTreeAndParent_theDocumentLookupGives() = onPage { + // The same lookup on the whole document, read first: a later read gives every node a new id, so ids are + // compared below on the document the update read, and everything else on this earlier read. + val before = oneOnTheDocument("li[data-rank='3']")!! + val item = select("li[data-rank='3']", timeout = 5_000) + + item.update() + + val tree = assertNotNull(item.tree) + val onTheSameRead = querySelector("li[data-rank='3']", NodeOrElement.WrappedNode(tree))!! + assertEquals(onTheSameRead.node, item.node, "node, subtree and node ids of the document read") + assertEquals(onTheSameRead.parentId, item.parentId) + assertEquals(onTheSameRead.parent!!.node, item.parent!!.node) + assertEquals(item.node.nodeId, dom.querySelector(tree.nodeId, "li[data-rank='3']").nodeId, "a live node id") + assertEquals(item.node.parentId, item.parent!!.node.nodeId) + assertEquals(before.node.withoutIds(), item.node.withoutIds()) + assertEquals(before.parent!!.node.withoutIds(), item.parent!!.node.withoutIds()) + assertEquals(before.tree!!.withoutIds(), tree.withoutIds()) } + @Test + fun aLookupUnderAnElementFoundInThePage_bindsItFirst() = onPage { + val list = select("#list", timeout = 5_000) + + assertEquals("Gamma", list.querySelector("li[data-rank='3']")?.text) + assertEquals(listOf("Alpha", "Beta", "Gamma"), list.querySelectorAll("li").map { it.text }) + assertNotNull(list.tree) + assertEquals("body", list.parent?.tag) + } + + @Test + fun anInvalidSelector_throwsTheSameExceptionAsTheDocumentLookup() = onPage { + for (selector in listOf("li[", "", "a:unknown-pseudo")) { + val document = dom.getDocument(depth = -1, pierce = true).root + val one = assertFailsWith { dom.querySelector(document.nodeId, selector) } + val all = assertFailsWith { dom.querySelectorAll(document.nodeId, selector) } + + for (lookup in listOf Unit>({ select(selector, timeout = 0) }, { querySelector(selector) })) { + assertSameError(one, assertFailsWith { lookup() }) + } + for (lookup in listOf Unit>({ selectAll(selector, timeout = 0) }, { querySelectorAll(selector) })) { + assertSameError(all, assertFailsWith { lookup() }) + } + } + } + + private fun assertSameError(expected: CDPException, actual: CDPException) { + assertEquals(expected.method, actual.method) + assertEquals(expected.code, actual.code) + assertEquals(expected.originalMessage, actual.originalMessage) + assertEquals(expected.data, actual.data) + assertEquals(expected.message, actual.message) + } + + // The node and its subtree with every node id and parent id cleared: what two reads of the same page share. + private fun DOM.Node.withoutIds(): DOM.Node = copy( + nodeId = 0, + parentId = null, + children = children?.map { it.withoutIds() }, + contentDocument = contentDocument?.withoutIds(), + shadowRoots = shadowRoots?.map { it.withoutIds() }, + pseudoElements = pseudoElements?.map { it.withoutIds() }, + templateContent = templateContent?.withoutIds(), + importedDocument = importedDocument?.withoutIds(), + ) + } diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt index c12690a68..2e514ee43 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt @@ -2,18 +2,17 @@ package dev.kdriver.core.tab +import dev.kdriver.cdp.CDPException import dev.kdriver.core.ScriptedTab import dev.kdriver.core.ScriptedTransport import dev.kdriver.core.ScriptedTransport.Reply -import dev.kdriver.core.browser.Browser -import dev.kdriver.core.browser.Config +import dev.kdriver.core.dom.Element +import dev.kdriver.core.dom.NodeOrElement import dev.kdriver.core.exceptions.EvaluateException import dev.kdriver.core.exceptions.TimeoutWaitingForElementException import dev.kdriver.core.objectIdsOf import dev.kdriver.core.param import dev.kdriver.core.valueReply -import io.mockk.every -import io.mockk.mockk import kotlinx.coroutines.launch import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.advanceTimeBy @@ -27,9 +26,10 @@ import kotlin.test.assertNull import kotlin.test.assertTrue /** - * With [Config.lookupsInPage], `select`, `selectAll`, `querySelector` and `querySelectorAll` without a node ask the page - * (`Runtime.evaluate`) and describe the matches (`DOM.describeNode`) instead of reading the whole document; without it - * they read the document as before. + * `select`, `selectAll`, `querySelector` and `querySelectorAll` without a node ask the page (`Runtime.evaluate`) and + * describe the matches (`DOM.describeNode`) instead of reading the whole document. A found element gets its node ids, + * tree and parent from the document when it is updated or a lookup runs under it, the same as a lookup on the + * document gave them; an invalid selector throws the browser's error of `DOM.querySelector(All)`. */ class LookupsInPageTest { @@ -54,20 +54,14 @@ class LookupsInPageTest { """"localName":"button","nodeValue":"","attributes":["id","go"],"childNodeCount":1,"children":[""" + """{"nodeId":8,"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"","nodeValue":"Send"}]}]}}""" - private fun TestScope.tab(lookupsInPage: Boolean, answer: (ScriptedTransport.Sent) -> Reply): ScriptedTab { - val config = mockk(relaxed = true) - every { config.lookupsInPage } returns lookupsInPage - every { config.commandTimeout } returns Config.Defaults.COMMAND_TIMEOUT - val browser = mockk(relaxed = true) - every { browser.config } returns config - return ScriptedTab(this, ScriptedTransport(this, answer)).also { it.owner = browser } - } + private fun TestScope.tab(answer: (ScriptedTransport.Sent) -> Reply): ScriptedTab = + ScriptedTab(this, ScriptedTransport(this, answer)) private val ScriptedTab.sent get() = transport.methods @Test fun select_asksThePage_andDescribesTheMatch_withoutReadingTheDocument() = runTest(StandardTestDispatcher()) { - val tab = tab(lookupsInPage = true) { + val tab = tab { when (it.method) { "Runtime.evaluate" -> Reply.ok(found("obj-1")) "DOM.describeNode" -> Reply.ok(button) @@ -95,7 +89,7 @@ class LookupsInPageTest { @Test fun select_firstCallUsesTheObjectOfTheLookup_withoutResolvingTheNode() = runTest(StandardTestDispatcher()) { - val tab = tab(lookupsInPage = true) { + val tab = tab { when (it.method) { "Runtime.evaluate" -> Reply.ok(found("obj-1")) "DOM.describeNode" -> Reply.ok(button) @@ -115,7 +109,7 @@ class LookupsInPageTest { @Test fun select_resolvesTheNodeAgain_whenTheObjectOfTheLookupIsStale() = runTest(StandardTestDispatcher()) { var calls = 0 - val tab = tab(lookupsInPage = true) { + val tab = tab { when (it.method) { "Runtime.evaluate" -> Reply.ok(found("obj-1")) "DOM.describeNode" -> Reply.ok(button) @@ -136,7 +130,7 @@ class LookupsInPageTest { @Test fun select_triesAgain_whileThePageHasNoMatch_thenTimesOut() = runTest(StandardTestDispatcher()) { - val tab = tab(lookupsInPage = true) { + val tab = tab { when (it.method) { "Runtime.evaluate" -> Reply.ok(nothing) "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) @@ -154,7 +148,7 @@ class LookupsInPageTest { @Test fun select_triesAgain_whenTheMatchIsGoneBeforeItIsDescribed() = runTest(StandardTestDispatcher()) { var describes = 0 - val tab = tab(lookupsInPage = true) { + val tab = tab { when (it.method) { "Runtime.evaluate" -> Reply.ok(found("obj-${describes + 1}")) "DOM.describeNode" -> @@ -171,29 +165,74 @@ class LookupsInPageTest { tab.close() } + private fun syntaxError(selector: String, method: String) = + """{"result":{"type":"object","subtype":"error","className":"DOMException","objectId":"err"},""" + + """"exceptionDetails":{"exceptionId":1,"text":"Uncaught","lineNumber":0,"columnNumber":9,"exception":""" + + """{"type":"object","subtype":"error","className":"DOMException","description":"SyntaxError: Failed to """ + + """execute '$method' on 'Document': '$selector' is not a valid selector.\\n at :1:10"}}}""" + + @Test + fun anInvalidSelector_throwsTheBrowserErrorOfDomQuerySelector_andDisablesTheDomAgent() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(syntaxError("li[", "querySelector")) + "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) + else -> Reply.ok() + } + } + + val error = assertFailsWith { tab.select("li[", timeout = 0) } + + assertEquals("DOM.querySelector", error.method) + assertEquals(-32000, error.code) + assertEquals("DOM Error while querying", error.originalMessage) + assertNull(error.data) + assertEquals("Error while calling command DOM.querySelector: DOM Error while querying (code: -32000)", error.message) + assertTrue("DOM.disable" in tab.sent, "the DOM agent is disabled on the error, as before") + tab.close() + } + @Test - fun select_withAnInvalidSelector_throwsThePageError() = runTest(StandardTestDispatcher()) { - val tab = tab(lookupsInPage = true) { + fun anInvalidSelector_throwsTheBrowserErrorOfDomQuerySelectorAll_forTheListMethods() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(syntaxError("li[", "querySelectorAll")) + else -> Reply.ok() + } + } + + for (lookup in listOf Unit>({ tab.querySelectorAll("li[") }, { tab.selectAll("li[", timeout = 0) })) { + val error = assertFailsWith { lookup() } + assertEquals("DOM.querySelectorAll", error.method) + assertEquals(-32000, error.code) + assertEquals("DOM Error while querying", error.originalMessage) + } + tab.close() + } + + @Test + fun anotherExceptionOfThePage_isThrownAsAnEvaluateException() = runTest(StandardTestDispatcher()) { + val tab = tab { when (it.method) { "Runtime.evaluate" -> Reply.ok( """{"result":{"type":"object","subtype":"error","objectId":"err"},"exceptionDetails":""" + """{"exceptionId":1,"text":"Uncaught","lineNumber":0,"columnNumber":9,"exception":""" + - """{"type":"object","subtype":"error","description":"SyntaxError: 'li[' is not a valid selector."}}}""" + """{"type":"object","subtype":"error","description":"TypeError: replaced by the page"}}}""" ) - "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) else -> Reply.ok() } } - val error = assertFailsWith { tab.select("li[", timeout = 0) } + val error = assertFailsWith { tab.querySelector("#go") } - assertTrue(error.jsError.startsWith("SyntaxError"), error.jsError) + assertTrue(error.jsError.startsWith("TypeError"), error.jsError) + assertTrue("DOM.disable" !in tab.sent) tab.close() } @Test fun querySelector_passesTheSelectorAsOneJsonStringLiteral() = runTest(StandardTestDispatcher()) { - val tab = tab(lookupsInPage = true) { Reply.ok(nothing) } + val tab = tab { Reply.ok(nothing) } val selector = "a[title=\"x\\\") + alert(1) + (\"\n\u2028\"]" assertNull(tab.querySelector(selector)) @@ -208,7 +247,7 @@ class LookupsInPageTest { @Test fun querySelectorAll_withNoMatch_costsOneRoundTrip() = runTest(StandardTestDispatcher()) { - val tab = tab(lookupsInPage = true) { Reply.ok(nothing) } + val tab = tab { Reply.ok(nothing) } assertEquals(emptyList(), tab.querySelectorAll(".item")) @@ -223,7 +262,7 @@ class LookupsInPageTest { @Test fun querySelectorAll_describesEveryMatch_inDocumentOrder() = runTest(StandardTestDispatcher()) { val items = mapOf("li-0" to item(10, "Alpha"), "li-1" to item(20, "Beta"), "li-2" to item(30, "Gamma")) - val tab = tab(lookupsInPage = true) { + val tab = tab { when (it.method) { "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) "Runtime.getProperties" -> Reply.ok( @@ -259,7 +298,7 @@ class LookupsInPageTest { @Test fun querySelectorAll_findsNothing_whenAMatchIsGoneBeforeItIsDescribed() = runTest(StandardTestDispatcher()) { - val tab = tab(lookupsInPage = true) { + val tab = tab { when (it.method) { "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) "Runtime.getProperties" -> Reply.ok( @@ -283,7 +322,7 @@ class LookupsInPageTest { @Test fun selectAll_asksThePage_andTimesOutWhenNothingMatches() = runTest(StandardTestDispatcher()) { - val tab = tab(lookupsInPage = true) { Reply.ok(nothing) } + val tab = tab { Reply.ok(nothing) } assertFailsWith { tab.selectAll(".item", timeout = 1_200) } @@ -292,57 +331,8 @@ class LookupsInPageTest { } @Test - fun withTheSettingOff_selectReadsTheDocumentAsBefore() = runTest(StandardTestDispatcher()) { - val tab = tab(lookupsInPage = false) { - when (it.method) { - "DOM.getDocument" -> Reply.ok(document) - "DOM.querySelector" -> Reply.ok("""{"nodeId":7}""") - "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) - else -> Reply.ok() - } - } - - val element = tab.select("#go", timeout = 1_000) - - assertEquals(7, element.node.nodeId) - assertEquals(listOf("DOM.getDocument", "DOM.querySelector"), tab.sent.filter { it != "Target.getTargetInfo" }) - tab.close() - } - - @Test - fun withTheSettingOff_querySelectorAllReadsTheDocumentAsBefore() = runTest(StandardTestDispatcher()) { - val tab = tab(lookupsInPage = false) { - when (it.method) { - "DOM.getDocument" -> Reply.ok(document) - "DOM.querySelectorAll" -> Reply.ok("""{"nodeIds":[7]}""") - else -> Reply.ok() - } - } - - assertEquals(listOf(7), tab.querySelectorAll("#go").map { it.node.nodeId }) - assertEquals(listOf("DOM.getDocument", "DOM.querySelectorAll"), tab.sent) - tab.close() - } - - @Test - fun withoutABrowser_lookupsReadTheDocument() = runTest(StandardTestDispatcher()) { - val transport = ScriptedTransport(this) { - when (it.method) { - "DOM.getDocument" -> Reply.ok(document) - "DOM.querySelector" -> Reply.ok("""{"nodeId":7}""") - else -> Reply.ok() - } - } - val tab = ScriptedTab(this, transport) - - assertEquals(7, tab.querySelector("#go")!!.node.nodeId) - assertEquals(listOf("DOM.getDocument", "DOM.querySelector"), transport.methods) - tab.close() - } - - @Test - fun underANode_lookupsAreUnchanged_evenWithTheSettingOn() = runTest(StandardTestDispatcher()) { - val tab = tab(lookupsInPage = true) { + fun underANode_lookupsReadTheDocument_asBefore() = runTest(StandardTestDispatcher()) { + val tab = tab { when (it.method) { "DOM.querySelector" -> Reply.ok("""{"nodeId":8}""") else -> Reply.ok() @@ -350,7 +340,7 @@ class LookupsInPageTest { } val parent = dev.kdriver.core.scriptedNode(7, name = "DIV", children = listOf(dev.kdriver.core.scriptedNode(8))) - val child = tab.querySelector("input", dev.kdriver.core.dom.NodeOrElement.WrappedNode(parent)) + val child = tab.querySelector("input", NodeOrElement.WrappedNode(parent)) assertEquals(8, child!!.node.nodeId) assertEquals(listOf("DOM.querySelector"), tab.sent) @@ -363,7 +353,7 @@ class LookupsInPageTest { @Test fun querySelectorAll_findsNothing_whenTheArrayIsGoneBeforeItIsRead() = runTest(StandardTestDispatcher()) { - val tab = tab(lookupsInPage = true) { + val tab = tab { when (it.method) { "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) "Runtime.getProperties" -> Reply.error("Could not find object with given id") @@ -382,7 +372,7 @@ class LookupsInPageTest { "Cannot find context with specified id", "Execution context was destroyed.", )) { - val tab = tab(lookupsInPage = true) { + val tab = tab { when (it.method) { "Runtime.evaluate" -> Reply.error(error) else -> Reply.ok() @@ -397,7 +387,7 @@ class LookupsInPageTest { @Test fun querySelector_findsNothing_whenTheNodeIsGoneBeforeItIsDescribed() = runTest(StandardTestDispatcher()) { - val tab = tab(lookupsInPage = true) { + val tab = tab { when (it.method) { "Runtime.evaluate" -> Reply.ok(found("obj-1")) "DOM.describeNode" -> Reply.error("No node with given id found") @@ -411,20 +401,20 @@ class LookupsInPageTest { @Test fun aClosedTarget_isAnError_notANoMatch() = runTest(StandardTestDispatcher()) { - val tab = tab(lookupsInPage = true) { + val tab = tab { when (it.method) { "Runtime.evaluate" -> Reply.error("Inspected target navigated or closed") else -> Reply.ok() } } - assertFailsWith { tab.querySelector("#go") } + assertFailsWith { tab.querySelector("#go") } tab.close() } @Test fun aDescriptionThatFails_isThrown_stopsTheOthers_andTheArrayIsStillReleased() = runTest(StandardTestDispatcher()) { - val tab = tab(lookupsInPage = true) { + val tab = tab { when (it.method) { "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) "Runtime.getProperties" -> Reply.ok( @@ -441,7 +431,7 @@ class LookupsInPageTest { } } - assertFailsWith { tab.querySelectorAll(".item") } + assertFailsWith { tab.querySelectorAll(".item") } assertEquals("array", tab.transport.sent.single { it.method == "Runtime.releaseObject" }.param("objectId")) assertEquals(50, testScheduler.currentTime, "the release was awaited, the other description was not") tab.close() @@ -449,7 +439,7 @@ class LookupsInPageTest { @Test fun aLookupCancelledWhileTheArrayIsRead_stillReleasesIt() = runTest(StandardTestDispatcher()) { - val tab = tab(lookupsInPage = true) { + val tab = tab { when (it.method) { "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) "Runtime.getProperties" -> Reply.ok(arrayOfOne, latency = 1_000) @@ -469,7 +459,7 @@ class LookupsInPageTest { @Test fun anyOtherProtocolError_isThrown() = runTest(StandardTestDispatcher()) { - val describing = tab(lookupsInPage = true) { + val describing = tab { when (it.method) { "Runtime.evaluate" -> Reply.ok(found("obj-1")) "DOM.describeNode" -> Reply.error("Message is too large") @@ -478,11 +468,11 @@ class LookupsInPageTest { } assertEquals( "Message is too large", - assertFailsWith { describing.querySelector("#go") }.originalMessage + assertFailsWith { describing.querySelector("#go") }.originalMessage ) describing.close() - val listing = tab(lookupsInPage = true) { + val listing = tab { when (it.method) { "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) "Runtime.getProperties" -> Reply.error("Message is too large") @@ -491,7 +481,7 @@ class LookupsInPageTest { } assertEquals( "Message is too large", - assertFailsWith { listing.querySelectorAll(".item") }.originalMessage + assertFailsWith { listing.querySelectorAll(".item") }.originalMessage ) assertEquals( "array", listing.transport.sent.single { it.method == "Runtime.releaseObject" }.param("objectId"), @@ -499,19 +489,19 @@ class LookupsInPageTest { ) listing.close() - val evaluating = tab(lookupsInPage = true) { + val evaluating = tab { when (it.method) { "Runtime.evaluate" -> Reply.error("Session closed") else -> Reply.ok() } } - assertFailsWith { evaluating.querySelectorAll(".item") } + assertFailsWith { evaluating.querySelectorAll(".item") } evaluating.close() } @Test fun querySelectorAll_keepsItsMatches_whenTheReleaseOfTheArrayFails() = runTest(StandardTestDispatcher()) { - val tab = tab(lookupsInPage = true) { + val tab = tab { when (it.method) { "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) "Runtime.getProperties" -> Reply.ok(arrayOfOne) @@ -539,7 +529,7 @@ class LookupsInPageTest { @Test fun selectAllWithAFrame_findsInsideItAndInThePage_fromOneDocumentRead() = runTest(StandardTestDispatcher()) { - val tab = tab(lookupsInPage = true) { + val tab = tab { when (it.method) { "DOM.getDocument" -> Reply.ok(documentWithAFrame) "DOM.querySelectorAll" -> when (it.param("nodeId")) { @@ -559,8 +549,8 @@ class LookupsInPageTest { } @Test - fun selectAllWithFrames_readsTheDocumentAsOff() = runTest(StandardTestDispatcher()) { - val tab = tab(lookupsInPage = true) { + fun selectAllWithFrames_readsTheDocument() = runTest(StandardTestDispatcher()) { + val tab = tab { when (it.method) { "DOM.getDocument" -> Reply.ok(document) "DOM.querySelectorAll" -> @@ -580,28 +570,145 @@ class LookupsInPageTest { } @Test - fun aLookupUnderAnElementFoundInThePage_updatesItFromTheDocumentFirst() = runTest(StandardTestDispatcher()) { - val tab = tab(lookupsInPage = true) { + fun aLookupUnderAnElementFoundInThePage_bindsItToTheDocumentFirst() = runTest(StandardTestDispatcher()) { + val tab = tab { when (it.method) { "Runtime.evaluate" -> Reply.ok(found("obj-1")) "DOM.describeNode" -> Reply.ok(button) "DOM.getDocument" -> Reply.ok(document) "DOM.querySelector" -> Reply.ok("""{"nodeId":8}""") - "DOM.resolveNode" -> Reply.ok("""{"object":{"type":"object","subtype":"node","objectId":"obj-2"}}""") else -> Reply.ok() } } val button = tab.querySelector("#go")!! - val text = tab.querySelector("*", dev.kdriver.core.dom.NodeOrElement.WrappedElement(button)) + val text = tab.querySelector("*", NodeOrElement.WrappedElement(button)) - assertEquals(7, button.node.nodeId, "updated from the document") + assertEquals(7, button.node.nodeId, "bound to the document") + assertEquals(1, button.tree?.nodeId) assertEquals("7", tab.transport.sent.single { it.method == "DOM.querySelector" }.param("nodeId")) assertEquals(8, text!!.node.nodeId) - val resolvesBefore = tab.sent.count { it == "DOM.resolveNode" } - tab.querySelector("*", dev.kdriver.core.dom.NodeOrElement.WrappedElement(button)) - assertEquals(resolvesBefore, tab.sent.count { it == "DOM.resolveNode" }, "a bound element is not updated again") + assertEquals("obj-1", button.objectId, "the object of the lookup is kept, not resolved again") + tab.querySelector("*", NodeOrElement.WrappedElement(button)) + assertEquals(1, tab.sent.count { it == "DOM.getDocument" }, "a bound element is not bound again") assertEquals(2, tab.sent.count { it == "DOM.querySelector" }) + assertTrue("DOM.resolveNode" !in tab.sent) + tab.close() + } + + /** `
  • Beta
`, as the document read gives it. */ + private val list = + """{"root":{"nodeId":1,"backendNodeId":1,"nodeType":9,"nodeName":"#document","localName":"","nodeValue":"",""" + + """"childNodeCount":1,"children":[{"nodeId":5,"parentId":1,"backendNodeId":50,"nodeType":1,""" + + """"nodeName":"UL","localName":"ul","nodeValue":"","attributes":["id","list"],"childNodeCount":1,""" + + """"children":[{"nodeId":7,"parentId":5,"backendNodeId":70,"nodeType":1,"nodeName":"LI",""" + + """"localName":"li","nodeValue":"","attributes":["class","item"],"childNodeCount":1,"children":[""" + + """{"nodeId":8,"parentId":7,"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"",""" + + """"nodeValue":"Beta"}]}]}]}}""" + + /** The same `li`, as `DOM.describeNode` gives it: no node ids, no parent id. */ + private val describedItem = + """{"node":{"nodeId":0,"backendNodeId":70,"nodeType":1,"nodeName":"LI","localName":"li","nodeValue":"",""" + + """"attributes":["class","item"],"childNodeCount":1,"children":[{"nodeId":0,"parentId":0,""" + + """"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"","nodeValue":"Beta"}]}}""" + + private fun TestScope.listTab() = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-1")) + "DOM.describeNode" -> Reply.ok(describedItem) + "DOM.getDocument" -> Reply.ok(list) + "DOM.querySelector" -> Reply.ok("""{"nodeId":7}""") + "DOM.resolveNode" -> Reply.ok("""{"object":{"type":"object","subtype":"node","objectId":"obj-2"}}""") + "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) + else -> Reply.ok() + } + } + + // What a lookup on the whole document gave: DOM.querySelector on the document read, the match taken from it. + private suspend fun ScriptedTab.onTheDocument(selector: String): Element = + querySelector(selector, NodeOrElement.WrappedNode(currentDocument().first))!! + + @Test + fun anElementFoundInThePage_hasNoNodeIdTreeNorParent_untilUpdated() = runTest(StandardTestDispatcher()) { + val tab = listTab() + + val item = tab.select("li.item", timeout = 1_000) + + assertEquals(0, item.node.nodeId) + assertNull(item.parentId) + assertNull(item.tree) + assertEquals( + "could not get parent since the element has no tree set", + assertFailsWith { item.parent }.message, + ) + assertEquals(listOf(0), item.children.map { it.node.nodeId }) + assertTrue("DOM.getDocument" !in tab.sent) + tab.close() + } + + @Test + fun update_givesTheNodeIdsTreeAndParent_aLookupOnTheDocumentGave() = runTest(StandardTestDispatcher()) { + val tab = listTab() + val item = tab.select("li.item", timeout = 1_000) + + item.update() + val before = tab.onTheDocument("li.item") + + assertEquals(before.node, item.node) + assertEquals(7, item.node.nodeId) + assertEquals(5, item.parentId) + assertEquals(before.tree, item.tree) + assertEquals(before.parent!!.node, item.parent!!.node) + assertEquals("ul", item.parent!!.tag) + assertEquals(before.children.map { it.node }, item.children.map { it.node }) + assertEquals(1, tab.sent.count { it == "DOM.getDocument" }, "one document read for both") + tab.close() + } + + @Test + fun aBareNodeFoundInThePage_isReplacedByTheNodeOfTheDocument_forALookupUnderIt() = runTest(StandardTestDispatcher()) { + val tab = listTab() + val item = tab.querySelector("li.item")!! + + tab.querySelector("*", NodeOrElement.WrappedNode(item.node)) + + assertEquals("7", tab.transport.sent.single { it.method == "DOM.querySelector" }.param("nodeId")) + tab.close() + } + + @Test + fun aNodeFoundInThePage_butGoneFromTheDocument_isQueriedAsItIs() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-1")) + "DOM.describeNode" -> Reply.ok(item(30, "Gone")) + "DOM.getDocument" -> Reply.ok(list) + "DOM.querySelector" -> Reply.error("Could not find node with given id") + "DOM.resolveNode" -> Reply.ok("""{"object":{"type":"object","subtype":"node","objectId":"obj-2"}}""") + else -> Reply.ok() + } + } + val gone = tab.querySelector("li")!! + + assertNull(tab.querySelector("*", NodeOrElement.WrappedNode(gone.node))) + assertNull(tab.querySelector("*", NodeOrElement.WrappedElement(gone))) + + assertEquals(0, gone.node.nodeId, "no node of the document to take") + assertEquals(1, gone.tree?.nodeId, "the element is bound to the document all the same, as update() does") + assertEquals(listOf("0", "0"), tab.transport.sent.filter { it.method == "DOM.querySelector" }.take(2).map { it.param("nodeId") }) + tab.close() + } + + @Test + fun anotherElementImplementation_isUpdated_beforeALookupUnderIt() = runTest(StandardTestDispatcher()) { + val tab = listTab() + val found = tab.querySelector("li.item")!! + val wrapper: Element = object : Element by found {} + + tab.querySelector("*", NodeOrElement.WrappedElement(wrapper)) + + assertEquals(7, wrapper.node.nodeId) + assertTrue("DOM.resolveNode" in tab.sent, "Element.update resolves the object, as it always did") tab.close() } diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/SettledLookupTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/SettledLookupTest.kt index d98bc3d2c..8bbaaa2c0 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/SettledLookupTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/SettledLookupTest.kt @@ -28,6 +28,11 @@ class SettledLookupTest { """"localName":"button","nodeValue":"","attributes":["id","go"],"childNodeCount":1,"children":[""" + """{"nodeId":8,"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"","nodeValue":"Send"}]}]}}""" + private val button = + """{"node":{"nodeId":0,"backendNodeId":70,"nodeType":1,"nodeName":"BUTTON","localName":"button",""" + + """"nodeValue":"","attributes":["id","go"],"childNodeCount":1,"children":[{"nodeId":0,""" + + """"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"","nodeValue":"Send"}]}}""" + /** A page with one ``; [found] false makes every lookup come back empty. */ private fun browser(found: Boolean = true, targetError: String? = null): (ScriptedTransport.Sent) -> Reply = { when (it.method) { @@ -35,6 +40,10 @@ class SettledLookupTest { if (targetError != null) Reply.error(targetError, latency = 100) else Reply.ok(ScriptedTab.TARGET_INFO, latency = 100) "DOM.getDocument" -> Reply.ok(document, latency = 100) + "Runtime.evaluate" -> + if (found) Reply.ok("""{"result":{"type":"object","subtype":"node","objectId":"obj-1"}}""", latency = 100) + else Reply.ok("""{"result":{"type":"object","subtype":"null","value":null}}""", latency = 100) + "DOM.describeNode" -> Reply.ok(button, latency = 100) "DOM.querySelector" -> Reply.ok(if (found) """{"nodeId":7}""" else """{"nodeId":0}""", latency = 100) "DOM.performSearch" -> Reply.ok("""{"searchId":"s1","resultCount":${if (found) 1 else 0}}""", latency = 100) "DOM.getSearchResults" -> Reply.ok("""{"nodeIds":[7]}""", latency = 100) @@ -53,9 +62,9 @@ class SettledLookupTest { assertEquals("Send", button.text) assertEquals("https://example.test/", tab.targetInfo!!.url, "the target info is still refreshed") val sentAtStart = transport.methodsSentAt(0) - assertEquals(setOf("DOM.getDocument", "Target.getTargetInfo"), sentAtStart) - assertEquals(listOf("DOM.querySelector"), transport.sent.filter { it.atMillis > 0 }.map { it.method }) - assertEquals(200, testScheduler.currentTime, "two round trips (refresh ∥ document, then query), not three") + assertEquals(setOf("Runtime.evaluate", "Target.getTargetInfo"), sentAtStart) + assertEquals(listOf("DOM.describeNode"), transport.sent.filter { it.atMillis > 0 }.map { it.method }) + assertEquals(200, testScheduler.currentTime, "two round trips (refresh ∥ evaluation, then description), not three") tab.close() } @@ -67,7 +76,7 @@ class SettledLookupTest { val error = assertFailsWith { tab.select("#missing", timeout = 50) } assertTrue(error.message!!.contains("#missing")) - val attempts = transport.methods.count { it == "DOM.querySelector" } + val attempts = transport.methods.count { it == "Runtime.evaluate" } assertTrue(attempts >= 1, "polled ($attempts)") assertEquals(attempts, transport.methods.count { it == "Target.getTargetInfo" }, "one refresh per attempt") tab.close() diff --git a/docs/home/quickstart.md b/docs/home/quickstart.md index c7476674c..9f146362c 100644 --- a/docs/home/quickstart.md +++ b/docs/home/quickstart.md @@ -189,41 +189,43 @@ The browser advertises its own, internal, address in `webSocketDebuggerUrl`; whe set, kdriver keeps only the path of that URL and connects to it on `browserUrl`. Without `browserUrl`, `host` and `port` keep working as before. -## Lookups on a remote browser - -By default, `select`, `selectAll`, `querySelector` and `querySelectorAll` read the whole document -(`DOM.getDocument`) each time the page changed since the last read, then query it. That read is the -size of the whole DOM, often a megabyte, and it happens after every navigation and on any page that -keeps changing. When the browser is far away, it is usually the largest transfer of a script. - -With `lookupsInPage`, these lookups ask the page instead: the page runs the selector and only the -matching elements are sent back. +## How lookups work + +`select`, `selectAll`, `querySelector` and `querySelectorAll` (without a node) let the page run the +selector: kdriver evaluates `document.querySelector(…)` / `document.querySelectorAll(…)` in the page, +then asks the browser to describe only the matching elements, each with its subtree. The whole +document is never transferred, which matters most when the browser is far away (`browserUrl`) and +the page is large or keeps changing. + +| What | How | +| --- | --- | +| Commands for `select` / `querySelector` | `Runtime.evaluate`, then `DOM.describeNode` of the match (one round trip when nothing matches) | +| Commands for `selectAll` / `querySelectorAll` | one `Runtime.evaluate` when nothing matches; otherwise also `Runtime.getProperties`, then every `DOM.describeNode` sent together, with the release of the list | +| Data received | the matches and their subtrees (many or nested matches can add up to more than the document) | +| First call on a found element (`click`, `apply`, …) | uses the object the page returned, no `DOM.resolveNode` | +| Text, attributes, children, `backendNodeId` | read from the match and its subtree, as before | +| `element.node.nodeId`, `element.parentId`, `element.tree`, `element.parent` | 0, `null`, `null`, and `parent` throws, until `element.update()` reads the document; a lookup under the element does it by itself | +| Shadow roots, iframes | not searched (`selectAll(includeFrames = true)` reads the document to search inside each iframe, as before) | +| Waiting | `select` / `selectAll` retry every 500 ms until the timeout, as before | +| A navigation during the lookup | an object or context dropped by the navigation counts as no match: `select` tries again | +| Invalid selector | the same `CDPException` as before (`DOM.querySelector` or `DOM.querySelectorAll`, code -32000, "DOM Error while querying") | ```kotlin -val browser = createBrowser(this) { - browserUrl = "https://browsers.example.com/team/one" - lookupsInPage = true -} +val item = tab.select("li.item") +item.text // read from the match +item.click() // no extra command to resolve the element +item.tree // null: no document was read +item.update() // reads the document (one DOM.getDocument) +item.parent?.tag // "ul" ``` -The setting is off by default. What changes when it is on: - -| | Off (default) | On | -| --- | --- | --- | -| Commands for `select` / `querySelector` | `DOM.getDocument` (whole document, unless the page has not changed since the last read), then `DOM.querySelector` | `Runtime.evaluate` (`document.querySelector`), then `DOM.describeNode` of the match | -| Commands for `selectAll` / `querySelectorAll` | `DOM.getDocument`, then `DOM.querySelectorAll` | one `Runtime.evaluate` when nothing matches; otherwise also `Runtime.getProperties`, then one `DOM.describeNode` per match, sent together | -| Data received per lookup | the whole document | the matches and their subtrees (many or nested matches can add up to more than the document) | -| First call on a found element (`click`, `apply`, …) | resolves the node first (`DOM.resolveNode`) | uses the object the page returned, no extra command | -| `element.node.nodeId` | the node id | 0: no document was requested | -| `element.tree`, `element.parent` | the document, the parent | `null`, and `parent` throws until `element.update()`, which reads the document | -| Text, attributes, children of an element | read from the node and its subtree | the same | -| Shadow roots | not searched | not searched | -| Iframes | not searched; `selectAll(includeFrames = true)` searches inside each one | the same: with `includeFrames = true`, `selectAll` reads the document as off, for the page's own matches too | -| Waiting | `select` / `selectAll` retry every 500 ms until the timeout | the same; with no document requested, the browser sends fewer `DOM.*` events, so a busy page may count as idle sooner | -| A navigation during the lookup | a node gone from the document read counts as no match | an object or context dropped by the navigation counts as no match (all of them, even if only some matches are gone): `select` tries again | -| Invalid selector | `CDPException` | `EvaluateException` (the page's `SyntaxError`) | -| Remote objects held | one per element used, from its first call | one per match, until the page navigates; the array of `selectAll` is released (one more command, sent with the descriptions) | -| A page that replaces `document.querySelector` | not affected | the page's own function runs | +What still differs from reading the whole document: + +- the page's own `document.querySelector` runs, so a page that replaces it changes the result; +- each found element holds the remote object of its match until the page navigates (an element read + from the document held one only after its first call); +- until something reads the document (`find`, `update`, a lookup under an element…), the browser + sends no `DOM.*` mutation events for the page, so a busy page may count as idle sooner. Lookups under an element (`element.querySelector`, `element.querySelectorAll`), `find`, `findAll` -and `xpath` are the same in both modes: they still read the document. +and `xpath` read the document, as before. From 1aa78f63eec03c7d6e9c836a8cf8fa06088473ab Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Fri, 20 Nov 2026 15:11:27 +0100 Subject: [PATCH 07/16] test: wait for the frame before comparing two document reads, enable the DOM agent before disabling it A lookup run by the page does not enable the DOM agent, so a DOM.disable sent by hand right after one fails as on any tab where it was never enabled. Also keeps the lines added by this branch within the 120 columns of detekt. --- .../kotlin/dev/kdriver/core/tab/DefaultTab.kt | 4 +- .../kotlin/dev/kdriver/core/tab/Tab.kt | 9 +-- .../dev/kdriver/core/tab/DocumentReuseTest.kt | 2 +- .../kdriver/core/tab/LookupBehaviourTest.kt | 1 + .../core/tab/LookupsInPageBehaviourTest.kt | 18 ++--- .../dev/kdriver/core/tab/LookupsInPageTest.kt | 67 ++++++++++++------- .../dev/kdriver/core/tab/SettledLookupTest.kt | 4 +- 7 files changed, 65 insertions(+), 40 deletions(-) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt index 395323d70..f36bcf480 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt @@ -987,8 +987,8 @@ open class DefaultTab( /** * Error texts of the browser for an object, a node or an execution context it no longer knows (a navigation dropped * it): "Could not find object with given id", "No node with given id found", "Cannot find context with specified id", - * "Execution context was destroyed". Not "Inspected target navigated or closed", also sent for a closed tab, which is an - * error and not a lookup to try again. + * "Execution context was destroyed". Not "Inspected target navigated or closed", also sent for a closed tab, which is + * an error and not a lookup to try again. */ private val GONE = listOf( "could not find object", diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt b/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt index 88622b2fb..b2cf7e706 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt @@ -424,10 +424,11 @@ interface Tab : Connection { * - until something reads the document (a lookup under an element, [find], [Element.update]…), the browser sends * no `DOM.*` mutation events for the page, so on a busy page the connection may count as idle sooner. * - * Unchanged: shadow roots and iframes are not searched; an invalid selector throws the [dev.kdriver.cdp.CDPException] - * the browser gives `DOM.querySelector` (code -32000, "DOM Error while querying"), `DOM.querySelectorAll` for the - * other methods; a node or execution context dropped by a navigation during the lookup counts as no match, so - * [select] tries again (for [querySelectorAll], none of the old page's matches is returned). + * Unchanged: shadow roots and iframes are not searched; an invalid selector throws the + * [dev.kdriver.cdp.CDPException] the browser gives `DOM.querySelector` (code -32000, "DOM Error while querying"), + * `DOM.querySelectorAll` for the other methods; a node or execution context dropped by a navigation during the + * lookup counts as no match, so [select] tries again (for [querySelectorAll], none of the old page's matches is + * returned). * * Lookups under a node or an element, [find], [findAll] and [xpath] read the document, as before. * diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/DocumentReuseTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/DocumentReuseTest.kt index f81db5f9d..b2213681a 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/DocumentReuseTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/DocumentReuseTest.kt @@ -71,7 +71,7 @@ class DocumentReuseTest { private val ScriptedTransport.documentReads get() = methods.count { it == "DOM.getDocument" } - // A selector lookup that reads the document: selectAll with frames (no frame on this page), then the page's matches. + // A selector lookup that reads the document: selectAll with frames (none on this page), then the page's matches. private suspend fun ScriptedTab.lookUp() = selectAll("#go", timeout = 1_000, includeFrames = true).first() @Test diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupBehaviourTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupBehaviourTest.kt index 5cd9edf5f..58cdb1b75 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupBehaviourTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupBehaviourTest.kt @@ -203,6 +203,7 @@ class LookupBehaviourTest { fun lookupsKeepWorking_afterTheDomAgentWasDisabledByHand() = withPage { assertEquals("Alpha", select("li[data-rank='1']", timeout = 5_000).text) + dom.enable() // a lookup run by the page does not enable the DOM agent; a document read did dom.disable() rawEvaluate("document.querySelector(\"li[data-rank='1']\").textContent = 'Omega'") diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt index 6a7be813f..35e399246 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt @@ -95,12 +95,15 @@ class LookupsInPageBehaviourTest { fun frames_areNotSearched_butSelectAllWithFramesSearchesThem() = onPage { assertNull(oneOnTheDocument("p.inner")) assertNull(querySelector("p.inner")) - assertEquals(listOf("Inside the frame"), selectAll("p.inner", timeout = 5_000, includeFrames = true).map { it.text }) + val inFrames = selectAll("p.inner", timeout = 5_000, includeFrames = true) + assertEquals(listOf("Inside the frame"), inFrames.map { it.text }) } @Test fun aFoundElementCanBeClickedAndRead() = onPage { - rawEvaluate("document.getElementById('panel').onclick = () => document.getElementById('panel').dataset.state = 'open'") + rawEvaluate( + "document.getElementById('panel').onclick = () => document.getElementById('panel').dataset.state = 'open'" + ) select("#panel", timeout = 5_000).click() @@ -134,6 +137,7 @@ class LookupsInPageBehaviourTest { @Test fun update_givesTheNodeIdsTreeAndParent_theDocumentLookupGives() = onPage { + selectAll("p.inner", timeout = 5_000, includeFrames = true) // the frame loaded: both reads see the same page // The same lookup on the whole document, read first: a later read gives every node a new id, so ids are // compared below on the document the update read, and everything else on this earlier read. val before = oneOnTheDocument("li[data-rank='3']")!! @@ -170,12 +174,10 @@ class LookupsInPageBehaviourTest { val one = assertFailsWith { dom.querySelector(document.nodeId, selector) } val all = assertFailsWith { dom.querySelectorAll(document.nodeId, selector) } - for (lookup in listOf Unit>({ select(selector, timeout = 0) }, { querySelector(selector) })) { - assertSameError(one, assertFailsWith { lookup() }) - } - for (lookup in listOf Unit>({ selectAll(selector, timeout = 0) }, { querySelectorAll(selector) })) { - assertSameError(all, assertFailsWith { lookup() }) - } + val ones = listOf Unit>({ select(selector, timeout = 0) }, { querySelector(selector) }) + for (lookup in ones) assertSameError(one, assertFailsWith { lookup() }) + val alls = listOf Unit>({ selectAll(selector, timeout = 0) }, { querySelectorAll(selector) }) + for (lookup in alls) assertSameError(all, assertFailsWith { lookup() }) } } diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt index 2e514ee43..b57b2bf01 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt @@ -43,6 +43,11 @@ class LookupsInPageTest { """"nodeValue":"","childNodeCount":1,"children":[{"nodeId":0,"backendNodeId":${backendNodeId + 1},""" + """"nodeType":3,"nodeName":"#text","localName":"","nodeValue":"$text"}]}}""" + // An own property of the array of `querySelectorAll`: the match at [index], as Runtime.getProperties lists it. + private fun match(index: Int, objectId: String) = + """{"name":"$index","configurable":true,"enumerable":true,""" + + """"value":{"type":"object","subtype":"node","objectId":"$objectId"}}""" + private val nothing = """{"result":{"type":"object","subtype":"null","value":null}}""" private fun found(objectId: String, subtype: String = "node") = @@ -114,7 +119,8 @@ class LookupsInPageTest { "Runtime.evaluate" -> Reply.ok(found("obj-1")) "DOM.describeNode" -> Reply.ok(button) "Runtime.callFunctionOn" -> - if (calls++ == 0) Reply.error("Could not find object with given id") else Reply.ok(valueReply("null")) + if (calls++ == 0) Reply.error("Could not find object with given id") + else Reply.ok(valueReply("null")) "DOM.resolveNode" -> Reply.ok("""{"object":{"type":"object","objectId":"obj-2"}}""") "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) else -> Reply.ok() @@ -172,7 +178,7 @@ class LookupsInPageTest { """execute '$method' on 'Document': '$selector' is not a valid selector.\\n at :1:10"}}}""" @Test - fun anInvalidSelector_throwsTheBrowserErrorOfDomQuerySelector_andDisablesTheDomAgent() = runTest(StandardTestDispatcher()) { + fun anInvalidSelector_throwsTheErrorOfDomQuerySelector_andDisablesDom() = runTest(StandardTestDispatcher()) { val tab = tab { when (it.method) { "Runtime.evaluate" -> Reply.ok(syntaxError("li[", "querySelector")) @@ -187,13 +193,16 @@ class LookupsInPageTest { assertEquals(-32000, error.code) assertEquals("DOM Error while querying", error.originalMessage) assertNull(error.data) - assertEquals("Error while calling command DOM.querySelector: DOM Error while querying (code: -32000)", error.message) + assertEquals( + "Error while calling command DOM.querySelector: DOM Error while querying (code: -32000)", + error.message, + ) assertTrue("DOM.disable" in tab.sent, "the DOM agent is disabled on the error, as before") tab.close() } @Test - fun anInvalidSelector_throwsTheBrowserErrorOfDomQuerySelectorAll_forTheListMethods() = runTest(StandardTestDispatcher()) { + fun anInvalidSelector_throwsTheErrorOfDomQuerySelectorAll_forTheListMethods() = runTest(StandardTestDispatcher()) { val tab = tab { when (it.method) { "Runtime.evaluate" -> Reply.ok(syntaxError("li[", "querySelectorAll")) @@ -201,7 +210,8 @@ class LookupsInPageTest { } } - for (lookup in listOf Unit>({ tab.querySelectorAll("li[") }, { tab.selectAll("li[", timeout = 0) })) { + val lookups = listOf Unit>({ tab.querySelectorAll("li[") }, { tab.selectAll("li[", timeout = 0) }) + for (lookup in lookups) { val error = assertFailsWith { lookup() } assertEquals("DOM.querySelectorAll", error.method) assertEquals(-32000, error.code) @@ -253,7 +263,8 @@ class LookupsInPageTest { assertEquals(listOf("Runtime.evaluate"), tab.sent) assertEquals( - "(() => { const all = Array.from(document.querySelectorAll(\".item\")); return all.length ? all : null; })()", + "(() => { const all = Array.from(document.querySelectorAll(\".item\"));" + + " return all.length ? all : null; })()", tab.transport.sent.single().param("expression"), ) tab.close() @@ -267,13 +278,16 @@ class LookupsInPageTest { "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) "Runtime.getProperties" -> Reply.ok( """{"result":[""" + - """{"name":"2","configurable":true,"enumerable":true,"value":{"type":"object","subtype":"node","objectId":"li-2"}},""" + - """{"name":"0","configurable":true,"enumerable":true,"value":{"type":"object","subtype":"node","objectId":"li-0"}},""" + - """{"name":"1","configurable":true,"enumerable":true,"value":{"type":"object","subtype":"node","objectId":"li-1"}},""" + - """{"name":"3","configurable":true,"enumerable":true,"get":{"type":"function","objectId":"getter"}},""" + + """${match(2, "li-2")},""" + + """${match(0, "li-0")},""" + + """${match(1, "li-1")},""" + + """{"name":"3","configurable":true,"enumerable":true,""" + + """"get":{"type":"function","objectId":"getter"}},""" + """{"name":"4","configurable":true,"enumerable":true,"value":{"type":"number","value":4}},""" + - """{"name":"length","configurable":false,"enumerable":false,"value":{"type":"number","value":3}},""" + - """{"name":"__proto__","configurable":true,"enumerable":false,"value":{"type":"object","objectId":"proto"}}""" + + """{"name":"length","configurable":false,"enumerable":false,""" + + """"value":{"type":"number","value":3}},""" + + """{"name":"__proto__","configurable":true,"enumerable":false,""" + + """"value":{"type":"object","objectId":"proto"}}""" + """]}""" ) "DOM.describeNode" -> Reply.ok(items.getValue(it.param("objectId")!!), latency = 100) @@ -303,8 +317,8 @@ class LookupsInPageTest { "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) "Runtime.getProperties" -> Reply.ok( """{"result":[""" + - """{"name":"0","configurable":true,"enumerable":true,"value":{"type":"object","subtype":"node","objectId":"li-0"}},""" + - """{"name":"1","configurable":true,"enumerable":true,"value":{"type":"object","subtype":"node","objectId":"li-1"}}""" + + """${match(0, "li-0")},""" + + """${match(1, "li-1")}""" + """]}""" ) "DOM.describeNode" -> @@ -348,7 +362,7 @@ class LookupsInPageTest { } private val arrayOfOne = """{"result":[""" + - """{"name":"0","configurable":true,"enumerable":true,"value":{"type":"object","subtype":"node","objectId":"li-0"}}""" + + """${match(0, "li-0")}""" + """]}""" @Test @@ -419,8 +433,8 @@ class LookupsInPageTest { "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) "Runtime.getProperties" -> Reply.ok( """{"result":[""" + - """{"name":"0","configurable":true,"enumerable":true,"value":{"type":"object","subtype":"node","objectId":"li-0"}},""" + - """{"name":"1","configurable":true,"enumerable":true,"value":{"type":"object","subtype":"node","objectId":"li-1"}}""" + + """${match(0, "li-0")},""" + + """${match(1, "li-1")}""" + """]}""" ) "DOM.describeNode" -> @@ -519,7 +533,8 @@ class LookupsInPageTest { """{"root":{"nodeId":1,"backendNodeId":1,"nodeType":9,"nodeName":"#document","localName":"","nodeValue":"",""" + """"childNodeCount":2,"children":[{"nodeId":7,"backendNodeId":70,"nodeType":1,"nodeName":"P",""" + """"localName":"p","nodeValue":"","childNodeCount":1,"children":[""" + - """{"nodeId":8,"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"","nodeValue":"Outer"}]},""" + + """{"nodeId":8,"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"",""" + + """"nodeValue":"Outer"}]},""" + """{"nodeId":9,"backendNodeId":90,"nodeType":1,"nodeName":"IFRAME","localName":"iframe","nodeValue":"",""" + """"childNodeCount":0,"contentDocument":{"nodeId":10,"backendNodeId":100,"nodeType":9,""" + """"nodeName":"#document","localName":"","nodeValue":"","childNodeCount":1,"children":[""" + @@ -533,7 +548,9 @@ class LookupsInPageTest { when (it.method) { "DOM.getDocument" -> Reply.ok(documentWithAFrame) "DOM.querySelectorAll" -> when (it.param("nodeId")) { - "1" -> if (it.param("selector") == "iframe") Reply.ok("""{"nodeIds":[9]}""") else Reply.ok("""{"nodeIds":[7]}""") + "1" -> + if (it.param("selector") == "iframe") Reply.ok("""{"nodeIds":[9]}""") + else Reply.ok("""{"nodeIds":[7]}""") "10" -> Reply.ok("""{"nodeIds":[11]}""") else -> Reply.error("Could not find node with given id") } @@ -542,7 +559,9 @@ class LookupsInPageTest { } } - assertEquals(listOf("Inner", "Outer"), tab.selectAll("p", timeout = 1_000, includeFrames = true).map { it.text }) + val found = tab.selectAll("p", timeout = 1_000, includeFrames = true) + + assertEquals(listOf("Inner", "Outer"), found.map { it.text }) assertEquals(1, tab.sent.count { it == "DOM.getDocument" }, "one read for the frame and the page") assertTrue("Runtime.evaluate" !in tab.sent) tab.close() @@ -554,7 +573,8 @@ class LookupsInPageTest { when (it.method) { "DOM.getDocument" -> Reply.ok(document) "DOM.querySelectorAll" -> - if (it.param("selector") == "iframe") Reply.ok("""{"nodeIds":[]}""") else Reply.ok("""{"nodeIds":[7]}""") + if (it.param("selector") == "iframe") Reply.ok("""{"nodeIds":[]}""") + else Reply.ok("""{"nodeIds":[7]}""") else -> Reply.ok() } } @@ -666,7 +686,7 @@ class LookupsInPageTest { } @Test - fun aBareNodeFoundInThePage_isReplacedByTheNodeOfTheDocument_forALookupUnderIt() = runTest(StandardTestDispatcher()) { + fun aBareNodeFoundInThePage_isReplacedByTheDocumentNode_forALookupUnderIt() = runTest(StandardTestDispatcher()) { val tab = listTab() val item = tab.querySelector("li.item")!! @@ -695,7 +715,8 @@ class LookupsInPageTest { assertEquals(0, gone.node.nodeId, "no node of the document to take") assertEquals(1, gone.tree?.nodeId, "the element is bound to the document all the same, as update() does") - assertEquals(listOf("0", "0"), tab.transport.sent.filter { it.method == "DOM.querySelector" }.take(2).map { it.param("nodeId") }) + val queried = tab.transport.sent.filter { it.method == "DOM.querySelector" }.map { it.param("nodeId") } + assertEquals(listOf("0", "0"), queried.take(2)) tab.close() } diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/SettledLookupTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/SettledLookupTest.kt index 8bbaaa2c0..248422e0f 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/SettledLookupTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/SettledLookupTest.kt @@ -41,7 +41,7 @@ class SettledLookupTest { else Reply.ok(ScriptedTab.TARGET_INFO, latency = 100) "DOM.getDocument" -> Reply.ok(document, latency = 100) "Runtime.evaluate" -> - if (found) Reply.ok("""{"result":{"type":"object","subtype":"node","objectId":"obj-1"}}""", latency = 100) + if (found) Reply.ok("""{"result":{"type":"object","objectId":"obj-1"}}""", latency = 100) else Reply.ok("""{"result":{"type":"object","subtype":"null","value":null}}""", latency = 100) "DOM.describeNode" -> Reply.ok(button, latency = 100) "DOM.querySelector" -> Reply.ok(if (found) """{"nodeId":7}""" else """{"nodeId":0}""", latency = 100) @@ -64,7 +64,7 @@ class SettledLookupTest { val sentAtStart = transport.methodsSentAt(0) assertEquals(setOf("Runtime.evaluate", "Target.getTargetInfo"), sentAtStart) assertEquals(listOf("DOM.describeNode"), transport.sent.filter { it.atMillis > 0 }.map { it.method }) - assertEquals(200, testScheduler.currentTime, "two round trips (refresh ∥ evaluation, then description), not three") + assertEquals(200, testScheduler.currentTime, "two round trips (refresh ∥ evaluation, then describe), not three") tab.close() } From c5e581372387a60a89bb4f02383382034cf36238 Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Fri, 20 Nov 2026 15:11:40 +0100 Subject: [PATCH 08/16] docs: lookups run by the page leave the DOM agent disabled --- core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt | 3 ++- docs/home/quickstart.md | 6 +++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt b/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt index b2cf7e706..cd2128377 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt @@ -422,7 +422,8 @@ interface Tab : Connection { * - each element holds the remote object of its match until the page navigates (an element read from the document * holds one only after its first call); * - until something reads the document (a lookup under an element, [find], [Element.update]…), the browser sends - * no `DOM.*` mutation events for the page, so on a busy page the connection may count as idle sooner. + * no `DOM.*` mutation events for the page, so on a busy page the connection may count as idle sooner; the DOM + * agent is not enabled either, so a `DOM.disable` sent by hand then fails, as on a tab that never read it. * * Unchanged: shadow roots and iframes are not searched; an invalid selector throws the * [dev.kdriver.cdp.CDPException] the browser gives `DOM.querySelector` (code -32000, "DOM Error while querying"), diff --git a/docs/home/quickstart.md b/docs/home/quickstart.md index 9f146362c..295047a89 100644 --- a/docs/home/quickstart.md +++ b/docs/home/quickstart.md @@ -225,7 +225,11 @@ What still differs from reading the whole document: - each found element holds the remote object of its match until the page navigates (an element read from the document held one only after its first call); - until something reads the document (`find`, `update`, a lookup under an element…), the browser - sends no `DOM.*` mutation events for the page, so a busy page may count as idle sooner. + sends no `DOM.*` mutation events for the page, so a busy page may count as idle sooner, and the DOM + agent is not enabled: a `tab.dom.disable()` sent by hand then fails, as on a tab that never read it; +- `element.node.nodeId`, `element.parentId`, `element.tree` and `element.parent` are plain + properties: their first read cannot fetch the document by itself, so code that reads them calls + `element.update()` first. Lookups under an element (`element.querySelector`, `element.querySelectorAll`), `find`, `findAll` and `xpath` read the document, as before. From d01b38358178b425ceadfb11119cf08e15872b74 Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Fri, 20 Nov 2026 15:22:31 +0100 Subject: [PATCH 09/16] fix: selectAll leaves no object in the page and reads the document when its matches outweigh it - The array and the matches of an in-page querySelectorAll live in an object group of their own, released in the same round trip as the descriptions (sent after them), on every path: a polled lookup no longer leaves one object per match in the page. Its elements resolve their node at their first call, as elements read from the document. - When the matches' subtrees hold more elements than the whole document (nested matches, a selector matching most of the page), the page answers "document" and the lookup reads the document, the smaller transfer, as before. - Only a DOMException SyntaxError is an invalid selector; a SyntaxError thrown by a script of the page stays an EvaluateException. --- .../kotlin/dev/kdriver/core/tab/DefaultTab.kt | 115 ++++++++++++------ .../kotlin/dev/kdriver/core/tab/Tab.kt | 11 +- .../core/tab/LookupsInPageBehaviourTest.kt | 22 ++++ .../dev/kdriver/core/tab/LookupsInPageTest.kt | 108 +++++++++++++--- docs/home/quickstart.md | 10 +- 5 files changed, 200 insertions(+), 66 deletions(-) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt index f36bcf480..09625d3ac 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt @@ -1,11 +1,13 @@ package dev.kdriver.core.tab import dev.kdriver.cdp.CDPException +import dev.kdriver.cdp.CommandMode import dev.kdriver.cdp.Serialization import dev.kdriver.cdp.domain.* import dev.kdriver.cdp.domain.Input import dev.kdriver.core.browser.Browser import dev.kdriver.core.connection.DefaultConnection +import dev.kdriver.core.connection.PendingCommand import dev.kdriver.core.dom.DefaultElement import dev.kdriver.core.dom.Element import dev.kdriver.core.dom.NodeOrElement @@ -19,7 +21,6 @@ import io.ktor.util.logging.* import io.ktor.utils.io.core.* import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Deferred import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll @@ -32,10 +33,12 @@ import kotlinx.io.files.SystemFileSystem import kotlinx.serialization.builtins.serializer import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.decodeFromJsonElement +import kotlinx.serialization.json.encodeToJsonElement import kotlin.concurrent.Volatile import kotlin.io.encoding.Base64 import kotlin.io.encoding.ExperimentalEncodingApi import kotlin.math.abs +import kotlin.random.Random import kotlin.time.Clock import kotlin.time.Duration.Companion.seconds @@ -460,55 +463,81 @@ open class DefaultTab( /** * `document.querySelectorAll(selector)` run by the page, each match then described with its subtree: see - * [Tab.querySelector]. One round trip when nothing matches (the page answers `null`), otherwise three: the - * evaluation, the array's own properties, and the descriptions, sent together. + * [Tab.querySelectorAll]. One round trip when nothing matches (the page answers `null`), otherwise three: the + * evaluation, the array's own properties, then every description and the release of the objects, sent together. + * + * The array and the matches live in an object group of their own, released once the matches are described, so a + * lookup leaves no object behind in the page: an element found here resolves its node at its first call, as an + * element read from the document does. When the matches' subtrees hold more elements than the whole document + * (nested matches, a selector matching most of the page), the page answers `"document"` instead, and the lookup + * reads the document, which is then the smaller transfer. */ private suspend fun querySelectorAllInPage(selector: String): List { - val array = evaluateLookup( + val group = "kdriver-lookup-${Random.nextLong().toULong().toString(16)}" + val found = evaluateLookup( "(() => { const all = Array.from(document.querySelectorAll(${jsStringLiteral(selector)}));" + - " return all.length ? all : null; })()", + " if (!all.length) return null;" + + " const described = all.reduce((sum, e) => sum + 1 + e.getElementsByTagName('*').length, 0);" + + " return described > document.getElementsByTagName('*').length ? 'document' : all; })()", protocolMethod = "DOM.querySelectorAll", + objectGroup = group, ) ?: return emptyList() - val arrayId = array.objectId!! - // The array is a cleanup to release on every path, cancellation included (NonCancellable); while the matches - // are described, in parallel with them, at no extra wait. Gone with the page, it needs no release. - var release: Deferred? = null - var gone = false + val arrayId = found.objectId ?: return querySelectorAllInDocument(selector) + // From here the group holds objects: it is released on every path, cancellation included (NonCancellable), + // and on the main path in the same round trip as the descriptions, sent after them. + var release: PendingCommand? = null try { - val properties = unlessGone { runtime.getProperties(objectId = arrayId, ownProperties = true).result } - if (properties == null) { - gone = true - return emptyList() - } - val matches = properties + val properties = unlessGone { runtime.getProperties(objectId = arrayId, ownProperties = true) } + ?: return emptyList() + val matches = properties.result .mapNotNull { property -> property.name.toIntOrNull()?.let { index -> index to property.value } } .sortedBy { it.first } - .mapNotNull { (_, value) -> value?.takeIf { it.objectId != null } } - return coroutineScope { - release = async(NonCancellable) { releaseQuietly(arrayId) } - val described = matches.map { match -> async { describeMatch(match) } }.awaitAll() - // A match gone before it was described means the page navigated during the lookup: no match at all, - // as for one lookup, rather than a part of the old page's matches. - if (null in described) emptyList() else described.filterNotNull() + .mapNotNull { (_, value) -> value?.objectId } + val describing = matches.map { objectId -> + sendCommand("DOM.describeNode", describeParameter(objectId), CommandMode.DEFAULT) } + release = sendCommand("Runtime.releaseObjectGroup", releaseParameter(group), CommandMode.DEFAULT) + val described = describing.map { pending -> awaitDescription(pending) } + // A match gone before it was described means the page navigated during the lookup: no match at all, as + // for one lookup, rather than a part of the old page's matches. Any other error is thrown, once every + // reply has been read. + described.firstNotNullOfOrNull { it.exceptionOrNull() }?.let { throw it } + val nodes = described.map { it.getOrNull() } + return if (null in nodes) emptyList() else nodes.filterNotNull().map { DefaultElement(this, it) } } finally { - val pending = release + val sent = release withContext(NonCancellable) { - if (pending != null) pending.await() else if (!gone) releaseQuietly(arrayId) + try { + if (sent != null) sent.await() else runtime.releaseObjectGroup(group) + } catch (_: Exception) { + // A cleanup: already gone with the page, timed out, or the connection is closing. Under + // NonCancellable, a CancellationException here is the command's own timeout, never the caller's. + } } } } - // Releases a remote object the lookup no longer needs. A cleanup, always run under NonCancellable, so a - // CancellationException here is the command's own timeout, never the caller's cancellation: no failure of it ever - // fails the lookup (the page drops the object at its next navigation anyway). - private suspend fun releaseQuietly(objectId: String) { + // The node of a description sent by querySelectorAllInPage: a success holding null when the match is gone, a + // failure holding any other error, so that every reply is read before one is thrown. + private suspend fun awaitDescription(pending: PendingCommand): Result = try { - runtime.releaseObject(objectId) - } catch (_: Exception) { - // Already gone, timed out, or the connection is closing: nothing to clean up. + Result.success( + unlessGone { pending.await() } + ?.let { Serialization.json.decodeFromJsonElement(it).node } + ) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Result.failure(e) } - } + + private fun describeParameter(objectId: String): JsonElement = + Serialization.json.encodeToJsonElement( + DOM.DescribeNodeParameter(objectId = objectId, depth = -1, pierce = true) + ) + + private fun releaseParameter(group: String): JsonElement = + Serialization.json.encodeToJsonElement(Runtime.ReleaseObjectGroupParameter(objectGroup = group)) /** * `document.querySelector(selector)` run by the page, the match then described with its subtree: see @@ -518,12 +547,13 @@ open class DefaultTab( val match = evaluateLookup( "document.querySelector(${jsStringLiteral(selector)})", protocolMethod = "DOM.querySelector", - ) ?: return null + )?.takeIf { it.objectId != null } ?: return null return describeMatch(match) } /** - * Evaluates [expression] in the page and returns the object it yields, or null when it yields no object (`null`). + * Evaluates [expression] in the page and returns the object or string it yields, or null when it yields neither + * (`null`). The objects it creates go to [objectGroup] when given. * * An invalid selector makes the page throw a `SyntaxError`: it is thrown as the error the browser gives * [protocolMethod] (`DOM.querySelector` or `DOM.querySelectorAll`) for that selector, a [CDPException] with code @@ -531,8 +561,13 @@ open class DefaultTab( * did. Any other exception of the page (a page that replaced `document.querySelector`) is thrown as an * [EvaluateException]. */ - private suspend fun evaluateLookup(expression: String, protocolMethod: String): Runtime.RemoteObject? { - val evaluated = unlessGone { runtime.evaluate(expression = expression) } ?: return null + private suspend fun evaluateLookup( + expression: String, + protocolMethod: String, + objectGroup: String? = null, + ): Runtime.RemoteObject? { + val evaluated = unlessGone { runtime.evaluate(expression = expression, objectGroup = objectGroup) } + ?: return null evaluated.exceptionDetails?.let { details -> if (details.isSyntaxError()) { disableDomAgent() @@ -540,12 +575,12 @@ open class DefaultTab( } throw EvaluateException(details) } - return evaluated.result.takeIf { it.objectId != null } + return evaluated.result.takeIf { it.objectId != null || it.type == "string" } } - // The `SyntaxError` (a DOMException) the page throws for a selector it cannot parse. + // The `SyntaxError` the page throws for a selector it cannot parse: a DOMException, not an error a script threw. private fun Runtime.ExceptionDetails.isSyntaxError(): Boolean = - exception?.description?.startsWith("SyntaxError") == true + exception?.className == "DOMException" && exception?.description?.startsWith("SyntaxError") == true /** * The element of [match], a remote object the page returned: its node and subtree (`DOM.describeNode`, depth -1, diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt b/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt index cd2128377..b073ff371 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt @@ -384,8 +384,11 @@ interface Tab : Connection { * * Without [node], the page runs `document.querySelectorAll` and the matches are described together, in document * order: one round trip when nothing matches, three otherwise (the evaluation, the list of matches, then every - * description at once, with the release of the list). Each match is described with its subtree, so many matches, - * or nested ones, can add up to more than the document would. The elements are as for [querySelector]. + * description at once, with the release of the objects the lookup created). The elements are as for + * [querySelector], except that they keep no object of the page: each resolves its node at its first call, as an + * element read from the document does. When the matches' subtrees would hold more elements than the whole + * document (nested matches, a selector matching most of the page), the document is read instead, as before, and + * the elements then have their node ids and tree. * * @param selector CSS selector. (first time? See https://www.w3schools.com/cssref/css_selectors.php) * @param node For internal use. The node to start the search from. Defaults to the document root. @@ -419,8 +422,8 @@ interface Tab : Connection { * * What else differs from reading the document: * - the page's own `document.querySelector` runs: a page that replaces it changes the result; - * - each element holds the remote object of its match until the page navigates (an element read from the document - * holds one only after its first call); + * - the element found by [select] or [querySelector] holds the remote object of its match until the page + * navigates (an element read from the document held one only after its first call); * - until something reads the document (a lookup under an element, [find], [Element.update]…), the browser sends * no `DOM.*` mutation events for the page, so on a busy page the connection may count as idle sooner; the DOM * agent is not enabled either, so a `DOM.disable` sent by hand then fails, as on a tab that never read it. diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt index 35e399246..c6d4ed202 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt @@ -17,6 +17,7 @@ import kotlin.test.assertFailsWith import kotlin.test.assertNotEquals import kotlin.test.assertNotNull import kotlin.test.assertNull +import kotlin.test.assertTrue /** * On a real page, the lookups the page runs (`select`, `selectAll`, `querySelector`, `querySelectorAll` without a @@ -110,6 +111,27 @@ class LookupsInPageBehaviourTest { assertEquals("open", select("#panel", timeout = 5_000)["data-state"]) } + @Test + fun anElementOfSelectAll_keepsNoObject_andCanBeClicked() = onPage { + rawEvaluate("document.getElementById('label').onclick = (e) => e.target.textContent = 'Hit'") + val label = selectAll("#label", timeout = 5_000).single() + + assertNull(label.objectId, "the objects of the lookup were released") + label.click() + + assertEquals("Hit", select("#label", timeout = 5_000).text) + } + + @Test + fun selectAll_readsTheDocument_whenTheMatchesOutweighIt() = onPage { + val before = allOnTheDocument("html, body").map { it.seen() } + + val outer = selectAll("html, body", timeout = 5_000) + + assertEquals(before, outer.map { it.seen() }) + assertTrue(outer.all { it.node.nodeId != 0 && it.tree != null }, "read from the document, as before") + } + @Test fun select_seesTheNewDocumentAfterANavigation() = onPage { rawEvaluate("document.getElementById('title').textContent = 'Changed'") diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt index b57b2bf01..5e98cb00b 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt @@ -264,7 +264,9 @@ class LookupsInPageTest { assertEquals(listOf("Runtime.evaluate"), tab.sent) assertEquals( "(() => { const all = Array.from(document.querySelectorAll(\".item\"));" + - " return all.length ? all : null; })()", + " if (!all.length) return null;" + + " const described = all.reduce((sum, e) => sum + 1 + e.getElementsByTagName('*').length, 0);" + + " return described > document.getElementsByTagName('*').length ? 'document' : all; })()", tab.transport.sent.single().param("expression"), ) tab.close() @@ -302,10 +304,16 @@ class LookupsInPageTest { assertEquals("array", tab.transport.sent.single { it.method == "Runtime.getProperties" }.param("objectId")) assertEquals("true", tab.transport.sent.single { it.method == "Runtime.getProperties" }.param("ownProperties")) assertEquals(100, testScheduler.currentTime, "the descriptions are sent together, one round trip for all") + val group = tab.transport.sent.single { it.method == "Runtime.evaluate" }.param("objectGroup")!! + assertTrue(group.startsWith("kdriver-lookup-"), group) assertEquals( - "array", tab.transport.sent.single { it.method == "Runtime.releaseObject" }.param("objectId"), - "the array is released while the matches are described" + listOf("DOM.describeNode", "DOM.describeNode", "DOM.describeNode", "Runtime.releaseObjectGroup"), + tab.sent.dropWhile { it != "DOM.describeNode" }, + "the objects of the lookup are released in the same round trip, after the descriptions", ) + val released = tab.transport.sent.single { it.method == "Runtime.releaseObjectGroup" } + assertEquals(group, released.param("objectGroup")) + assertEquals(listOf(null, null, null), found.map { it.objectId }, "no object of the page is kept") assertTrue("DOM.getDocument" !in tab.sent) tab.close() } @@ -324,13 +332,13 @@ class LookupsInPageTest { "DOM.describeNode" -> if (it.param("objectId") == "li-0") Reply.error("Could not find object with given id") else Reply.ok(item(20, "Beta")) - "Runtime.releaseObject" -> Reply.error("Could not find object with given id") + "Runtime.releaseObjectGroup" -> Reply.error("Could not find object with given id") else -> Reply.ok() } } assertEquals(emptyList(), tab.querySelectorAll(".item"), "the page navigated: none of its old matches") - assertTrue("Runtime.releaseObject" in tab.sent) + assertTrue("Runtime.releaseObjectGroup" in tab.sent) tab.close() } @@ -376,7 +384,7 @@ class LookupsInPageTest { } assertEquals(emptyList(), tab.querySelectorAll(".item")) - assertEquals(listOf("Runtime.evaluate", "Runtime.getProperties"), tab.sent) + assertEquals(listOf("Runtime.evaluate", "Runtime.getProperties", "Runtime.releaseObjectGroup"), tab.sent) tab.close() } @@ -427,7 +435,7 @@ class LookupsInPageTest { } @Test - fun aDescriptionThatFails_isThrown_stopsTheOthers_andTheArrayIsStillReleased() = runTest(StandardTestDispatcher()) { + fun aDescriptionThatFails_isThrown_onceEveryReplyIsRead() = runTest(StandardTestDispatcher()) { val tab = tab { when (it.method) { "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) @@ -440,19 +448,19 @@ class LookupsInPageTest { "DOM.describeNode" -> if (it.param("objectId") == "li-0") Reply.error("Message is too large", latency = 10) else Reply.ok(item(20, "Beta"), latency = 1_000) - "Runtime.releaseObject" -> Reply.ok(latency = 50) + "Runtime.releaseObjectGroup" -> Reply.ok(latency = 50) else -> Reply.ok() } } assertFailsWith { tab.querySelectorAll(".item") } - assertEquals("array", tab.transport.sent.single { it.method == "Runtime.releaseObject" }.param("objectId")) - assertEquals(50, testScheduler.currentTime, "the release was awaited, the other description was not") + assertTrue("Runtime.releaseObjectGroup" in tab.sent) + assertEquals(1_000, testScheduler.currentTime, "every reply was read before the error was thrown") tab.close() } @Test - fun aLookupCancelledWhileTheArrayIsRead_stillReleasesIt() = runTest(StandardTestDispatcher()) { + fun aLookupCancelledWhileTheArrayIsRead_stillReleasesItsObjects() = runTest(StandardTestDispatcher()) { val tab = tab { when (it.method) { "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) @@ -467,7 +475,10 @@ class LookupsInPageTest { advanceUntilIdle() assertTrue(lookup.isCancelled) - assertEquals("array", tab.transport.sent.single { it.method == "Runtime.releaseObject" }.param("objectId")) + assertEquals( + tab.transport.sent.single { it.method == "Runtime.evaluate" }.param("objectGroup"), + tab.transport.sent.single { it.method == "Runtime.releaseObjectGroup" }.param("objectGroup"), + ) tab.close() } @@ -497,10 +508,7 @@ class LookupsInPageTest { "Message is too large", assertFailsWith { listing.querySelectorAll(".item") }.originalMessage ) - assertEquals( - "array", listing.transport.sent.single { it.method == "Runtime.releaseObject" }.param("objectId"), - "the array is released before the error is thrown" - ) + assertTrue("Runtime.releaseObjectGroup" in listing.sent, "the objects are released before the error is thrown") listing.close() val evaluating = tab { @@ -520,7 +528,7 @@ class LookupsInPageTest { "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) "Runtime.getProperties" -> Reply.ok(arrayOfOne) "DOM.describeNode" -> Reply.ok(item(10, "Alpha")) - "Runtime.releaseObject" -> Reply.error("Session closed") + "Runtime.releaseObjectGroup" -> Reply.error("Session closed") else -> Reply.ok() } } @@ -733,4 +741,70 @@ class LookupsInPageTest { tab.close() } + @Test + fun querySelectorAll_readsTheDocument_whenTheMatchesOutweighIt() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok("""{"result":{"type":"string","value":"document"}}""") + "DOM.getDocument" -> Reply.ok(list) + "DOM.querySelectorAll" -> Reply.ok("""{"nodeIds":[5,7]}""") + else -> Reply.ok() + } + } + + val found = tab.querySelectorAll("ul, li") + + assertEquals(listOf(5, 7), found.map { it.node.nodeId }, "read from the document, as before") + assertEquals(listOf(1, 1), found.map { it.tree?.nodeId }) + assertEquals(listOf("Runtime.evaluate", "DOM.getDocument", "DOM.querySelectorAll"), tab.sent) + tab.close() + } + + @Test + fun anElementOfQuerySelectorAll_resolvesItsNodeAtItsFirstCall() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) + "Runtime.getProperties" -> Reply.ok(arrayOfOne) + "DOM.describeNode" -> Reply.ok(item(10, "Alpha")) + "DOM.resolveNode" -> Reply.ok("""{"object":{"type":"object","subtype":"node","objectId":"obj-2"}}""") + "Runtime.callFunctionOn" -> Reply.ok(valueReply("null")) + else -> Reply.ok() + } + } + + tab.querySelectorAll(".item").single().click() + + assertEquals("10", tab.transport.sent.single { it.method == "DOM.resolveNode" }.param("backendNodeId")) + assertEquals(listOf("obj-2"), tab.transport.objectIdsOf()) + tab.close() + } + + @Test + fun aSyntaxErrorThrownByAScriptOfThePage_isAnEvaluateException() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok( + """{"result":{"type":"object","subtype":"error","objectId":"err"},"exceptionDetails":""" + + """{"exceptionId":1,"text":"Uncaught","lineNumber":0,"columnNumber":9,"exception":""" + + """{"type":"object","subtype":"error","className":"SyntaxError",""" + + """"description":"SyntaxError: thrown by the page"}}}""" + ) + else -> Reply.ok() + } + } + + assertFailsWith { tab.querySelector("#go") } + tab.close() + } + + @Test + fun aStringAnsweredForQuerySelector_isNoMatch() = runTest(StandardTestDispatcher()) { + val tab = tab { Reply.ok("""{"result":{"type":"string","value":"document"}}""") } + + assertNull(tab.querySelector("#go")) + assertEquals(listOf("Runtime.evaluate"), tab.sent) + tab.close() + } + } diff --git a/docs/home/quickstart.md b/docs/home/quickstart.md index 295047a89..3b3e31837 100644 --- a/docs/home/quickstart.md +++ b/docs/home/quickstart.md @@ -200,9 +200,9 @@ the page is large or keeps changing. | What | How | | --- | --- | | Commands for `select` / `querySelector` | `Runtime.evaluate`, then `DOM.describeNode` of the match (one round trip when nothing matches) | -| Commands for `selectAll` / `querySelectorAll` | one `Runtime.evaluate` when nothing matches; otherwise also `Runtime.getProperties`, then every `DOM.describeNode` sent together, with the release of the list | -| Data received | the matches and their subtrees (many or nested matches can add up to more than the document) | -| First call on a found element (`click`, `apply`, …) | uses the object the page returned, no `DOM.resolveNode` | +| Commands for `selectAll` / `querySelectorAll` | one `Runtime.evaluate` when nothing matches; otherwise also `Runtime.getProperties`, then every `DOM.describeNode` sent together, with the release of the objects the lookup created | +| Data received | the matches and their subtrees; when they would hold more elements than the whole document (nested matches, a selector matching most of the page), the document is read instead, as before | +| First call on a found element (`click`, `apply`, …) | `select` / `querySelector`: uses the object the page returned, no `DOM.resolveNode`; `selectAll` / `querySelectorAll`: resolves the node first, as before | | Text, attributes, children, `backendNodeId` | read from the match and its subtree, as before | | `element.node.nodeId`, `element.parentId`, `element.tree`, `element.parent` | 0, `null`, `null`, and `parent` throws, until `element.update()` reads the document; a lookup under the element does it by itself | | Shadow roots, iframes | not searched (`selectAll(includeFrames = true)` reads the document to search inside each iframe, as before) | @@ -222,8 +222,8 @@ item.parent?.tag // "ul" What still differs from reading the whole document: - the page's own `document.querySelector` runs, so a page that replaces it changes the result; -- each found element holds the remote object of its match until the page navigates (an element read - from the document held one only after its first call); +- the element found by `select` or `querySelector` holds the remote object of its match until the + page navigates (an element read from the document held one only after its first call); - until something reads the document (`find`, `update`, a lookup under an element…), the browser sends no `DOM.*` mutation events for the page, so a busy page may count as idle sooner, and the DOM agent is not enabled: a `tab.dom.disable()` sent by hand then fails, as on a tab that never read it; From 3be39c8a123706004fd2de55c1f585a4fcc5ac72 Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Fri, 20 Nov 2026 15:38:42 +0100 Subject: [PATCH 10/16] fix: in-page lookups leave no object in the page, and bound their cleanup - select and querySelector put the match in an object group of the lookup, released in the same round trip as its description, like selectAll: a found element keeps no object of the page and resolves its node at its first call, as before, so a polled lookup no longer pins one object per call. - The release waits two seconds at most, so a cancelled or timed-out lookup is not held by a slow connection for a whole command timeout. - The selectAll script uses no global of the page but querySelectorAll and getElementsByTagName, and stops counting the matches' elements as soon as they pass the document's. --- .../dev/kdriver/core/dom/DefaultElement.kt | 9 - .../kotlin/dev/kdriver/core/tab/DefaultTab.kt | 154 ++++++++++-------- .../kotlin/dev/kdriver/core/tab/Tab.kt | 13 +- .../core/tab/LookupsInPageBehaviourTest.kt | 2 +- .../dev/kdriver/core/tab/LookupsInPageTest.kt | 50 +++--- .../dev/kdriver/core/tab/SettledLookupTest.kt | 5 +- docs/home/quickstart.md | 8 +- 7 files changed, 134 insertions(+), 107 deletions(-) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt b/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt index 8f9e44ea0..e9183f5c3 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt @@ -90,15 +90,6 @@ open class DefaultElement( override val attrs: List get() = node.attributes?.chunked(2)?.map { it.first() } ?: emptyList() - /** - * Keeps [found], the remote object a lookup in the page already returned for [node], so that the first call on this - * element needs no `DOM.resolveNode`. Calls fall back on resolving the node again when the browser rejects it. - */ - internal fun keepRemoteObject(found: Runtime.RemoteObject) { - remoteObject = found - remoteObjectBackendNodeId = node.backendNodeId - } - /** * Binds an element found in the page (no node id, no [tree]) to the whole document, as [update] does, without * resolving its object again: [node] becomes the document's node of the same backend node id, with its node ids, diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt index 09625d3ac..cdb2203bf 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt @@ -27,6 +27,7 @@ import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull import kotlinx.io.buffered import kotlinx.io.files.Path import kotlinx.io.files.SystemFileSystem @@ -466,59 +467,104 @@ open class DefaultTab( * [Tab.querySelectorAll]. One round trip when nothing matches (the page answers `null`), otherwise three: the * evaluation, the array's own properties, then every description and the release of the objects, sent together. * - * The array and the matches live in an object group of their own, released once the matches are described, so a - * lookup leaves no object behind in the page: an element found here resolves its node at its first call, as an - * element read from the document does. When the matches' subtrees hold more elements than the whole document - * (nested matches, a selector matching most of the page), the page answers `"document"` instead, and the lookup - * reads the document, which is then the smaller transfer. + * When the matches' subtrees hold more elements than the whole document (nested matches, a selector matching most + * of the page), the page answers `"document"` instead, and the lookup reads the document, which is then the smaller + * transfer. The count stops as soon as it passes the document's, so the page never walks much more than once its + * own size. The script uses no global of the page but `document.querySelectorAll` and `getElementsByTagName`. */ - private suspend fun querySelectorAllInPage(selector: String): List { - val group = "kdriver-lookup-${Random.nextLong().toULong().toString(16)}" + private suspend fun querySelectorAllInPage(selector: String): List = inLookupGroup { group -> val found = evaluateLookup( - "(() => { const all = Array.from(document.querySelectorAll(${jsStringLiteral(selector)}));" + + "(() => { const all = document.querySelectorAll(${jsStringLiteral(selector)});" + " if (!all.length) return null;" + - " const described = all.reduce((sum, e) => sum + 1 + e.getElementsByTagName('*').length, 0);" + - " return described > document.getElementsByTagName('*').length ? 'document' : all; })()", + " const most = document.getElementsByTagName('*').length; const matches = []; let described = 0;" + + " for (let i = 0; i < all.length; i++) {" + + " described += 1 + all[i].getElementsByTagName('*').length;" + + " if (described > most) return 'document'; matches[i] = all[i]; }" + + " return matches; })()", protocolMethod = "DOM.querySelectorAll", - objectGroup = group, - ) ?: return emptyList() - val arrayId = found.objectId ?: return querySelectorAllInDocument(selector) - // From here the group holds objects: it is released on every path, cancellation included (NonCancellable), - // and on the main path in the same round trip as the descriptions, sent after them. + objectGroup = group.name, + ) ?: return@inLookupGroup emptyList() + val arrayId = found.objectId ?: return@inLookupGroup querySelectorAllInDocument(selector) + group.holdsObjects = true + val properties = unlessGone { runtime.getProperties(objectId = arrayId, ownProperties = true) } + ?: return@inLookupGroup emptyList() + val matches = properties.result + .mapNotNull { property -> property.name.toIntOrNull()?.let { index -> index to property.value } } + .sortedBy { it.first } + .mapNotNull { (_, value) -> value?.objectId } + describeAndRelease(group, matches)?.map { DefaultElement(this, it) } ?: emptyList() + } + + /** + * `document.querySelector(selector)` run by the page, the match then described with its subtree: see + * [Tab.querySelector]. Two round trips when something matches (the evaluation, then the description and the + * release of the object, sent together), one otherwise. + */ + private suspend fun querySelectorInPage(selector: String): Element? = inLookupGroup { group -> + val match = evaluateLookup( + "document.querySelector(${jsStringLiteral(selector)})", + protocolMethod = "DOM.querySelector", + objectGroup = group.name, + )?.objectId ?: return@inLookupGroup null + group.holdsObjects = true + describeAndRelease(group, listOf(match))?.single()?.let { DefaultElement(this, it) } + } + + /** + * The objects an in-page lookup creates in the page (the match, or the array and its matches), all in one group + * named after the lookup, and the release of that group once it is sent. + */ + private class LookupGroup(val name: String) { + var holdsObjects = false var release: PendingCommand? = null + } + + /** + * Runs [lookup] with a [LookupGroup] of its own, then releases the group, so that a lookup leaves no object behind + * in the page, on every path, cancellation included: an element found in the page resolves its node at its first + * call, as an element read from the document does. The release is a cleanup: it runs under NonCancellable, waits + * [LOOKUP_RELEASE_WAIT] at most, and none of its failures fails the lookup (the page drops the objects at its next + * navigation anyway). + */ + private suspend fun inLookupGroup(lookup: suspend (LookupGroup) -> T): T { + val group = LookupGroup("kdriver-lookup-${Random.nextLong().toULong().toString(16)}") try { - val properties = unlessGone { runtime.getProperties(objectId = arrayId, ownProperties = true) } - ?: return emptyList() - val matches = properties.result - .mapNotNull { property -> property.name.toIntOrNull()?.let { index -> index to property.value } } - .sortedBy { it.first } - .mapNotNull { (_, value) -> value?.objectId } - val describing = matches.map { objectId -> - sendCommand("DOM.describeNode", describeParameter(objectId), CommandMode.DEFAULT) - } - release = sendCommand("Runtime.releaseObjectGroup", releaseParameter(group), CommandMode.DEFAULT) - val described = describing.map { pending -> awaitDescription(pending) } - // A match gone before it was described means the page navigated during the lookup: no match at all, as - // for one lookup, rather than a part of the old page's matches. Any other error is thrown, once every - // reply has been read. - described.firstNotNullOfOrNull { it.exceptionOrNull() }?.let { throw it } - val nodes = described.map { it.getOrNull() } - return if (null in nodes) emptyList() else nodes.filterNotNull().map { DefaultElement(this, it) } + return lookup(group) } finally { - val sent = release - withContext(NonCancellable) { - try { - if (sent != null) sent.await() else runtime.releaseObjectGroup(group) - } catch (_: Exception) { - // A cleanup: already gone with the page, timed out, or the connection is closing. Under - // NonCancellable, a CancellationException here is the command's own timeout, never the caller's. + if (group.holdsObjects) withContext(NonCancellable) { + withTimeoutOrNull(LOOKUP_RELEASE_WAIT) { + try { + val sent = group.release + if (sent != null) sent.await() else runtime.releaseObjectGroup(group.name) + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + // Already gone with the page, or the connection is closing: nothing left to release. + } } } } } - // The node of a description sent by querySelectorAllInPage: a success holding null when the match is gone, a - // failure holding any other error, so that every reply is read before one is thrown. + /** + * Describes [objectIds] with their subtrees (`DOM.describeNode`, depth -1, piercing), then releases [group]: the + * descriptions and the release are sent one after the other, so the browser runs them in that order, in one round + * trip. Null when a match is gone before it was described (the page navigated during the lookup: no match at all, + * rather than a part of the old page's); any other error is thrown, once every reply has been read. + */ + private suspend fun describeAndRelease(group: LookupGroup, objectIds: List): List? { + val describing = objectIds.map { objectId -> + sendCommand("DOM.describeNode", describeParameter(objectId), CommandMode.DEFAULT) + } + group.release = sendCommand("Runtime.releaseObjectGroup", releaseParameter(group.name), CommandMode.DEFAULT) + val described = describing.map { pending -> awaitDescription(pending) } + described.firstNotNullOfOrNull { it.exceptionOrNull() }?.let { throw it } + val nodes = described.map { it.getOrNull() } + return if (null in nodes) null else nodes.filterNotNull() + } + + // The node of a description sent by describeAndRelease: a success holding null when the match is gone, a failure + // holding any other error, so that every reply is read before one is thrown. private suspend fun awaitDescription(pending: PendingCommand): Result = try { Result.success( @@ -539,18 +585,6 @@ open class DefaultTab( private fun releaseParameter(group: String): JsonElement = Serialization.json.encodeToJsonElement(Runtime.ReleaseObjectGroupParameter(objectGroup = group)) - /** - * `document.querySelector(selector)` run by the page, the match then described with its subtree: see - * [Tab.querySelector]. Two round trips when something matches, one otherwise. - */ - private suspend fun querySelectorInPage(selector: String): Element? { - val match = evaluateLookup( - "document.querySelector(${jsStringLiteral(selector)})", - protocolMethod = "DOM.querySelector", - )?.takeIf { it.objectId != null } ?: return null - return describeMatch(match) - } - /** * Evaluates [expression] in the page and returns the object or string it yields, or null when it yields neither * (`null`). The objects it creates go to [objectGroup] when given. @@ -582,17 +616,6 @@ open class DefaultTab( private fun Runtime.ExceptionDetails.isSyntaxError(): Boolean = exception?.className == "DOMException" && exception?.description?.startsWith("SyntaxError") == true - /** - * The element of [match], a remote object the page returned: its node and subtree (`DOM.describeNode`, depth -1, - * piercing), with [match] kept so its first call needs no `DOM.resolveNode`. Null when the browser no longer knows - * the object (the page navigated in between): the match is gone, and `select` tries again as for no match. - */ - private suspend fun describeMatch(match: Runtime.RemoteObject): Element? { - val node = unlessGone { dom.describeNode(objectId = match.objectId, depth = -1, pierce = true).node } - ?: return null - return DefaultElement(this, node).also { it.keepRemoteObject(match) } - } - /** * Runs [command] of an in-page lookup, or returns null when the browser no longer knows what it refers to: the * object or the execution context was dropped by a navigation in between, so the lookup found nothing and `select` @@ -1033,6 +1056,9 @@ private val GONE = listOf( "context was destroyed", ) +/** How long the release of the objects of an in-page lookup may hold the lookup, at most, in milliseconds. */ +private const val LOOKUP_RELEASE_WAIT = 2_000L + /** The code and message Chrome answers `DOM.querySelector(All)` with for a selector it cannot parse. */ private const val INVALID_SELECTOR_CODE = -32000 private const val INVALID_SELECTOR_MESSAGE = "DOM Error while querying" diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt b/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt index b073ff371..91484d709 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt @@ -385,8 +385,7 @@ interface Tab : Connection { * Without [node], the page runs `document.querySelectorAll` and the matches are described together, in document * order: one round trip when nothing matches, three otherwise (the evaluation, the list of matches, then every * description at once, with the release of the objects the lookup created). The elements are as for - * [querySelector], except that they keep no object of the page: each resolves its node at its first call, as an - * element read from the document does. When the matches' subtrees would hold more elements than the whole + * [querySelector]. When the matches' subtrees would hold more elements than the whole * document (nested matches, a selector matching most of the page), the document is read instead, as before, and * the elements then have their node ids and tree. * @@ -407,14 +406,14 @@ interface Tab : Connection { * * Without [node] (and in [select], [selectAll] and [querySelectorAll] without it), the page runs the selector: * `document.querySelector` is evaluated (`Runtime.evaluate`, the selector entering the script only as a JSON string - * literal), then only the match is described, with its subtree (`DOM.describeNode`, depth -1, piercing). The - * whole document is never read: two small round trips when something matches, one otherwise, whatever the size of - * the page. + * literal), then only the match is described, with its subtree (`DOM.describeNode`, depth -1, piercing), and the + * object the page returned is released in the same round trip. The whole document is never read: two small round + * trips when something matches, one otherwise, whatever the size of the page. * * The element found: * - has its node and subtree: [Element.tag], [Element.text], [Element.textAll], attributes, * [Element.children] and [Element.backendNodeId] read as from a document; - * - keeps the object the page returned, so its first call (`click`, `apply`, …) needs no `DOM.resolveNode`; + * - keeps no object of the page: its first call (`click`, `apply`, …) resolves its node, as before; * - has no node id yet: `node.nodeId` and the node ids of its subtree are 0, [Element.parentId] and * [Element.tree] are null and [Element.parent] throws, until [Element.update] reads the document, which also * binds it. A lookup under the element ([Element.querySelector], or a [NodeOrElement] passed back here) binds it @@ -422,8 +421,6 @@ interface Tab : Connection { * * What else differs from reading the document: * - the page's own `document.querySelector` runs: a page that replaces it changes the result; - * - the element found by [select] or [querySelector] holds the remote object of its match until the page - * navigates (an element read from the document held one only after its first call); * - until something reads the document (a lookup under an element, [find], [Element.update]…), the browser sends * no `DOM.*` mutation events for the page, so on a busy page the connection may count as idle sooner; the DOM * agent is not enabled either, so a `DOM.disable` sent by hand then fails, as on a tab that never read it. diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt index c6d4ed202..ce0294be8 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt @@ -54,7 +54,7 @@ class LookupsInPageBehaviourTest { assertEquals(before.seen(), item.seen()) assertEquals(listOf("li", "Beta", "Beta", "class, data-rank"), item.seen().take(4)) - assertNotNull(item.objectId, "the element keeps the object the page returned") + assertNull(item.objectId, "the lookup left no object in the page") } @Test diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt index 5e98cb00b..aea6df6aa 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt @@ -82,9 +82,21 @@ class LookupsInPageTest { assertEquals("go", element["id"]) assertEquals(0, element.node.nodeId, "no node id: no document was requested") assertNull(element.tree) - assertEquals(listOf("Runtime.evaluate", "DOM.describeNode"), tab.sent.filter { it != "Target.getTargetInfo" }) + assertEquals( + listOf("Runtime.evaluate", "DOM.describeNode", "Runtime.releaseObjectGroup"), + tab.sent.filter { it != "Target.getTargetInfo" }, + ) val evaluate = tab.transport.sent.first { it.method == "Runtime.evaluate" } assertEquals("document.querySelector(\"#go\")", evaluate.param("expression")) + val group = evaluate.param("objectGroup")!! + assertTrue(group.startsWith("kdriver-lookup-"), group) + val release = tab.transport.sent.single { it.method == "Runtime.releaseObjectGroup" } + assertEquals(group, release.param("objectGroup")) + assertEquals( + tab.transport.sent.single { it.method == "DOM.describeNode" }.atMillis, + tab.transport.sent.single { it.method == "Runtime.releaseObjectGroup" }.atMillis, + "the release goes with the description, after it", + ) val describe = tab.transport.sent.first { it.method == "DOM.describeNode" } assertEquals("obj-1", describe.param("objectId")) assertEquals("-1", describe.param("depth")) @@ -93,44 +105,41 @@ class LookupsInPageTest { } @Test - fun select_firstCallUsesTheObjectOfTheLookup_withoutResolvingTheNode() = runTest(StandardTestDispatcher()) { + fun select_leavesNoObject_andTheFirstCallResolvesTheNode_asBefore() = runTest(StandardTestDispatcher()) { val tab = tab { when (it.method) { "Runtime.evaluate" -> Reply.ok(found("obj-1")) "DOM.describeNode" -> Reply.ok(button) + "DOM.resolveNode" -> Reply.ok("""{"object":{"type":"object","objectId":"obj-2"}}""") "Runtime.callFunctionOn" -> Reply.ok(valueReply("null")) "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) else -> Reply.ok() } } - tab.select("#go", timeout = 1_000).click() + val element = tab.select("#go", timeout = 1_000) + assertNull(element.objectId) + element.click() - assertEquals(listOf("obj-1"), tab.transport.objectIdsOf()) - assertTrue("DOM.resolveNode" !in tab.sent) + assertEquals(listOf("obj-2"), tab.transport.objectIdsOf()) + assertEquals("70", tab.transport.sent.single { it.method == "DOM.resolveNode" }.param("backendNodeId")) tab.close() } @Test - fun select_resolvesTheNodeAgain_whenTheObjectOfTheLookupIsStale() = runTest(StandardTestDispatcher()) { - var calls = 0 + fun theReleaseOfTheObjects_holdsTheLookupTwoSecondsAtMost() = runTest(StandardTestDispatcher()) { val tab = tab { when (it.method) { "Runtime.evaluate" -> Reply.ok(found("obj-1")) "DOM.describeNode" -> Reply.ok(button) - "Runtime.callFunctionOn" -> - if (calls++ == 0) Reply.error("Could not find object with given id") - else Reply.ok(valueReply("null")) - "DOM.resolveNode" -> Reply.ok("""{"object":{"type":"object","objectId":"obj-2"}}""") - "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) + "Runtime.releaseObjectGroup" -> Reply.ok(latency = 60_000) else -> Reply.ok() } } - tab.select("#go", timeout = 1_000).click() + assertEquals("button", tab.querySelector("#go")?.tag) - assertEquals(listOf("obj-1", "obj-2"), tab.transport.objectIdsOf()) - assertEquals("70", tab.transport.sent.single { it.method == "DOM.resolveNode" }.param("backendNodeId")) + assertEquals(2_000, testScheduler.currentTime) tab.close() } @@ -263,10 +272,13 @@ class LookupsInPageTest { assertEquals(listOf("Runtime.evaluate"), tab.sent) assertEquals( - "(() => { const all = Array.from(document.querySelectorAll(\".item\"));" + + "(() => { const all = document.querySelectorAll(\".item\");" + " if (!all.length) return null;" + - " const described = all.reduce((sum, e) => sum + 1 + e.getElementsByTagName('*').length, 0);" + - " return described > document.getElementsByTagName('*').length ? 'document' : all; })()", + " const most = document.getElementsByTagName('*').length; const matches = []; let described = 0;" + + " for (let i = 0; i < all.length; i++) {" + + " described += 1 + all[i].getElementsByTagName('*').length;" + + " if (described > most) return 'document'; matches[i] = all[i]; }" + + " return matches; })()", tab.transport.sent.single().param("expression"), ) tab.close() @@ -616,7 +628,7 @@ class LookupsInPageTest { assertEquals(1, button.tree?.nodeId) assertEquals("7", tab.transport.sent.single { it.method == "DOM.querySelector" }.param("nodeId")) assertEquals(8, text!!.node.nodeId) - assertEquals("obj-1", button.objectId, "the object of the lookup is kept, not resolved again") + assertNull(button.objectId, "bound without resolving its object") tab.querySelector("*", NodeOrElement.WrappedElement(button)) assertEquals(1, tab.sent.count { it == "DOM.getDocument" }, "a bound element is not bound again") assertEquals(2, tab.sent.count { it == "DOM.querySelector" }) diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/SettledLookupTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/SettledLookupTest.kt index 248422e0f..ab3e61e2b 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/SettledLookupTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/SettledLookupTest.kt @@ -63,7 +63,10 @@ class SettledLookupTest { assertEquals("https://example.test/", tab.targetInfo!!.url, "the target info is still refreshed") val sentAtStart = transport.methodsSentAt(0) assertEquals(setOf("Runtime.evaluate", "Target.getTargetInfo"), sentAtStart) - assertEquals(listOf("DOM.describeNode"), transport.sent.filter { it.atMillis > 0 }.map { it.method }) + assertEquals( + listOf("DOM.describeNode", "Runtime.releaseObjectGroup"), + transport.sent.filter { it.atMillis > 0 }.map { it.method }, + ) assertEquals(200, testScheduler.currentTime, "two round trips (refresh ∥ evaluation, then describe), not three") tab.close() } diff --git a/docs/home/quickstart.md b/docs/home/quickstart.md index 3b3e31837..b74e33012 100644 --- a/docs/home/quickstart.md +++ b/docs/home/quickstart.md @@ -199,10 +199,10 @@ the page is large or keeps changing. | What | How | | --- | --- | -| Commands for `select` / `querySelector` | `Runtime.evaluate`, then `DOM.describeNode` of the match (one round trip when nothing matches) | +| Commands for `select` / `querySelector` | `Runtime.evaluate`, then `DOM.describeNode` of the match with the release of the object the lookup created (one round trip when nothing matches) | | Commands for `selectAll` / `querySelectorAll` | one `Runtime.evaluate` when nothing matches; otherwise also `Runtime.getProperties`, then every `DOM.describeNode` sent together, with the release of the objects the lookup created | | Data received | the matches and their subtrees; when they would hold more elements than the whole document (nested matches, a selector matching most of the page), the document is read instead, as before | -| First call on a found element (`click`, `apply`, …) | `select` / `querySelector`: uses the object the page returned, no `DOM.resolveNode`; `selectAll` / `querySelectorAll`: resolves the node first, as before | +| First call on a found element (`click`, `apply`, …) | resolves the node first (`DOM.resolveNode`), as before: a lookup leaves no object behind in the page | | Text, attributes, children, `backendNodeId` | read from the match and its subtree, as before | | `element.node.nodeId`, `element.parentId`, `element.tree`, `element.parent` | 0, `null`, `null`, and `parent` throws, until `element.update()` reads the document; a lookup under the element does it by itself | | Shadow roots, iframes | not searched (`selectAll(includeFrames = true)` reads the document to search inside each iframe, as before) | @@ -213,7 +213,7 @@ the page is large or keeps changing. ```kotlin val item = tab.select("li.item") item.text // read from the match -item.click() // no extra command to resolve the element +item.click() // resolves the element, then clicks it item.tree // null: no document was read item.update() // reads the document (one DOM.getDocument) item.parent?.tag // "ul" @@ -222,8 +222,6 @@ item.parent?.tag // "ul" What still differs from reading the whole document: - the page's own `document.querySelector` runs, so a page that replaces it changes the result; -- the element found by `select` or `querySelector` holds the remote object of its match until the - page navigates (an element read from the document held one only after its first call); - until something reads the document (`find`, `update`, a lookup under an element…), the browser sends no `DOM.*` mutation events for the page, so a busy page may count as idle sooner, and the DOM agent is not enabled: a `tab.dom.disable()` sent by hand then fails, as on a tab that never read it; From 4207cc16e4e34a69dfd446ba1d16b6e9d87ba655 Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Fri, 20 Nov 2026 19:19:23 +0100 Subject: [PATCH 11/16] feat: elements found in the page fill their node ids, tree and parent on first read The node and tree of an element found by a lookup the page ran are filled on their first read from the document the tab keeps from an earlier read, while the page has not changed since, with no command: node ids, tree, parentId and parent are then those a lookup on the document gave. Without such a document the element stays as found until update() or a lookup under it. --- .../dev/kdriver/core/dom/DefaultElement.kt | 54 ++++++++++++++++- .../kotlin/dev/kdriver/core/tab/DefaultTab.kt | 10 +++- .../kotlin/dev/kdriver/core/tab/Tab.kt | 15 +++-- .../core/tab/LookupsInPageBehaviourTest.kt | 15 +++++ .../dev/kdriver/core/tab/LookupsInPageTest.kt | 59 +++++++++++++++++++ docs/home/quickstart.md | 12 ++-- 6 files changed, 152 insertions(+), 13 deletions(-) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt b/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt index e9183f5c3..f068c2358 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt @@ -19,12 +19,59 @@ import kotlin.random.Random */ open class DefaultElement( val tab: Tab, - override var node: DOM.Node, - override var tree: DOM.Node? = null, + node: DOM.Node, + tree: DOM.Node? = null, ) : Element { private val logger = KtorSimpleLogger("Element") + private var currentNode: DOM.Node = node + private var currentTree: DOM.Node? = tree + + // The document epoch the last binding attempt looked at (see [bindFromKeptDocument]). + private var bindingCheckedAt: Long = NOT_CHECKED + + /** + * The node of this element. For an element found in the page (no node id, no [tree]), the first read after the + * document was read, while the page has not changed since, takes the document's node of the same backend node id, + * with its node ids, as a lookup on the document gave it. + */ + override var node: DOM.Node + get() { + bindFromKeptDocument() + return currentNode + } + set(value) { + currentNode = value + bindingCheckedAt = NOT_CHECKED + } + + /** The document this element was read from: for an element found in the page, filled as [node] is. */ + override var tree: DOM.Node? + get() { + bindFromKeptDocument() + return currentTree + } + set(value) { + currentTree = value + bindingCheckedAt = NOT_CHECKED + } + + /** + * Binds an element found in the page to the document [DefaultTab] keeps from its last read, when it still matches + * the page, without any command: node ids, [tree] and [parent] are then those a lookup on the document gave. Each + * kept document is looked at once; without one, the element stays as found until [update] or a lookup under it. + */ + private fun bindFromKeptDocument() { + if (currentTree != null || currentNode.nodeId != 0) return + val (doc, epoch) = (tab as? DefaultTab)?.keptDocument() ?: return + if (epoch == bindingCheckedAt) return + bindingCheckedAt = epoch + val documentNode = doc.filterRecurse { it.backendNodeId == currentNode.backendNodeId } ?: return + currentNode = documentNode + currentTree = doc + } + private var remoteObject: Runtime.RemoteObject? = null // The node the cached [remoteObject] was resolved for: [rawApply] reuses the object only while [node] is still @@ -813,6 +860,9 @@ open class DefaultElement( // No node resolved yet: backend node ids are positive. const val NO_NODE = Int.MIN_VALUE + // No kept document looked at yet: epochs are never negative. + const val NOT_CHECKED = -1L + // Human-like pauses, in milliseconds (lower bound inclusive, upper bound exclusive). const val TRAJECTORY_STEP_DELAY_MIN = 8L const val TRAJECTORY_STEP_DELAY_MAX = 25L diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt index cdb2203bf..ed41caeb7 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt @@ -751,10 +751,18 @@ open class DefaultTab( * @return the root of the document, and whether it is the copy kept from an earlier read. */ internal suspend fun currentDocument(): Pair { - documentSnapshot?.takeIf { it.epoch == documentEpoch }?.let { return it.root to true } + keptDocument()?.let { return it.first to true } return readDocument() to false } + /** + * The document kept from an earlier read while it still matches the page, with the [documentEpoch] it matches, + * without reading anything: null when there is none. The properties of an element found in the page take their + * node ids and tree from it on their first read ([DefaultElement.node], [DefaultElement.tree]). + */ + internal fun keptDocument(): Pair? = + documentSnapshot?.takeIf { it.epoch == documentEpoch }?.let { it.root to it.epoch } + private suspend fun readDocument(): DOM.Node { val before = documentEpoch val root = dom.getDocument(-1, true).root diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt b/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt index 91484d709..0030f0232 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt @@ -294,7 +294,7 @@ interface Tab : Connection { * * This method waits for the element to appear in the DOM, retrying every 500 milliseconds until the timeout is reached. * - * The page runs the selector, and the element has no node id nor tree until [Element.update]: see + * The page runs the selector, and the element's node ids and tree are filled on demand: see * [querySelector] for how lookups work. * * @param selector The CSS selector of the element to select. @@ -332,7 +332,7 @@ interface Tab : Connection { * * Can also be used to wait for such elements to appear. Optionally includes results from iframes. * - * The page runs the selector, and the elements have no node id nor tree until [Element.update]: see + * The page runs the selector, and the elements' node ids and tree are filled on demand: see * [querySelector] for how lookups work. With [includeFrames], `selectAll` reads the whole document instead * (searching inside the frames needs it), for the page's own matches too: they then have a node id and a tree. * @@ -414,10 +414,13 @@ interface Tab : Connection { * - has its node and subtree: [Element.tag], [Element.text], [Element.textAll], attributes, * [Element.children] and [Element.backendNodeId] read as from a document; * - keeps no object of the page: its first call (`click`, `apply`, …) resolves its node, as before; - * - has no node id yet: `node.nodeId` and the node ids of its subtree are 0, [Element.parentId] and - * [Element.tree] are null and [Element.parent] throws, until [Element.update] reads the document, which also - * binds it. A lookup under the element ([Element.querySelector], or a [NodeOrElement] passed back here) binds it - * first by itself. These are plain properties, so the first read of one cannot fetch the document on its own. + * - gets its node ids and tree on demand: the first read of `node`, [Element.tree], [Element.parentId] or + * [Element.parent] takes them from the document kept by an earlier read ([find], [xpath], a lookup under an + * element, [Element.update]…) while the page has not changed since, with no command; a lookup under the element + * ([Element.querySelector], or a [NodeOrElement] passed back here) binds it first by itself. These are plain + * properties, so their read cannot fetch the document on its own: without such a document, `node.nodeId` and + * the node ids of its subtree are 0, [Element.parentId] and [Element.tree] are null and [Element.parent] throws, + * until [Element.update] reads the document. * * What else differs from reading the document: * - the page's own `document.querySelector` runs: a page that replaces it changes the result; diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt index ce0294be8..e8a290ace 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt @@ -157,6 +157,21 @@ class LookupsInPageBehaviourTest { assertEquals("ul", item.parent?.tag) } + @Test + fun anElementFoundInThePage_fillsItsNodeIdsTreeAndParent_onFirstRead_onceTheDocumentWasRead() = onPage { + selectAll("p.inner", timeout = 5_000, includeFrames = true) // the frame loaded: the read below stays current + val (tree, _) = (this as DefaultTab).currentDocument() + val onTheSameRead = querySelector("li[data-rank='3']", NodeOrElement.WrappedNode(tree))!! + + val item = select("li[data-rank='3']", timeout = 5_000) + + assertEquals(onTheSameRead.node, item.node, "node, subtree and node ids of the document read") + assertEquals(tree, item.tree) + assertEquals(onTheSameRead.parentId, item.parentId) + assertEquals("ul", item.parent?.tag) + assertEquals(item.node.nodeId, dom.querySelector(tree.nodeId, "li[data-rank='3']").nodeId, "a live node id") + } + @Test fun update_givesTheNodeIdsTreeAndParent_theDocumentLookupGives() = onPage { selectAll("p.inner", timeout = 5_000, includeFrames = true) // the frame loaded: both reads see the same page diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt index aea6df6aa..358c48005 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt @@ -18,6 +18,7 @@ import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest import kotlin.test.Test import kotlin.test.assertEquals @@ -705,6 +706,64 @@ class LookupsInPageTest { tab.close() } + @Test + fun anElementFoundInThePage_fillsItsNodeIdsTreeAndParent_onFirstRead_fromAKeptDocument() = + runTest(StandardTestDispatcher()) { + val tab = listTab() + val before = tab.onTheDocument("li.item") + val item = tab.select("li.item", timeout = 1_000) + val sentBefore = tab.sent.size + + assertEquals(before.node, item.node) + assertEquals(7, item.node.nodeId) + assertEquals(5, item.parentId) + assertEquals(before.tree, item.tree) + assertEquals("ul", item.parent!!.tag) + assertEquals(listOf(8), item.children.map { it.node.nodeId }) + assertEquals(sentBefore, tab.sent.size, "filled from the kept document, with no command") + assertEquals(1, tab.sent.count { it == "DOM.getDocument" }) + tab.close() + } + + @Test + fun anElementFoundInThePage_isNotFilledFromADocumentThePageChangedSince() = runTest(StandardTestDispatcher()) { + val tab = listTab() + tab.onTheDocument("li.item") + tab.transport.event("DOM.attributeModified", """{"nodeId":7,"name":"class","value":"busy"}""") + runCurrent() + + val item = tab.select("li.item", timeout = 1_000) + + assertEquals(0, item.node.nodeId) + assertNull(item.tree) + item.update() + assertEquals(7, item.node.nodeId, "update() still reads the document") + assertEquals(2, tab.sent.count { it == "DOM.getDocument" }) + tab.close() + } + + @Test + fun anElementFoundInThePage_whoseNodeTheKeptDocumentLacks_staysAsFound() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-1")) + "DOM.describeNode" -> Reply.ok(item(30, "Gone")) + "DOM.getDocument" -> Reply.ok(list) + "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) + else -> Reply.ok() + } + } + tab.currentDocument() + val gone = tab.select("li", timeout = 1_000) + + assertEquals(0, gone.node.nodeId) + assertNull(gone.tree) + assertEquals("Gone", gone.text) + gone.node = gone.node.copy(nodeName = "P") + assertEquals("p", gone.tag, "a node set by hand is kept") + tab.close() + } + @Test fun aBareNodeFoundInThePage_isReplacedByTheDocumentNode_forALookupUnderIt() = runTest(StandardTestDispatcher()) { val tab = listTab() diff --git a/docs/home/quickstart.md b/docs/home/quickstart.md index b74e33012..84c21fa47 100644 --- a/docs/home/quickstart.md +++ b/docs/home/quickstart.md @@ -204,7 +204,7 @@ the page is large or keeps changing. | Data received | the matches and their subtrees; when they would hold more elements than the whole document (nested matches, a selector matching most of the page), the document is read instead, as before | | First call on a found element (`click`, `apply`, …) | resolves the node first (`DOM.resolveNode`), as before: a lookup leaves no object behind in the page | | Text, attributes, children, `backendNodeId` | read from the match and its subtree, as before | -| `element.node.nodeId`, `element.parentId`, `element.tree`, `element.parent` | 0, `null`, `null`, and `parent` throws, until `element.update()` reads the document; a lookup under the element does it by itself | +| `element.node.nodeId`, `element.parentId`, `element.tree`, `element.parent` | filled on their first read from the document kept by an earlier read (`find`, `xpath`, a lookup under an element, `update`…) while the page has not changed since; otherwise 0, `null`, `null`, and `parent` throws, until `element.update()` reads the document; a lookup under the element binds it by itself | | Shadow roots, iframes | not searched (`selectAll(includeFrames = true)` reads the document to search inside each iframe, as before) | | Waiting | `select` / `selectAll` retry every 500 ms until the timeout, as before | | A navigation during the lookup | an object or context dropped by the navigation counts as no match: `select` tries again | @@ -214,9 +214,12 @@ the page is large or keeps changing. val item = tab.select("li.item") item.text // read from the match item.click() // resolves the element, then clicks it -item.tree // null: no document was read +item.tree // null: no document was read yet item.update() // reads the document (one DOM.getDocument) item.parent?.tag // "ul" + +val other = tab.select("li.other") +other.parent?.tag // "ul": the document read above still matches the page, no command sent ``` What still differs from reading the whole document: @@ -226,8 +229,9 @@ What still differs from reading the whole document: sends no `DOM.*` mutation events for the page, so a busy page may count as idle sooner, and the DOM agent is not enabled: a `tab.dom.disable()` sent by hand then fails, as on a tab that never read it; - `element.node.nodeId`, `element.parentId`, `element.tree` and `element.parent` are plain - properties: their first read cannot fetch the document by itself, so code that reads them calls - `element.update()` first. + properties, not suspend functions: their first read fills them from a document kept by an earlier + read, but cannot fetch one by itself. When no document was read since the page last changed, code + that reads them calls `element.update()` first. Lookups under an element (`element.querySelector`, `element.querySelectorAll`), `find`, `findAll` and `xpath` read the document, as before. From c8630424d90625409d845945a0129497ca6a446f Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Fri, 20 Nov 2026 19:25:18 +0100 Subject: [PATCH 12/16] test: set the node of a found element through DefaultElement --- .../jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt index 358c48005..da5834b16 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt @@ -6,6 +6,7 @@ import dev.kdriver.cdp.CDPException import dev.kdriver.core.ScriptedTab import dev.kdriver.core.ScriptedTransport import dev.kdriver.core.ScriptedTransport.Reply +import dev.kdriver.core.dom.DefaultElement import dev.kdriver.core.dom.Element import dev.kdriver.core.dom.NodeOrElement import dev.kdriver.core.exceptions.EvaluateException @@ -759,7 +760,7 @@ class LookupsInPageTest { assertEquals(0, gone.node.nodeId) assertNull(gone.tree) assertEquals("Gone", gone.text) - gone.node = gone.node.copy(nodeName = "P") + (gone as DefaultElement).node = gone.node.copy(nodeName = "P") assertEquals("p", gone.tag, "a node set by hand is kept") tab.close() } From 80e26dd6bc3ed1d2d70df0887487c73a862e02f2 Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Fri, 20 Nov 2026 19:49:00 +0100 Subject: [PATCH 13/16] fix: bind a found element only to an identical document node, and release an evaluation cut in flight - A found element takes the kept document's node on its first read only when that node holds the same subtree, ids aside, so a read elsewhere never changes what the element shows; it binds even when the description already carries node ids (the browser gives them once the document was read). The document's nodes are indexed once per read. - The object group of a lookup counts as holding objects from the moment the evaluation is sent: one cancelled or timed out in flight is released too; a lookup that finds nothing still sends no release. --- .../dev/kdriver/core/dom/DefaultElement.kt | 26 ++++--- .../kotlin/dev/kdriver/core/dom/Extensions.kt | 15 +++++ .../kotlin/dev/kdriver/core/tab/DefaultTab.kt | 67 +++++++++++++++---- .../dev/kdriver/core/tab/LookupsInPageTest.kt | 39 +++++++++++ 4 files changed, 122 insertions(+), 25 deletions(-) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt b/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt index f068c2358..31951659d 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt @@ -32,9 +32,9 @@ open class DefaultElement( private var bindingCheckedAt: Long = NOT_CHECKED /** - * The node of this element. For an element found in the page (no node id, no [tree]), the first read after the - * document was read, while the page has not changed since, takes the document's node of the same backend node id, - * with its node ids, as a lookup on the document gave it. + * The node of this element. For an element found in the page (no [tree]), the first read after the document was + * read, while the page has not changed since, takes the document's node of the same backend node id, with its node + * ids and parent id, as a lookup on the document gave it, when it holds the same subtree. */ override var node: DOM.Node get() { @@ -59,17 +59,21 @@ open class DefaultElement( /** * Binds an element found in the page to the document [DefaultTab] keeps from its last read, when it still matches - * the page, without any command: node ids, [tree] and [parent] are then those a lookup on the document gave. Each - * kept document is looked at once; without one, the element stays as found until [update] or a lookup under it. + * the page, without any command: node ids, [tree] and [parent] are then those a lookup on the document gave. The + * document's node is taken only when it holds the same subtree as the one found (ids aside), so a read never + * changes what the element shows. Each kept document is looked at once; without one, the element stays as found + * until [update] or a lookup under it. */ private fun bindFromKeptDocument() { - if (currentTree != null || currentNode.nodeId != 0) return - val (doc, epoch) = (tab as? DefaultTab)?.keptDocument() ?: return - if (epoch == bindingCheckedAt) return - bindingCheckedAt = epoch - val documentNode = doc.filterRecurse { it.backendNodeId == currentNode.backendNodeId } ?: return + if (currentTree != null) return + val kept = (tab as? DefaultTab)?.keptDocument() ?: return + if (kept.epoch == bindingCheckedAt) return + bindingCheckedAt = kept.epoch + val found = currentNode + val documentNode = kept.nodeOf(found.backendNodeId) ?: return + if (documentNode.withoutIds() != found.withoutIds()) return + currentTree = kept.root currentNode = documentNode - currentTree = doc } private var remoteObject: Runtime.RemoteObject? = null diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/dom/Extensions.kt b/core/src/commonMain/kotlin/dev/kdriver/core/dom/Extensions.kt index 4784eb872..dde375da6 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/dom/Extensions.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/dom/Extensions.kt @@ -91,3 +91,18 @@ val Input.MouseButton.buttonsMask: Int Input.MouseButton.FORWARD -> 16 Input.MouseButton.NONE -> 0 } + +/** + * This node and its subtree without their node ids and parent ids: two reads of the same unchanged nodes, one by + * `DOM.describeNode` and one by `DOM.getDocument`, are then equal. + */ +internal fun DOM.Node.withoutIds(): DOM.Node = copy( + nodeId = 0, + parentId = null, + children = children?.map { it.withoutIds() }, + contentDocument = contentDocument?.withoutIds(), + shadowRoots = shadowRoots?.map { it.withoutIds() }, + pseudoElements = pseudoElements?.map { it.withoutIds() }, + templateContent = templateContent?.withoutIds(), + importedDocument = importedDocument?.withoutIds(), +) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt index ed41caeb7..315082506 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt @@ -413,7 +413,8 @@ open class DefaultTab( val items = mutableListOf() if (includeFrames) { // Searching inside the frames reads the document (Element.querySelectorAll), so the whole lookup goes - // through it: the frames and the page's own matches come from one read. + // through it, as before: the frames and the page's own matches share the kept read while the page + // does not change. for (fr in querySelectorAllInDocument("iframe")) items.addAll(fr.querySelectorAll(trimmedSelector)) items.addAll(querySelectorAllInDocument(trimmedSelector)) } else { @@ -473,7 +474,8 @@ open class DefaultTab( * own size. The script uses no global of the page but `document.querySelectorAll` and `getElementsByTagName`. */ private suspend fun querySelectorAllInPage(selector: String): List = inLookupGroup { group -> - val found = evaluateLookup( + val found = evaluateInGroup( + group, "(() => { const all = document.querySelectorAll(${jsStringLiteral(selector)});" + " if (!all.length) return null;" + " const most = document.getElementsByTagName('*').length; const matches = []; let described = 0;" + @@ -482,10 +484,8 @@ open class DefaultTab( " if (described > most) return 'document'; matches[i] = all[i]; }" + " return matches; })()", protocolMethod = "DOM.querySelectorAll", - objectGroup = group.name, ) ?: return@inLookupGroup emptyList() val arrayId = found.objectId ?: return@inLookupGroup querySelectorAllInDocument(selector) - group.holdsObjects = true val properties = unlessGone { runtime.getProperties(objectId = arrayId, ownProperties = true) } ?: return@inLookupGroup emptyList() val matches = properties.result @@ -501,12 +501,11 @@ open class DefaultTab( * release of the object, sent together), one otherwise. */ private suspend fun querySelectorInPage(selector: String): Element? = inLookupGroup { group -> - val match = evaluateLookup( + val match = evaluateInGroup( + group, "document.querySelector(${jsStringLiteral(selector)})", protocolMethod = "DOM.querySelector", - objectGroup = group.name, )?.objectId ?: return@inLookupGroup null - group.holdsObjects = true describeAndRelease(group, listOf(match))?.single()?.let { DefaultElement(this, it) } } @@ -546,6 +545,30 @@ open class DefaultTab( } } + /** + * [evaluateLookup] with the objects it creates in [group]. The group counts as holding objects from the moment the + * evaluation is sent, so that one cut while in flight (cancelled, timed out, connection lost), which the page may + * still run, is released all the same; once the page answered, only when it returned an object. + */ + private suspend fun evaluateInGroup( + group: LookupGroup, + expression: String, + protocolMethod: String, + ): Runtime.RemoteObject? { + group.holdsObjects = true + val found = try { + evaluateLookup(expression, protocolMethod, objectGroup = group.name) + } catch (e: CDPException) { + group.holdsObjects = false // answered with an error: nothing was created + throw e + } catch (e: EvaluateException) { + group.holdsObjects = false // the script threw: nothing was returned + throw e + } + group.holdsObjects = found?.objectId != null + return found + } + /** * Describes [objectIds] with their subtrees (`DOM.describeNode`, depth -1, piercing), then releases [group]: the * descriptions and the release are sent one after the other, so the browser runs them in that order, in one round @@ -736,7 +759,24 @@ open class DefaultTab( * The last whole document read for a lookup (`DOM.getDocument(depth = -1, pierce = true)`), and the * [documentEpoch] it still matches the page at. */ - private class DocumentSnapshot(val root: DOM.Node, val epoch: Long) + internal class DocumentSnapshot(val root: DOM.Node, val epoch: Long) { + + private val byBackendNodeId: Map by lazy { + buildMap { + fun index(node: DOM.Node) { + for (child in node.children.orEmpty()) { + if (child.backendNodeId !in this) put(child.backendNodeId, child) + child.shadowRoots?.firstOrNull()?.let { index(it) } + index(child) + } + } + index(root) + } + } + + /** The node of [backendNodeId] in this document, as `root.filterRecurse` finds it, from an index built once. */ + fun nodeOf(backendNodeId: Int): DOM.Node? = byBackendNodeId[backendNodeId] + } @Volatile private var documentSnapshot: DocumentSnapshot? = null @@ -751,17 +791,16 @@ open class DefaultTab( * @return the root of the document, and whether it is the copy kept from an earlier read. */ internal suspend fun currentDocument(): Pair { - keptDocument()?.let { return it.first to true } + keptDocument()?.let { return it.root to true } return readDocument() to false } /** - * The document kept from an earlier read while it still matches the page, with the [documentEpoch] it matches, - * without reading anything: null when there is none. The properties of an element found in the page take their - * node ids and tree from it on their first read ([DefaultElement.node], [DefaultElement.tree]). + * The document kept from an earlier read while it still matches the page, without reading anything: null when + * there is none. The properties of an element found in the page take their node ids and tree from it on their + * first read ([DefaultElement.node], [DefaultElement.tree]). */ - internal fun keptDocument(): Pair? = - documentSnapshot?.takeIf { it.epoch == documentEpoch }?.let { it.root to it.epoch } + internal fun keptDocument(): DocumentSnapshot? = documentSnapshot?.takeIf { it.epoch == documentEpoch } private suspend fun readDocument(): DOM.Node { val before = documentEpoch diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt index da5834b16..c18a78e32 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt @@ -496,6 +496,45 @@ class LookupsInPageTest { tab.close() } + @Test + fun aLookupCancelledWhileThePageEvaluates_stillReleasesItsObjects() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-1"), latency = 1_000) + else -> Reply.ok() + } + } + + val lookup = launch { tab.querySelector("#go") } + advanceTimeBy(100) + lookup.cancel() + advanceUntilIdle() + + assertTrue(lookup.isCancelled) + assertEquals( + tab.transport.sent.single { it.method == "Runtime.evaluate" }.param("objectGroup"), + tab.transport.sent.single { it.method == "Runtime.releaseObjectGroup" }.param("objectGroup"), + "the page may still run an evaluation cut in flight", + ) + tab.close() + } + + @Test + fun aLookupThatFindsNothing_sendsNoRelease() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(nothing) + else -> Reply.ok() + } + } + + assertNull(tab.querySelector("#go")) + assertEquals(emptyList(), tab.querySelectorAll("#go")) + + assertTrue("Runtime.releaseObjectGroup" !in tab.sent) + tab.close() + } + @Test fun anyOtherProtocolError_isThrown() = runTest(StandardTestDispatcher()) { val describing = tab { From 52c3be63e8703ac201f027dbb15b7750a169f832 Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Fri, 20 Nov 2026 19:49:10 +0100 Subject: [PATCH 14/16] docs: node ids of a found element may be 0 until it is bound --- core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt | 5 +++-- docs/home/quickstart.md | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt b/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt index 0030f0232..ca8cd4cf1 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/tab/Tab.kt @@ -419,8 +419,9 @@ interface Tab : Connection { * element, [Element.update]…) while the page has not changed since, with no command; a lookup under the element * ([Element.querySelector], or a [NodeOrElement] passed back here) binds it first by itself. These are plain * properties, so their read cannot fetch the document on its own: without such a document, `node.nodeId` and - * the node ids of its subtree are 0, [Element.parentId] and [Element.tree] are null and [Element.parent] throws, - * until [Element.update] reads the document. + * the node ids of its subtree may be 0, [Element.parentId] and [Element.tree] are null and [Element.parent] + * throws, until [Element.update] reads the document. The document's node is taken only when it holds the same + * subtree as the one found, so a read elsewhere never changes what the element shows. * * What else differs from reading the document: * - the page's own `document.querySelector` runs: a page that replaces it changes the result; diff --git a/docs/home/quickstart.md b/docs/home/quickstart.md index 84c21fa47..ed97ea058 100644 --- a/docs/home/quickstart.md +++ b/docs/home/quickstart.md @@ -204,7 +204,7 @@ the page is large or keeps changing. | Data received | the matches and their subtrees; when they would hold more elements than the whole document (nested matches, a selector matching most of the page), the document is read instead, as before | | First call on a found element (`click`, `apply`, …) | resolves the node first (`DOM.resolveNode`), as before: a lookup leaves no object behind in the page | | Text, attributes, children, `backendNodeId` | read from the match and its subtree, as before | -| `element.node.nodeId`, `element.parentId`, `element.tree`, `element.parent` | filled on their first read from the document kept by an earlier read (`find`, `xpath`, a lookup under an element, `update`…) while the page has not changed since; otherwise 0, `null`, `null`, and `parent` throws, until `element.update()` reads the document; a lookup under the element binds it by itself | +| `element.node.nodeId`, `element.parentId`, `element.tree`, `element.parent` | filled on their first read from the document kept by an earlier read (`find`, `xpath`, a lookup under an element, `update`…) while the page has not changed since; otherwise `nodeId` may be 0, `parentId` and `tree` are `null` and `parent` throws, until `element.update()` reads the document; a lookup under the element binds it by itself | | Shadow roots, iframes | not searched (`selectAll(includeFrames = true)` reads the document to search inside each iframe, as before) | | Waiting | `select` / `selectAll` retry every 500 ms until the timeout, as before | | A navigation during the lookup | an object or context dropped by the navigation counts as no match: `select` tries again | From 5297b131034fca934cba0a9c0c1c31729cfa4343 Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Fri, 20 Nov 2026 20:04:23 +0100 Subject: [PATCH 15/16] test: compare lookups on a page that finished loading --- .../dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt index e8a290ace..506c667ed 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBehaviourTest.kt @@ -31,7 +31,10 @@ class LookupsInPageBehaviourTest { private fun onPage(block: suspend Tab.() -> Unit) = runBlocking { val browser: Browser = createBrowser(this as CoroutineScope, headless = true, sandbox = false) try { - browser.get(sampleFile("lookup-test.html")).block() + browser.get(sampleFile("lookup-test.html")).apply { + // Both reads compared below must see the whole page: wait for it to be parsed and loaded first. + waitForReadyState(ReadyState.COMPLETE) + }.block() } finally { browser.stop() } From 1b941584657ca21ac3649299079bbaa445628215 Mon Sep 17 00:00:00 2001 From: NathanFallet Date: Sat, 21 Nov 2026 16:31:10 +0100 Subject: [PATCH 16/16] refactor: split the lookup code to pass the detekt checks Move the binding of an element to the kept document into ElementBinding, the stable coordinates script into its own file, the cleanup of a lookup group into a function of its own, and split the lookups in the page tests in two classes sharing their fixtures. No behaviour change. Co-Authored-By: Claude Sonnet 5.5 --- .../dev/kdriver/core/dom/DefaultElement.kt | 104 +----- .../dev/kdriver/core/dom/ElementBinding.kt | 52 +++ .../core/dom/StableCoordinatesScript.kt | 59 +++ .../kotlin/dev/kdriver/core/tab/DefaultTab.kt | 35 +- .../core/tab/LookupsInPageBindingTest.kt | 338 +++++++++++++++++ .../kdriver/core/tab/LookupsInPageFixtures.kt | 67 ++++ .../dev/kdriver/core/tab/LookupsInPageTest.kt | 340 +----------------- 7 files changed, 546 insertions(+), 449 deletions(-) create mode 100644 core/src/commonMain/kotlin/dev/kdriver/core/dom/ElementBinding.kt create mode 100644 core/src/commonMain/kotlin/dev/kdriver/core/dom/StableCoordinatesScript.kt create mode 100644 core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBindingTest.kt create mode 100644 core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageFixtures.kt diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt b/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt index 31951659d..463507635 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt @@ -25,56 +25,21 @@ open class DefaultElement( private val logger = KtorSimpleLogger("Element") - private var currentNode: DOM.Node = node - private var currentTree: DOM.Node? = tree - - // The document epoch the last binding attempt looked at (see [bindFromKeptDocument]). - private var bindingCheckedAt: Long = NOT_CHECKED + private val binding = ElementBinding(node, tree) /** * The node of this element. For an element found in the page (no [tree]), the first read after the document was * read, while the page has not changed since, takes the document's node of the same backend node id, with its node - * ids and parent id, as a lookup on the document gave it, when it holds the same subtree. + * ids and parent id, as a lookup on the document gave it, when it holds the same subtree (see [ElementBinding]). */ override var node: DOM.Node - get() { - bindFromKeptDocument() - return currentNode - } - set(value) { - currentNode = value - bindingCheckedAt = NOT_CHECKED - } + get() = binding.bindFrom((tab as? DefaultTab)?.keptDocument()).node + set(value) = binding.replaceNode(value) /** The document this element was read from: for an element found in the page, filled as [node] is. */ override var tree: DOM.Node? - get() { - bindFromKeptDocument() - return currentTree - } - set(value) { - currentTree = value - bindingCheckedAt = NOT_CHECKED - } - - /** - * Binds an element found in the page to the document [DefaultTab] keeps from its last read, when it still matches - * the page, without any command: node ids, [tree] and [parent] are then those a lookup on the document gave. The - * document's node is taken only when it holds the same subtree as the one found (ids aside), so a read never - * changes what the element shows. Each kept document is looked at once; without one, the element stays as found - * until [update] or a lookup under it. - */ - private fun bindFromKeptDocument() { - if (currentTree != null) return - val kept = (tab as? DefaultTab)?.keptDocument() ?: return - if (kept.epoch == bindingCheckedAt) return - bindingCheckedAt = kept.epoch - val found = currentNode - val documentNode = kept.nodeOf(found.backendNodeId) ?: return - if (documentNode.withoutIds() != found.withoutIds()) return - currentTree = kept.root - currentNode = documentNode - } + get() = binding.bindFrom((tab as? DefaultTab)?.keptDocument()).tree + set(value) = binding.replaceTree(value) private var remoteObject: Runtime.RemoteObject? = null @@ -220,59 +185,7 @@ open class DefaultElement( private suspend fun getStableCoordinates(): CoordinateResult? { return try { apply( - jsFunction = """ - function() { - if (!this || !this.isConnected) return null; - - return new Promise(resolve => { - let lastTop = null; - let lastLeft = null; - let stableFrames = 0; - const maxAttempts = 10; - let attempts = 0; - - const checkStable = () => { - attempts++; - const rect = this.getBoundingClientRect(); - - if (rect.width === 0 || rect.height === 0) { - resolve(null); - return; - } - - if (lastTop !== null && - Math.abs(rect.top - lastTop) < 1 && - Math.abs(rect.left - lastLeft) < 1) { - stableFrames++; - if (stableFrames >= 2) { - resolve({ - x: rect.left + rect.width / 2, - y: rect.top + rect.height / 2 - }); - return; - } - } else { - stableFrames = 0; - } - - lastTop = rect.top; - lastLeft = rect.left; - - if (attempts < maxAttempts) { - requestAnimationFrame(checkStable); - } else { - // Timeout: use current position - resolve({ - x: rect.left + rect.width / 2, - y: rect.top + rect.height / 2 - }); - } - }; - - requestAnimationFrame(checkStable); - }); - } - """.trimIndent(), + jsFunction = STABLE_COORDINATES_JS, awaitPromise = true ) } catch (e: EvaluateException) { @@ -864,9 +777,6 @@ open class DefaultElement( // No node resolved yet: backend node ids are positive. const val NO_NODE = Int.MIN_VALUE - // No kept document looked at yet: epochs are never negative. - const val NOT_CHECKED = -1L - // Human-like pauses, in milliseconds (lower bound inclusive, upper bound exclusive). const val TRAJECTORY_STEP_DELAY_MIN = 8L const val TRAJECTORY_STEP_DELAY_MAX = 25L diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/dom/ElementBinding.kt b/core/src/commonMain/kotlin/dev/kdriver/core/dom/ElementBinding.kt new file mode 100644 index 000000000..401add9ef --- /dev/null +++ b/core/src/commonMain/kotlin/dev/kdriver/core/dom/ElementBinding.kt @@ -0,0 +1,52 @@ +package dev.kdriver.core.dom + +import dev.kdriver.cdp.domain.DOM +import dev.kdriver.core.tab.DefaultTab + +/** + * The node and the document of a [DefaultElement], and the binding of an element found in the page to the document + * [DefaultTab] keeps from its last read, when it still matches the page, without any command: node ids, [tree] and + * parent are then those a lookup on the document gave. The document's node is taken only when it holds the same + * subtree as the one found (ids aside), so a read never changes what the element shows. Each kept document is looked + * at once; without one, the element stays as found until `update` or a lookup under it. + */ +internal class ElementBinding(node: DOM.Node, tree: DOM.Node?) { + + var node: DOM.Node = node + private set + + var tree: DOM.Node? = tree + private set + + // The epoch of the kept document the last binding attempt looked at. + private var checkedAt: Long = NOT_CHECKED + + fun replaceNode(value: DOM.Node) { + node = value + checkedAt = NOT_CHECKED + } + + fun replaceTree(value: DOM.Node?) { + tree = value + checkedAt = NOT_CHECKED + } + + /** Binds to [kept] when this element has no tree yet and [kept] was not looked at; returns this binding. */ + fun bindFrom(kept: DefaultTab.DocumentSnapshot?): ElementBinding { + if (tree == null && kept != null && kept.epoch != checkedAt) { + checkedAt = kept.epoch + val found = node + val documentNode = kept.nodeOf(found.backendNodeId) + if (documentNode != null && documentNode.withoutIds() == found.withoutIds()) { + tree = kept.root + node = documentNode + } + } + return this + } + + private companion object { + // No kept document looked at yet: epochs are never negative. + const val NOT_CHECKED = -1L + } +} diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/dom/StableCoordinatesScript.kt b/core/src/commonMain/kotlin/dev/kdriver/core/dom/StableCoordinatesScript.kt new file mode 100644 index 000000000..c5490da28 --- /dev/null +++ b/core/src/commonMain/kotlin/dev/kdriver/core/dom/StableCoordinatesScript.kt @@ -0,0 +1,59 @@ +package dev.kdriver.core.dom + +/** + * The function [DefaultElement] applies to an element to read its coordinates once its position is stable across + * several frames; it resolves null when the element is detached or has no size. + */ +internal val STABLE_COORDINATES_JS = """ + function() { + if (!this || !this.isConnected) return null; + + return new Promise(resolve => { + let lastTop = null; + let lastLeft = null; + let stableFrames = 0; + const maxAttempts = 10; + let attempts = 0; + + const checkStable = () => { + attempts++; + const rect = this.getBoundingClientRect(); + + if (rect.width === 0 || rect.height === 0) { + resolve(null); + return; + } + + if (lastTop !== null && + Math.abs(rect.top - lastTop) < 1 && + Math.abs(rect.left - lastLeft) < 1) { + stableFrames++; + if (stableFrames >= 2) { + resolve({ + x: rect.left + rect.width / 2, + y: rect.top + rect.height / 2 + }); + return; + } + } else { + stableFrames = 0; + } + + lastTop = rect.top; + lastLeft = rect.left; + + if (attempts < maxAttempts) { + requestAnimationFrame(checkStable); + } else { + // Timeout: use current position + resolve({ + x: rect.left + rect.width / 2, + y: rect.top + rect.height / 2 + }); + } + }; + + requestAnimationFrame(checkStable); + }); + } +""".trimIndent() diff --git a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt index 315082506..9184c7963 100644 --- a/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt +++ b/core/src/commonMain/kotlin/dev/kdriver/core/tab/DefaultTab.kt @@ -526,20 +526,25 @@ open class DefaultTab( * navigation anyway). */ private suspend fun inLookupGroup(lookup: suspend (LookupGroup) -> T): T { - val group = LookupGroup("kdriver-lookup-${Random.nextLong().toULong().toString(16)}") + val group = LookupGroup("kdriver-lookup-${Random.nextLong().toULong().toString(LOOKUP_GROUP_RADIX)}") try { return lookup(group) } finally { - if (group.holdsObjects) withContext(NonCancellable) { - withTimeoutOrNull(LOOKUP_RELEASE_WAIT) { - try { - val sent = group.release - if (sent != null) sent.await() else runtime.releaseObjectGroup(group.name) - } catch (e: CancellationException) { - throw e - } catch (_: Exception) { - // Already gone with the page, or the connection is closing: nothing left to release. - } + if (group.holdsObjects) releaseLookupGroup(group) + } + } + + // The cleanup of [inLookupGroup], a function of its own: a cancellation of the wait goes on from here. + private suspend fun releaseLookupGroup(group: LookupGroup) { + withContext(NonCancellable) { + withTimeoutOrNull(LOOKUP_RELEASE_WAIT) { + try { + val sent = group.release + if (sent != null) sent.await() else runtime.releaseObjectGroup(group.name) + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + // Already gone with the page, or the connection is closing: nothing left to release. } } } @@ -596,8 +601,9 @@ open class DefaultTab( ) } catch (e: CancellationException) { throw e - } catch (e: Exception) { - Result.failure(e) + } catch (expected: Exception) { + // Not swallowed: handed back as the failure, so that every reply is read before one is thrown. + Result.failure(expected) } private fun describeParameter(objectId: String): JsonElement = @@ -1106,6 +1112,9 @@ private val GONE = listOf( /** How long the release of the objects of an in-page lookup may hold the lookup, at most, in milliseconds. */ private const val LOOKUP_RELEASE_WAIT = 2_000L +// The base of the random suffix of a lookup group's name (hexadecimal). +private const val LOOKUP_GROUP_RADIX = 16 + /** The code and message Chrome answers `DOM.querySelector(All)` with for a selector it cannot parse. */ private const val INVALID_SELECTOR_CODE = -32000 private const val INVALID_SELECTOR_MESSAGE = "DOM Error while querying" diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBindingTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBindingTest.kt new file mode 100644 index 000000000..a644ec195 --- /dev/null +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageBindingTest.kt @@ -0,0 +1,338 @@ +@file:OptIn(dev.kdriver.cdp.InternalCdpApi::class) + +package dev.kdriver.core.tab + +import dev.kdriver.cdp.CDPException +import dev.kdriver.core.ScriptedTab +import dev.kdriver.core.ScriptedTransport +import dev.kdriver.core.ScriptedTransport.Reply +import dev.kdriver.core.dom.DefaultElement +import dev.kdriver.core.dom.Element +import dev.kdriver.core.dom.NodeOrElement +import dev.kdriver.core.exceptions.EvaluateException +import dev.kdriver.core.exceptions.TimeoutWaitingForElementException +import dev.kdriver.core.objectIdsOf +import dev.kdriver.core.param +import dev.kdriver.core.valueReply +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * The elements `select`, `selectAll`, `querySelector` and `querySelectorAll` find in the page get their node ids, tree + * and parent from the document when they are updated, read after the document was read, or when a lookup runs under + * them; a frame is searched with the page from one document read. + */ +class LookupsInPageBindingTest: LookupsInPageFixtures() { + + + private val documentWithAFrame = + """{"root":{"nodeId":1,"backendNodeId":1,"nodeType":9,"nodeName":"#document","localName":"","nodeValue":"",""" + + """"childNodeCount":2,"children":[{"nodeId":7,"backendNodeId":70,"nodeType":1,"nodeName":"P",""" + + """"localName":"p","nodeValue":"","childNodeCount":1,"children":[""" + + """{"nodeId":8,"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"",""" + + """"nodeValue":"Outer"}]},""" + + """{"nodeId":9,"backendNodeId":90,"nodeType":1,"nodeName":"IFRAME","localName":"iframe","nodeValue":"",""" + + """"childNodeCount":0,"contentDocument":{"nodeId":10,"backendNodeId":100,"nodeType":9,""" + + """"nodeName":"#document","localName":"","nodeValue":"","childNodeCount":1,"children":[""" + + """{"nodeId":11,"backendNodeId":110,"nodeType":1,"nodeName":"P","localName":"p","nodeValue":"",""" + + """"childNodeCount":1,"children":[{"nodeId":12,"backendNodeId":120,"nodeType":3,"nodeName":"#text",""" + + """"localName":"","nodeValue":"Inner"}]}]}}]}}""" + + @Test + fun selectAllWithAFrame_findsInsideItAndInThePage_fromOneDocumentRead() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "DOM.getDocument" -> Reply.ok(documentWithAFrame) + "DOM.querySelectorAll" -> when (it.param("nodeId")) { + "1" -> + if (it.param("selector") == "iframe") Reply.ok("""{"nodeIds":[9]}""") + else Reply.ok("""{"nodeIds":[7]}""") + "10" -> Reply.ok("""{"nodeIds":[11]}""") + else -> Reply.error("Could not find node with given id") + } + "DOM.resolveNode" -> Reply.ok("""{"object":{"type":"object","subtype":"node","objectId":"frame"}}""") + else -> Reply.ok() + } + } + + val found = tab.selectAll("p", timeout = 1_000, includeFrames = true) + + assertEquals(listOf("Inner", "Outer"), found.map { it.text }) + assertEquals(1, tab.sent.count { it == "DOM.getDocument" }, "one read for the frame and the page") + assertTrue("Runtime.evaluate" !in tab.sent) + tab.close() + } + + @Test + fun selectAllWithFrames_readsTheDocument() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "DOM.getDocument" -> Reply.ok(document) + "DOM.querySelectorAll" -> + if (it.param("selector") == "iframe") Reply.ok("""{"nodeIds":[]}""") + else Reply.ok("""{"nodeIds":[7]}""") + else -> Reply.ok() + } + } + + assertEquals(listOf("Send"), tab.selectAll("#go", timeout = 1_000, includeFrames = true).map { it.text }) + assertEquals( + listOf("iframe", "#go"), + tab.transport.sent.filter { it.method == "DOM.querySelectorAll" }.map { it.param("selector") } + ) + assertEquals(1, tab.sent.count { it == "DOM.getDocument" }, "one read for the frames and the page") + assertTrue("Runtime.evaluate" !in tab.sent) + tab.close() + } + + @Test + fun aLookupUnderAnElementFoundInThePage_bindsItToTheDocumentFirst() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-1")) + "DOM.describeNode" -> Reply.ok(button) + "DOM.getDocument" -> Reply.ok(document) + "DOM.querySelector" -> Reply.ok("""{"nodeId":8}""") + else -> Reply.ok() + } + } + val button = tab.querySelector("#go")!! + + val text = tab.querySelector("*", NodeOrElement.WrappedElement(button)) + + assertEquals(7, button.node.nodeId, "bound to the document") + assertEquals(1, button.tree?.nodeId) + assertEquals("7", tab.transport.sent.single { it.method == "DOM.querySelector" }.param("nodeId")) + assertEquals(8, text!!.node.nodeId) + assertNull(button.objectId, "bound without resolving its object") + tab.querySelector("*", NodeOrElement.WrappedElement(button)) + assertEquals(1, tab.sent.count { it == "DOM.getDocument" }, "a bound element is not bound again") + assertEquals(2, tab.sent.count { it == "DOM.querySelector" }) + assertTrue("DOM.resolveNode" !in tab.sent) + tab.close() + } + + /** `
  • Beta
`, as the document read gives it. */ + private val list = + """{"root":{"nodeId":1,"backendNodeId":1,"nodeType":9,"nodeName":"#document","localName":"","nodeValue":"",""" + + """"childNodeCount":1,"children":[{"nodeId":5,"parentId":1,"backendNodeId":50,"nodeType":1,""" + + """"nodeName":"UL","localName":"ul","nodeValue":"","attributes":["id","list"],"childNodeCount":1,""" + + """"children":[{"nodeId":7,"parentId":5,"backendNodeId":70,"nodeType":1,"nodeName":"LI",""" + + """"localName":"li","nodeValue":"","attributes":["class","item"],"childNodeCount":1,"children":[""" + + """{"nodeId":8,"parentId":7,"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"",""" + + """"nodeValue":"Beta"}]}]}]}}""" + + /** The same `li`, as `DOM.describeNode` gives it: no node ids, no parent id. */ + private val describedItem = + """{"node":{"nodeId":0,"backendNodeId":70,"nodeType":1,"nodeName":"LI","localName":"li","nodeValue":"",""" + + """"attributes":["class","item"],"childNodeCount":1,"children":[{"nodeId":0,"parentId":0,""" + + """"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"","nodeValue":"Beta"}]}}""" + + private fun TestScope.listTab() = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-1")) + "DOM.describeNode" -> Reply.ok(describedItem) + "DOM.getDocument" -> Reply.ok(list) + "DOM.querySelector" -> Reply.ok("""{"nodeId":7}""") + "DOM.resolveNode" -> Reply.ok("""{"object":{"type":"object","subtype":"node","objectId":"obj-2"}}""") + "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) + else -> Reply.ok() + } + } + + // What a lookup on the whole document gave: DOM.querySelector on the document read, the match taken from it. + private suspend fun ScriptedTab.onTheDocument(selector: String): Element = + querySelector(selector, NodeOrElement.WrappedNode(currentDocument().first))!! + + @Test + fun anElementFoundInThePage_hasNoNodeIdTreeNorParent_untilUpdated() = runTest(StandardTestDispatcher()) { + val tab = listTab() + + val item = tab.select("li.item", timeout = 1_000) + + assertEquals(0, item.node.nodeId) + assertNull(item.parentId) + assertNull(item.tree) + assertEquals( + "could not get parent since the element has no tree set", + assertFailsWith { item.parent }.message, + ) + assertEquals(listOf(0), item.children.map { it.node.nodeId }) + assertTrue("DOM.getDocument" !in tab.sent) + tab.close() + } + + @Test + fun update_givesTheNodeIdsTreeAndParent_aLookupOnTheDocumentGave() = runTest(StandardTestDispatcher()) { + val tab = listTab() + val item = tab.select("li.item", timeout = 1_000) + + item.update() + val before = tab.onTheDocument("li.item") + + assertEquals(before.node, item.node) + assertEquals(7, item.node.nodeId) + assertEquals(5, item.parentId) + assertEquals(before.tree, item.tree) + assertEquals(before.parent!!.node, item.parent!!.node) + assertEquals("ul", item.parent!!.tag) + assertEquals(before.children.map { it.node }, item.children.map { it.node }) + assertEquals(1, tab.sent.count { it == "DOM.getDocument" }, "one document read for both") + tab.close() + } + + @Test + fun anElementFoundInThePage_fillsItsNodeIdsTreeAndParent_onFirstRead_fromAKeptDocument() = + runTest(StandardTestDispatcher()) { + val tab = listTab() + val before = tab.onTheDocument("li.item") + val item = tab.select("li.item", timeout = 1_000) + val sentBefore = tab.sent.size + + assertEquals(before.node, item.node) + assertEquals(7, item.node.nodeId) + assertEquals(5, item.parentId) + assertEquals(before.tree, item.tree) + assertEquals("ul", item.parent!!.tag) + assertEquals(listOf(8), item.children.map { it.node.nodeId }) + assertEquals(sentBefore, tab.sent.size, "filled from the kept document, with no command") + assertEquals(1, tab.sent.count { it == "DOM.getDocument" }) + tab.close() + } + + @Test + fun anElementFoundInThePage_isNotFilledFromADocumentThePageChangedSince() = runTest(StandardTestDispatcher()) { + val tab = listTab() + tab.onTheDocument("li.item") + tab.transport.event("DOM.attributeModified", """{"nodeId":7,"name":"class","value":"busy"}""") + runCurrent() + + val item = tab.select("li.item", timeout = 1_000) + + assertEquals(0, item.node.nodeId) + assertNull(item.tree) + item.update() + assertEquals(7, item.node.nodeId, "update() still reads the document") + assertEquals(2, tab.sent.count { it == "DOM.getDocument" }) + tab.close() + } + + @Test + fun anElementFoundInThePage_whoseNodeTheKeptDocumentLacks_staysAsFound() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-1")) + "DOM.describeNode" -> Reply.ok(item(30, "Gone")) + "DOM.getDocument" -> Reply.ok(list) + "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) + else -> Reply.ok() + } + } + tab.currentDocument() + val gone = tab.select("li", timeout = 1_000) + + assertEquals(0, gone.node.nodeId) + assertNull(gone.tree) + assertEquals("Gone", gone.text) + (gone as DefaultElement).node = gone.node.copy(nodeName = "P") + assertEquals("p", gone.tag, "a node set by hand is kept") + tab.close() + } + + @Test + fun aBareNodeFoundInThePage_isReplacedByTheDocumentNode_forALookupUnderIt() = runTest(StandardTestDispatcher()) { + val tab = listTab() + val item = tab.querySelector("li.item")!! + + tab.querySelector("*", NodeOrElement.WrappedNode(item.node)) + + assertEquals("7", tab.transport.sent.single { it.method == "DOM.querySelector" }.param("nodeId")) + tab.close() + } + + @Test + fun aNodeFoundInThePage_butGoneFromTheDocument_isQueriedAsItIs() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("obj-1")) + "DOM.describeNode" -> Reply.ok(item(30, "Gone")) + "DOM.getDocument" -> Reply.ok(list) + "DOM.querySelector" -> Reply.error("Could not find node with given id") + "DOM.resolveNode" -> Reply.ok("""{"object":{"type":"object","subtype":"node","objectId":"obj-2"}}""") + else -> Reply.ok() + } + } + val gone = tab.querySelector("li")!! + + assertNull(tab.querySelector("*", NodeOrElement.WrappedNode(gone.node))) + assertNull(tab.querySelector("*", NodeOrElement.WrappedElement(gone))) + + assertEquals(0, gone.node.nodeId, "no node of the document to take") + assertEquals(1, gone.tree?.nodeId, "the element is bound to the document all the same, as update() does") + val queried = tab.transport.sent.filter { it.method == "DOM.querySelector" }.map { it.param("nodeId") } + assertEquals(listOf("0", "0"), queried.take(2)) + tab.close() + } + + @Test + fun anotherElementImplementation_isUpdated_beforeALookupUnderIt() = runTest(StandardTestDispatcher()) { + val tab = listTab() + val found = tab.querySelector("li.item")!! + val wrapper: Element = object : Element by found {} + + tab.querySelector("*", NodeOrElement.WrappedElement(wrapper)) + + assertEquals(7, wrapper.node.nodeId) + assertTrue("DOM.resolveNode" in tab.sent, "Element.update resolves the object, as it always did") + tab.close() + } + + @Test + fun querySelectorAll_readsTheDocument_whenTheMatchesOutweighIt() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok("""{"result":{"type":"string","value":"document"}}""") + "DOM.getDocument" -> Reply.ok(list) + "DOM.querySelectorAll" -> Reply.ok("""{"nodeIds":[5,7]}""") + else -> Reply.ok() + } + } + + val found = tab.querySelectorAll("ul, li") + + assertEquals(listOf(5, 7), found.map { it.node.nodeId }, "read from the document, as before") + assertEquals(listOf(1, 1), found.map { it.tree?.nodeId }) + assertEquals(listOf("Runtime.evaluate", "DOM.getDocument", "DOM.querySelectorAll"), tab.sent) + tab.close() + } + + @Test + fun anElementOfQuerySelectorAll_resolvesItsNodeAtItsFirstCall() = runTest(StandardTestDispatcher()) { + val tab = tab { + when (it.method) { + "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) + "Runtime.getProperties" -> Reply.ok(arrayOfOne) + "DOM.describeNode" -> Reply.ok(item(10, "Alpha")) + "DOM.resolveNode" -> Reply.ok("""{"object":{"type":"object","subtype":"node","objectId":"obj-2"}}""") + "Runtime.callFunctionOn" -> Reply.ok(valueReply("null")) + else -> Reply.ok() + } + } + + tab.querySelectorAll(".item").single().click() + + assertEquals("10", tab.transport.sent.single { it.method == "DOM.resolveNode" }.param("backendNodeId")) + assertEquals(listOf("obj-2"), tab.transport.objectIdsOf()) + tab.close() + } +} diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageFixtures.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageFixtures.kt new file mode 100644 index 000000000..46547e475 --- /dev/null +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageFixtures.kt @@ -0,0 +1,67 @@ +@file:OptIn(dev.kdriver.cdp.InternalCdpApi::class) + +package dev.kdriver.core.tab + +import dev.kdriver.cdp.CDPException +import dev.kdriver.core.ScriptedTab +import dev.kdriver.core.ScriptedTransport +import dev.kdriver.core.ScriptedTransport.Reply +import dev.kdriver.core.dom.DefaultElement +import dev.kdriver.core.dom.Element +import dev.kdriver.core.dom.NodeOrElement +import dev.kdriver.core.exceptions.EvaluateException +import dev.kdriver.core.exceptions.TimeoutWaitingForElementException +import dev.kdriver.core.objectIdsOf +import dev.kdriver.core.param +import dev.kdriver.core.valueReply +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** The replies and helpers the tests of the lookups in the page share. */ +abstract class LookupsInPageFixtures { + + protected val button = + """{"node":{"nodeId":0,"backendNodeId":70,"nodeType":1,"nodeName":"BUTTON","localName":"button",""" + + """"nodeValue":"","attributes":["id","go"],"childNodeCount":1,"children":[{"nodeId":0,""" + + """"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"","nodeValue":"Send"}]}}""" + + protected fun item(backendNodeId: Int, text: String) = + """{"node":{"nodeId":0,"backendNodeId":$backendNodeId,"nodeType":1,"nodeName":"LI","localName":"li",""" + + """"nodeValue":"","childNodeCount":1,"children":[{"nodeId":0,"backendNodeId":${backendNodeId + 1},""" + + """"nodeType":3,"nodeName":"#text","localName":"","nodeValue":"$text"}]}}""" + + // An own property of the array of `querySelectorAll`: the match at [index], as Runtime.getProperties lists it. + protected fun match(index: Int, objectId: String) = + """{"name":"$index","configurable":true,"enumerable":true,""" + + """"value":{"type":"object","subtype":"node","objectId":"$objectId"}}""" + + protected val nothing = """{"result":{"type":"object","subtype":"null","value":null}}""" + + protected fun found(objectId: String, subtype: String = "node") = + """{"result":{"type":"object","subtype":"$subtype","objectId":"$objectId"}}""" + + protected val document = + """{"root":{"nodeId":1,"backendNodeId":1,"nodeType":9,"nodeName":"#document","localName":"","nodeValue":"",""" + + """"childNodeCount":1,"children":[{"nodeId":7,"backendNodeId":70,"nodeType":1,"nodeName":"BUTTON",""" + + """"localName":"button","nodeValue":"","attributes":["id","go"],"childNodeCount":1,"children":[""" + + """{"nodeId":8,"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"","nodeValue":"Send"}]}]}}""" + + protected fun TestScope.tab(answer: (ScriptedTransport.Sent) -> Reply): ScriptedTab = + ScriptedTab(this, ScriptedTransport(this, answer)) + + protected val ScriptedTab.sent get() = transport.methods + + protected val arrayOfOne = """{"result":[""" + + """${match(0, "li-0")}""" + + """]}""" +} diff --git a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt index c18a78e32..0230562d3 100644 --- a/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt +++ b/core/src/jvmTest/kotlin/dev/kdriver/core/tab/LookupsInPageTest.kt @@ -33,38 +33,7 @@ import kotlin.test.assertTrue * tree and parent from the document when it is updated or a lookup runs under it, the same as a lookup on the * document gave them; an invalid selector throws the browser's error of `DOM.querySelector(All)`. */ -class LookupsInPageTest { - - private val button = - """{"node":{"nodeId":0,"backendNodeId":70,"nodeType":1,"nodeName":"BUTTON","localName":"button",""" + - """"nodeValue":"","attributes":["id","go"],"childNodeCount":1,"children":[{"nodeId":0,""" + - """"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"","nodeValue":"Send"}]}}""" - - private fun item(backendNodeId: Int, text: String) = - """{"node":{"nodeId":0,"backendNodeId":$backendNodeId,"nodeType":1,"nodeName":"LI","localName":"li",""" + - """"nodeValue":"","childNodeCount":1,"children":[{"nodeId":0,"backendNodeId":${backendNodeId + 1},""" + - """"nodeType":3,"nodeName":"#text","localName":"","nodeValue":"$text"}]}}""" - - // An own property of the array of `querySelectorAll`: the match at [index], as Runtime.getProperties lists it. - private fun match(index: Int, objectId: String) = - """{"name":"$index","configurable":true,"enumerable":true,""" + - """"value":{"type":"object","subtype":"node","objectId":"$objectId"}}""" - - private val nothing = """{"result":{"type":"object","subtype":"null","value":null}}""" - - private fun found(objectId: String, subtype: String = "node") = - """{"result":{"type":"object","subtype":"$subtype","objectId":"$objectId"}}""" - - private val document = - """{"root":{"nodeId":1,"backendNodeId":1,"nodeType":9,"nodeName":"#document","localName":"","nodeValue":"",""" + - """"childNodeCount":1,"children":[{"nodeId":7,"backendNodeId":70,"nodeType":1,"nodeName":"BUTTON",""" + - """"localName":"button","nodeValue":"","attributes":["id","go"],"childNodeCount":1,"children":[""" + - """{"nodeId":8,"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"","nodeValue":"Send"}]}]}}""" - - private fun TestScope.tab(answer: (ScriptedTransport.Sent) -> Reply): ScriptedTab = - ScriptedTab(this, ScriptedTransport(this, answer)) - - private val ScriptedTab.sent get() = transport.methods +class LookupsInPageTest: LookupsInPageFixtures() { @Test fun select_asksThePage_andDescribesTheMatch_withoutReadingTheDocument() = runTest(StandardTestDispatcher()) { @@ -383,10 +352,6 @@ class LookupsInPageTest { tab.close() } - private val arrayOfOne = """{"result":[""" + - """${match(0, "li-0")}""" + - """]}""" - @Test fun querySelectorAll_findsNothing_whenTheArrayIsGoneBeforeItIsRead() = runTest(StandardTestDispatcher()) { val tab = tab { @@ -589,308 +554,6 @@ class LookupsInPageTest { assertEquals(listOf("Alpha"), tab.querySelectorAll(".item").map { it.text }) tab.close() } - - private val documentWithAFrame = - """{"root":{"nodeId":1,"backendNodeId":1,"nodeType":9,"nodeName":"#document","localName":"","nodeValue":"",""" + - """"childNodeCount":2,"children":[{"nodeId":7,"backendNodeId":70,"nodeType":1,"nodeName":"P",""" + - """"localName":"p","nodeValue":"","childNodeCount":1,"children":[""" + - """{"nodeId":8,"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"",""" + - """"nodeValue":"Outer"}]},""" + - """{"nodeId":9,"backendNodeId":90,"nodeType":1,"nodeName":"IFRAME","localName":"iframe","nodeValue":"",""" + - """"childNodeCount":0,"contentDocument":{"nodeId":10,"backendNodeId":100,"nodeType":9,""" + - """"nodeName":"#document","localName":"","nodeValue":"","childNodeCount":1,"children":[""" + - """{"nodeId":11,"backendNodeId":110,"nodeType":1,"nodeName":"P","localName":"p","nodeValue":"",""" + - """"childNodeCount":1,"children":[{"nodeId":12,"backendNodeId":120,"nodeType":3,"nodeName":"#text",""" + - """"localName":"","nodeValue":"Inner"}]}]}}]}}""" - - @Test - fun selectAllWithAFrame_findsInsideItAndInThePage_fromOneDocumentRead() = runTest(StandardTestDispatcher()) { - val tab = tab { - when (it.method) { - "DOM.getDocument" -> Reply.ok(documentWithAFrame) - "DOM.querySelectorAll" -> when (it.param("nodeId")) { - "1" -> - if (it.param("selector") == "iframe") Reply.ok("""{"nodeIds":[9]}""") - else Reply.ok("""{"nodeIds":[7]}""") - "10" -> Reply.ok("""{"nodeIds":[11]}""") - else -> Reply.error("Could not find node with given id") - } - "DOM.resolveNode" -> Reply.ok("""{"object":{"type":"object","subtype":"node","objectId":"frame"}}""") - else -> Reply.ok() - } - } - - val found = tab.selectAll("p", timeout = 1_000, includeFrames = true) - - assertEquals(listOf("Inner", "Outer"), found.map { it.text }) - assertEquals(1, tab.sent.count { it == "DOM.getDocument" }, "one read for the frame and the page") - assertTrue("Runtime.evaluate" !in tab.sent) - tab.close() - } - - @Test - fun selectAllWithFrames_readsTheDocument() = runTest(StandardTestDispatcher()) { - val tab = tab { - when (it.method) { - "DOM.getDocument" -> Reply.ok(document) - "DOM.querySelectorAll" -> - if (it.param("selector") == "iframe") Reply.ok("""{"nodeIds":[]}""") - else Reply.ok("""{"nodeIds":[7]}""") - else -> Reply.ok() - } - } - - assertEquals(listOf("Send"), tab.selectAll("#go", timeout = 1_000, includeFrames = true).map { it.text }) - assertEquals( - listOf("iframe", "#go"), - tab.transport.sent.filter { it.method == "DOM.querySelectorAll" }.map { it.param("selector") } - ) - assertEquals(1, tab.sent.count { it == "DOM.getDocument" }, "one read for the frames and the page") - assertTrue("Runtime.evaluate" !in tab.sent) - tab.close() - } - - @Test - fun aLookupUnderAnElementFoundInThePage_bindsItToTheDocumentFirst() = runTest(StandardTestDispatcher()) { - val tab = tab { - when (it.method) { - "Runtime.evaluate" -> Reply.ok(found("obj-1")) - "DOM.describeNode" -> Reply.ok(button) - "DOM.getDocument" -> Reply.ok(document) - "DOM.querySelector" -> Reply.ok("""{"nodeId":8}""") - else -> Reply.ok() - } - } - val button = tab.querySelector("#go")!! - - val text = tab.querySelector("*", NodeOrElement.WrappedElement(button)) - - assertEquals(7, button.node.nodeId, "bound to the document") - assertEquals(1, button.tree?.nodeId) - assertEquals("7", tab.transport.sent.single { it.method == "DOM.querySelector" }.param("nodeId")) - assertEquals(8, text!!.node.nodeId) - assertNull(button.objectId, "bound without resolving its object") - tab.querySelector("*", NodeOrElement.WrappedElement(button)) - assertEquals(1, tab.sent.count { it == "DOM.getDocument" }, "a bound element is not bound again") - assertEquals(2, tab.sent.count { it == "DOM.querySelector" }) - assertTrue("DOM.resolveNode" !in tab.sent) - tab.close() - } - - /** `
  • Beta
`, as the document read gives it. */ - private val list = - """{"root":{"nodeId":1,"backendNodeId":1,"nodeType":9,"nodeName":"#document","localName":"","nodeValue":"",""" + - """"childNodeCount":1,"children":[{"nodeId":5,"parentId":1,"backendNodeId":50,"nodeType":1,""" + - """"nodeName":"UL","localName":"ul","nodeValue":"","attributes":["id","list"],"childNodeCount":1,""" + - """"children":[{"nodeId":7,"parentId":5,"backendNodeId":70,"nodeType":1,"nodeName":"LI",""" + - """"localName":"li","nodeValue":"","attributes":["class","item"],"childNodeCount":1,"children":[""" + - """{"nodeId":8,"parentId":7,"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"",""" + - """"nodeValue":"Beta"}]}]}]}}""" - - /** The same `li`, as `DOM.describeNode` gives it: no node ids, no parent id. */ - private val describedItem = - """{"node":{"nodeId":0,"backendNodeId":70,"nodeType":1,"nodeName":"LI","localName":"li","nodeValue":"",""" + - """"attributes":["class","item"],"childNodeCount":1,"children":[{"nodeId":0,"parentId":0,""" + - """"backendNodeId":80,"nodeType":3,"nodeName":"#text","localName":"","nodeValue":"Beta"}]}}""" - - private fun TestScope.listTab() = tab { - when (it.method) { - "Runtime.evaluate" -> Reply.ok(found("obj-1")) - "DOM.describeNode" -> Reply.ok(describedItem) - "DOM.getDocument" -> Reply.ok(list) - "DOM.querySelector" -> Reply.ok("""{"nodeId":7}""") - "DOM.resolveNode" -> Reply.ok("""{"object":{"type":"object","subtype":"node","objectId":"obj-2"}}""") - "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) - else -> Reply.ok() - } - } - - // What a lookup on the whole document gave: DOM.querySelector on the document read, the match taken from it. - private suspend fun ScriptedTab.onTheDocument(selector: String): Element = - querySelector(selector, NodeOrElement.WrappedNode(currentDocument().first))!! - - @Test - fun anElementFoundInThePage_hasNoNodeIdTreeNorParent_untilUpdated() = runTest(StandardTestDispatcher()) { - val tab = listTab() - - val item = tab.select("li.item", timeout = 1_000) - - assertEquals(0, item.node.nodeId) - assertNull(item.parentId) - assertNull(item.tree) - assertEquals( - "could not get parent since the element has no tree set", - assertFailsWith { item.parent }.message, - ) - assertEquals(listOf(0), item.children.map { it.node.nodeId }) - assertTrue("DOM.getDocument" !in tab.sent) - tab.close() - } - - @Test - fun update_givesTheNodeIdsTreeAndParent_aLookupOnTheDocumentGave() = runTest(StandardTestDispatcher()) { - val tab = listTab() - val item = tab.select("li.item", timeout = 1_000) - - item.update() - val before = tab.onTheDocument("li.item") - - assertEquals(before.node, item.node) - assertEquals(7, item.node.nodeId) - assertEquals(5, item.parentId) - assertEquals(before.tree, item.tree) - assertEquals(before.parent!!.node, item.parent!!.node) - assertEquals("ul", item.parent!!.tag) - assertEquals(before.children.map { it.node }, item.children.map { it.node }) - assertEquals(1, tab.sent.count { it == "DOM.getDocument" }, "one document read for both") - tab.close() - } - - @Test - fun anElementFoundInThePage_fillsItsNodeIdsTreeAndParent_onFirstRead_fromAKeptDocument() = - runTest(StandardTestDispatcher()) { - val tab = listTab() - val before = tab.onTheDocument("li.item") - val item = tab.select("li.item", timeout = 1_000) - val sentBefore = tab.sent.size - - assertEquals(before.node, item.node) - assertEquals(7, item.node.nodeId) - assertEquals(5, item.parentId) - assertEquals(before.tree, item.tree) - assertEquals("ul", item.parent!!.tag) - assertEquals(listOf(8), item.children.map { it.node.nodeId }) - assertEquals(sentBefore, tab.sent.size, "filled from the kept document, with no command") - assertEquals(1, tab.sent.count { it == "DOM.getDocument" }) - tab.close() - } - - @Test - fun anElementFoundInThePage_isNotFilledFromADocumentThePageChangedSince() = runTest(StandardTestDispatcher()) { - val tab = listTab() - tab.onTheDocument("li.item") - tab.transport.event("DOM.attributeModified", """{"nodeId":7,"name":"class","value":"busy"}""") - runCurrent() - - val item = tab.select("li.item", timeout = 1_000) - - assertEquals(0, item.node.nodeId) - assertNull(item.tree) - item.update() - assertEquals(7, item.node.nodeId, "update() still reads the document") - assertEquals(2, tab.sent.count { it == "DOM.getDocument" }) - tab.close() - } - - @Test - fun anElementFoundInThePage_whoseNodeTheKeptDocumentLacks_staysAsFound() = runTest(StandardTestDispatcher()) { - val tab = tab { - when (it.method) { - "Runtime.evaluate" -> Reply.ok(found("obj-1")) - "DOM.describeNode" -> Reply.ok(item(30, "Gone")) - "DOM.getDocument" -> Reply.ok(list) - "Target.getTargetInfo" -> Reply.ok(ScriptedTab.TARGET_INFO) - else -> Reply.ok() - } - } - tab.currentDocument() - val gone = tab.select("li", timeout = 1_000) - - assertEquals(0, gone.node.nodeId) - assertNull(gone.tree) - assertEquals("Gone", gone.text) - (gone as DefaultElement).node = gone.node.copy(nodeName = "P") - assertEquals("p", gone.tag, "a node set by hand is kept") - tab.close() - } - - @Test - fun aBareNodeFoundInThePage_isReplacedByTheDocumentNode_forALookupUnderIt() = runTest(StandardTestDispatcher()) { - val tab = listTab() - val item = tab.querySelector("li.item")!! - - tab.querySelector("*", NodeOrElement.WrappedNode(item.node)) - - assertEquals("7", tab.transport.sent.single { it.method == "DOM.querySelector" }.param("nodeId")) - tab.close() - } - - @Test - fun aNodeFoundInThePage_butGoneFromTheDocument_isQueriedAsItIs() = runTest(StandardTestDispatcher()) { - val tab = tab { - when (it.method) { - "Runtime.evaluate" -> Reply.ok(found("obj-1")) - "DOM.describeNode" -> Reply.ok(item(30, "Gone")) - "DOM.getDocument" -> Reply.ok(list) - "DOM.querySelector" -> Reply.error("Could not find node with given id") - "DOM.resolveNode" -> Reply.ok("""{"object":{"type":"object","subtype":"node","objectId":"obj-2"}}""") - else -> Reply.ok() - } - } - val gone = tab.querySelector("li")!! - - assertNull(tab.querySelector("*", NodeOrElement.WrappedNode(gone.node))) - assertNull(tab.querySelector("*", NodeOrElement.WrappedElement(gone))) - - assertEquals(0, gone.node.nodeId, "no node of the document to take") - assertEquals(1, gone.tree?.nodeId, "the element is bound to the document all the same, as update() does") - val queried = tab.transport.sent.filter { it.method == "DOM.querySelector" }.map { it.param("nodeId") } - assertEquals(listOf("0", "0"), queried.take(2)) - tab.close() - } - - @Test - fun anotherElementImplementation_isUpdated_beforeALookupUnderIt() = runTest(StandardTestDispatcher()) { - val tab = listTab() - val found = tab.querySelector("li.item")!! - val wrapper: Element = object : Element by found {} - - tab.querySelector("*", NodeOrElement.WrappedElement(wrapper)) - - assertEquals(7, wrapper.node.nodeId) - assertTrue("DOM.resolveNode" in tab.sent, "Element.update resolves the object, as it always did") - tab.close() - } - - @Test - fun querySelectorAll_readsTheDocument_whenTheMatchesOutweighIt() = runTest(StandardTestDispatcher()) { - val tab = tab { - when (it.method) { - "Runtime.evaluate" -> Reply.ok("""{"result":{"type":"string","value":"document"}}""") - "DOM.getDocument" -> Reply.ok(list) - "DOM.querySelectorAll" -> Reply.ok("""{"nodeIds":[5,7]}""") - else -> Reply.ok() - } - } - - val found = tab.querySelectorAll("ul, li") - - assertEquals(listOf(5, 7), found.map { it.node.nodeId }, "read from the document, as before") - assertEquals(listOf(1, 1), found.map { it.tree?.nodeId }) - assertEquals(listOf("Runtime.evaluate", "DOM.getDocument", "DOM.querySelectorAll"), tab.sent) - tab.close() - } - - @Test - fun anElementOfQuerySelectorAll_resolvesItsNodeAtItsFirstCall() = runTest(StandardTestDispatcher()) { - val tab = tab { - when (it.method) { - "Runtime.evaluate" -> Reply.ok(found("array", subtype = "array")) - "Runtime.getProperties" -> Reply.ok(arrayOfOne) - "DOM.describeNode" -> Reply.ok(item(10, "Alpha")) - "DOM.resolveNode" -> Reply.ok("""{"object":{"type":"object","subtype":"node","objectId":"obj-2"}}""") - "Runtime.callFunctionOn" -> Reply.ok(valueReply("null")) - else -> Reply.ok() - } - } - - tab.querySelectorAll(".item").single().click() - - assertEquals("10", tab.transport.sent.single { it.method == "DOM.resolveNode" }.param("backendNodeId")) - assertEquals(listOf("obj-2"), tab.transport.objectIdsOf()) - tab.close() - } - @Test fun aSyntaxErrorThrownByAScriptOfThePage_isAnEvaluateException() = runTest(StandardTestDispatcher()) { val tab = tab { @@ -917,5 +580,4 @@ class LookupsInPageTest { assertEquals(listOf("Runtime.evaluate"), tab.sent) tab.close() } - }