@plune-ai/cairn 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (337) hide show
  1. package/README.md +84 -8
  2. package/dist/agent/check-docs.d.ts +25 -0
  3. package/dist/agent/check-docs.d.ts.map +1 -0
  4. package/dist/agent/check-docs.js +57 -0
  5. package/dist/agent/check-docs.js.map +1 -0
  6. package/dist/agent/collect-docs.d.ts +94 -0
  7. package/dist/agent/collect-docs.d.ts.map +1 -0
  8. package/dist/agent/collect-docs.js +326 -0
  9. package/dist/agent/collect-docs.js.map +1 -0
  10. package/dist/agent/graph.d.ts +39 -2
  11. package/dist/agent/graph.d.ts.map +1 -1
  12. package/dist/agent/graph.js +113 -4
  13. package/dist/agent/graph.js.map +1 -1
  14. package/dist/agent/index.d.ts +14 -0
  15. package/dist/agent/index.d.ts.map +1 -1
  16. package/dist/agent/index.js +114 -10
  17. package/dist/agent/index.js.map +1 -1
  18. package/dist/agent/overlays.d.ts +88 -0
  19. package/dist/agent/overlays.d.ts.map +1 -0
  20. package/dist/agent/overlays.js +447 -0
  21. package/dist/agent/overlays.js.map +1 -0
  22. package/dist/agent/repair-loop.d.ts +8 -1
  23. package/dist/agent/repair-loop.d.ts.map +1 -1
  24. package/dist/agent/repair-loop.js +18 -3
  25. package/dist/agent/repair-loop.js.map +1 -1
  26. package/dist/analyze/index.d.ts +1 -1
  27. package/dist/analyze/index.d.ts.map +1 -1
  28. package/dist/analyze/index.js +3 -2
  29. package/dist/analyze/index.js.map +1 -1
  30. package/dist/api/adversarial.d.ts +1 -1
  31. package/dist/api/adversarial.js +1 -1
  32. package/dist/api/collection.d.ts +20 -0
  33. package/dist/api/collection.d.ts.map +1 -0
  34. package/dist/api/collection.js +357 -0
  35. package/dist/api/collection.js.map +1 -0
  36. package/dist/api/derived.d.ts +179 -0
  37. package/dist/api/derived.d.ts.map +1 -0
  38. package/dist/api/derived.js +852 -0
  39. package/dist/api/derived.js.map +1 -0
  40. package/dist/api/discover.d.ts +66 -0
  41. package/dist/api/discover.d.ts.map +1 -0
  42. package/dist/api/discover.js +125 -0
  43. package/dist/api/discover.js.map +1 -0
  44. package/dist/api/flows.d.ts +194 -0
  45. package/dist/api/flows.d.ts.map +1 -0
  46. package/dist/api/flows.js +663 -0
  47. package/dist/api/flows.js.map +1 -0
  48. package/dist/api/guard.d.ts +19 -0
  49. package/dist/api/guard.d.ts.map +1 -1
  50. package/dist/api/guard.js +18 -4
  51. package/dist/api/guard.js.map +1 -1
  52. package/dist/api/openapi.d.ts +17 -1
  53. package/dist/api/openapi.d.ts.map +1 -1
  54. package/dist/api/openapi.js +64 -3
  55. package/dist/api/openapi.js.map +1 -1
  56. package/dist/api/runner.d.ts.map +1 -1
  57. package/dist/api/runner.js +18 -14
  58. package/dist/api/runner.js.map +1 -1
  59. package/dist/api/two-actor.d.ts +165 -0
  60. package/dist/api/two-actor.d.ts.map +1 -0
  61. package/dist/api/two-actor.js +627 -0
  62. package/dist/api/two-actor.js.map +1 -0
  63. package/dist/artifacts/contract.d.ts +1 -1
  64. package/dist/artifacts/contract.d.ts.map +1 -1
  65. package/dist/artifacts/index.d.ts +5 -0
  66. package/dist/artifacts/index.d.ts.map +1 -1
  67. package/dist/artifacts/index.js +14 -10
  68. package/dist/artifacts/index.js.map +1 -1
  69. package/dist/artifacts/report.d.ts +29 -2
  70. package/dist/artifacts/report.d.ts.map +1 -1
  71. package/dist/artifacts/report.js +65 -1
  72. package/dist/artifacts/report.js.map +1 -1
  73. package/dist/artifacts/testcase-md.d.ts +18 -0
  74. package/dist/artifacts/testcase-md.d.ts.map +1 -1
  75. package/dist/artifacts/testcase-md.js +15 -1
  76. package/dist/artifacts/testcase-md.js.map +1 -1
  77. package/dist/browser/api-traffic.d.ts +85 -0
  78. package/dist/browser/api-traffic.d.ts.map +1 -0
  79. package/dist/browser/api-traffic.js +283 -0
  80. package/dist/browser/api-traffic.js.map +1 -0
  81. package/dist/browser/backends/playwright-cli.d.ts.map +1 -1
  82. package/dist/browser/backends/playwright-cli.js +3 -0
  83. package/dist/browser/backends/playwright-cli.js.map +1 -1
  84. package/dist/browser/backends/playwright-lib.d.ts +84 -1
  85. package/dist/browser/backends/playwright-lib.d.ts.map +1 -1
  86. package/dist/browser/backends/playwright-lib.js +677 -32
  87. package/dist/browser/backends/playwright-lib.js.map +1 -1
  88. package/dist/browser/click-effect.d.ts +84 -0
  89. package/dist/browser/click-effect.d.ts.map +1 -0
  90. package/dist/browser/click-effect.js +235 -0
  91. package/dist/browser/click-effect.js.map +1 -0
  92. package/dist/browser/gateway.d.ts +9 -1
  93. package/dist/browser/gateway.d.ts.map +1 -1
  94. package/dist/browser/index.d.ts +3 -0
  95. package/dist/browser/index.d.ts.map +1 -1
  96. package/dist/browser/index.js +5 -0
  97. package/dist/browser/index.js.map +1 -1
  98. package/dist/browser/types.d.ts +196 -1
  99. package/dist/browser/types.d.ts.map +1 -1
  100. package/dist/cli/index.d.ts +1 -1
  101. package/dist/cli/index.d.ts.map +1 -1
  102. package/dist/cli/index.js +123 -5
  103. package/dist/cli/index.js.map +1 -1
  104. package/dist/codegen/index.d.ts +10 -1
  105. package/dist/codegen/index.d.ts.map +1 -1
  106. package/dist/codegen/index.js +28 -7
  107. package/dist/codegen/index.js.map +1 -1
  108. package/dist/codegen/lint.d.ts +32 -1
  109. package/dist/codegen/lint.d.ts.map +1 -1
  110. package/dist/codegen/lint.js +286 -1
  111. package/dist/codegen/lint.js.map +1 -1
  112. package/dist/codegen/mailbox.d.ts +19 -0
  113. package/dist/codegen/mailbox.d.ts.map +1 -0
  114. package/dist/codegen/mailbox.js +78 -0
  115. package/dist/codegen/mailbox.js.map +1 -0
  116. package/dist/codegen/schema.d.ts.map +1 -1
  117. package/dist/codegen/schema.js +3 -2
  118. package/dist/codegen/schema.js.map +1 -1
  119. package/dist/config/profiles.d.ts +2 -0
  120. package/dist/config/profiles.d.ts.map +1 -1
  121. package/dist/config/profiles.js +2 -0
  122. package/dist/config/profiles.js.map +1 -1
  123. package/dist/core/modalities/api.d.ts.map +1 -1
  124. package/dist/core/modalities/api.js +265 -29
  125. package/dist/core/modalities/api.js.map +1 -1
  126. package/dist/core/modalities/check-docs.d.ts +3 -0
  127. package/dist/core/modalities/check-docs.d.ts.map +1 -0
  128. package/dist/core/modalities/check-docs.js +64 -0
  129. package/dist/core/modalities/check-docs.js.map +1 -0
  130. package/dist/core/modalities/collect-docs.d.ts +3 -0
  131. package/dist/core/modalities/collect-docs.d.ts.map +1 -0
  132. package/dist/core/modalities/collect-docs.js +48 -0
  133. package/dist/core/modalities/collect-docs.js.map +1 -0
  134. package/dist/core/modalities/explore.d.ts.map +1 -1
  135. package/dist/core/modalities/explore.js +2 -0
  136. package/dist/core/modalities/explore.js.map +1 -1
  137. package/dist/core/modalities/mcp-test.d.ts +3 -0
  138. package/dist/core/modalities/mcp-test.d.ts.map +1 -0
  139. package/dist/core/modalities/mcp-test.js +26 -0
  140. package/dist/core/modalities/mcp-test.js.map +1 -0
  141. package/dist/core/registry.d.ts.map +1 -1
  142. package/dist/core/registry.js +11 -3
  143. package/dist/core/registry.js.map +1 -1
  144. package/dist/decider/uses/repair-triage.d.ts +9 -0
  145. package/dist/decider/uses/repair-triage.d.ts.map +1 -1
  146. package/dist/decider/uses/repair-triage.js +20 -3
  147. package/dist/decider/uses/repair-triage.js.map +1 -1
  148. package/dist/design/critique.d.ts +1 -1
  149. package/dist/design/index.d.ts +7 -1
  150. package/dist/design/index.d.ts.map +1 -1
  151. package/dist/design/index.js +20 -2
  152. package/dist/design/index.js.map +1 -1
  153. package/dist/design/schema.d.ts +9 -3
  154. package/dist/design/schema.d.ts.map +1 -1
  155. package/dist/design/schema.js +4 -1
  156. package/dist/design/schema.js.map +1 -1
  157. package/dist/documentarian/check.d.ts +91 -0
  158. package/dist/documentarian/check.d.ts.map +1 -0
  159. package/dist/documentarian/check.js +230 -0
  160. package/dist/documentarian/check.js.map +1 -0
  161. package/dist/documentarian/docs.d.ts +103 -0
  162. package/dist/documentarian/docs.d.ts.map +1 -0
  163. package/dist/documentarian/docs.js +243 -0
  164. package/dist/documentarian/docs.js.map +1 -0
  165. package/dist/documentarian/index.d.ts +2 -0
  166. package/dist/documentarian/index.d.ts.map +1 -1
  167. package/dist/documentarian/index.js +5 -4
  168. package/dist/documentarian/index.js.map +1 -1
  169. package/dist/environment/apply.js +1 -1
  170. package/dist/environment/apply.js.map +1 -1
  171. package/dist/flow/crawl.d.ts +4 -0
  172. package/dist/flow/crawl.d.ts.map +1 -1
  173. package/dist/flow/crawl.js +9 -2
  174. package/dist/flow/crawl.js.map +1 -1
  175. package/dist/fs/inside-dir.d.ts +8 -0
  176. package/dist/fs/inside-dir.d.ts.map +1 -0
  177. package/dist/fs/inside-dir.js +15 -0
  178. package/dist/fs/inside-dir.js.map +1 -0
  179. package/dist/index.d.ts +6 -2
  180. package/dist/index.d.ts.map +1 -1
  181. package/dist/index.js +3 -0
  182. package/dist/index.js.map +1 -1
  183. package/dist/llm/index.d.ts +1 -1
  184. package/dist/llm/index.d.ts.map +1 -1
  185. package/dist/llm/index.js +1 -1
  186. package/dist/llm/index.js.map +1 -1
  187. package/dist/llm/structured.d.ts +19 -0
  188. package/dist/llm/structured.d.ts.map +1 -1
  189. package/dist/llm/structured.js +61 -0
  190. package/dist/llm/structured.js.map +1 -1
  191. package/dist/mailbox/doctor.d.ts +10 -0
  192. package/dist/mailbox/doctor.d.ts.map +1 -0
  193. package/dist/mailbox/doctor.js +33 -0
  194. package/dist/mailbox/doctor.js.map +1 -0
  195. package/dist/mailbox/rule.d.ts +34 -0
  196. package/dist/mailbox/rule.d.ts.map +1 -0
  197. package/dist/mailbox/rule.js +47 -0
  198. package/dist/mailbox/rule.js.map +1 -0
  199. package/dist/mailbox/session.d.ts +5 -0
  200. package/dist/mailbox/session.d.ts.map +1 -1
  201. package/dist/mailbox/session.js +8 -0
  202. package/dist/mailbox/session.js.map +1 -1
  203. package/dist/mcp/server.d.ts +15 -5
  204. package/dist/mcp/server.d.ts.map +1 -1
  205. package/dist/mcp/server.js +75 -27
  206. package/dist/mcp/server.js.map +1 -1
  207. package/dist/mcp/tools.d.ts +194 -82
  208. package/dist/mcp/tools.d.ts.map +1 -1
  209. package/dist/mcp/tools.js +82 -8
  210. package/dist/mcp/tools.js.map +1 -1
  211. package/dist/mcp-test/adversarial.d.ts +80 -0
  212. package/dist/mcp-test/adversarial.d.ts.map +1 -0
  213. package/dist/mcp-test/adversarial.js +99 -0
  214. package/dist/mcp-test/adversarial.js.map +1 -0
  215. package/dist/mcp-test/advice.d.ts +20 -0
  216. package/dist/mcp-test/advice.d.ts.map +1 -0
  217. package/dist/mcp-test/advice.js +22 -0
  218. package/dist/mcp-test/advice.js.map +1 -0
  219. package/dist/mcp-test/call.d.ts +76 -0
  220. package/dist/mcp-test/call.d.ts.map +1 -0
  221. package/dist/mcp-test/call.js +105 -0
  222. package/dist/mcp-test/call.js.map +1 -0
  223. package/dist/mcp-test/cases.d.ts +154 -0
  224. package/dist/mcp-test/cases.d.ts.map +1 -0
  225. package/dist/mcp-test/cases.js +643 -0
  226. package/dist/mcp-test/cases.js.map +1 -0
  227. package/dist/mcp-test/connect.d.ts +70 -0
  228. package/dist/mcp-test/connect.d.ts.map +1 -0
  229. package/dist/mcp-test/connect.js +426 -0
  230. package/dist/mcp-test/connect.js.map +1 -0
  231. package/dist/mcp-test/coverage.d.ts +61 -0
  232. package/dist/mcp-test/coverage.d.ts.map +1 -0
  233. package/dist/mcp-test/coverage.js +76 -0
  234. package/dist/mcp-test/coverage.js.map +1 -0
  235. package/dist/mcp-test/discover.d.ts +40 -0
  236. package/dist/mcp-test/discover.d.ts.map +1 -0
  237. package/dist/mcp-test/discover.js +149 -0
  238. package/dist/mcp-test/discover.js.map +1 -0
  239. package/dist/mcp-test/guard.d.ts +161 -0
  240. package/dist/mcp-test/guard.d.ts.map +1 -0
  241. package/dist/mcp-test/guard.js +363 -0
  242. package/dist/mcp-test/guard.js.map +1 -0
  243. package/dist/mcp-test/model.d.ts +89 -0
  244. package/dist/mcp-test/model.d.ts.map +1 -0
  245. package/dist/mcp-test/model.js +88 -0
  246. package/dist/mcp-test/model.js.map +1 -0
  247. package/dist/mcp-test/payloads.d.ts +20 -0
  248. package/dist/mcp-test/payloads.d.ts.map +1 -0
  249. package/dist/mcp-test/payloads.js +20 -0
  250. package/dist/mcp-test/payloads.js.map +1 -0
  251. package/dist/mcp-test/report.d.ts +55 -0
  252. package/dist/mcp-test/report.d.ts.map +1 -0
  253. package/dist/mcp-test/report.js +157 -0
  254. package/dist/mcp-test/report.js.map +1 -0
  255. package/dist/mcp-test/run.d.ts +68 -0
  256. package/dist/mcp-test/run.d.ts.map +1 -0
  257. package/dist/mcp-test/run.js +467 -0
  258. package/dist/mcp-test/run.js.map +1 -0
  259. package/dist/mcp-test/runner.d.ts +133 -0
  260. package/dist/mcp-test/runner.d.ts.map +1 -0
  261. package/dist/mcp-test/runner.js +412 -0
  262. package/dist/mcp-test/runner.js.map +1 -0
  263. package/dist/mcp-test/schema.d.ts +103 -0
  264. package/dist/mcp-test/schema.d.ts.map +1 -0
  265. package/dist/mcp-test/schema.js +513 -0
  266. package/dist/mcp-test/schema.js.map +1 -0
  267. package/dist/mcp-test/secrets.d.ts +25 -0
  268. package/dist/mcp-test/secrets.d.ts.map +1 -0
  269. package/dist/mcp-test/secrets.js +67 -0
  270. package/dist/mcp-test/secrets.js.map +1 -0
  271. package/dist/observe/index.d.ts +3 -1
  272. package/dist/observe/index.d.ts.map +1 -1
  273. package/dist/observe/index.js +1 -0
  274. package/dist/observe/index.js.map +1 -1
  275. package/dist/observe/locator-hints.d.ts +18 -0
  276. package/dist/observe/locator-hints.d.ts.map +1 -0
  277. package/dist/observe/locator-hints.js +36 -0
  278. package/dist/observe/locator-hints.js.map +1 -0
  279. package/dist/observe/overlays.d.ts +135 -0
  280. package/dist/observe/overlays.d.ts.map +1 -0
  281. package/dist/observe/overlays.js +242 -0
  282. package/dist/observe/overlays.js.map +1 -0
  283. package/dist/observe/parse-aria.d.ts +7 -1
  284. package/dist/observe/parse-aria.d.ts.map +1 -1
  285. package/dist/observe/parse-aria.js +79 -4
  286. package/dist/observe/parse-aria.js.map +1 -1
  287. package/dist/probe/index.d.ts +3 -1
  288. package/dist/probe/index.d.ts.map +1 -1
  289. package/dist/probe/index.js +3 -2
  290. package/dist/probe/index.js.map +1 -1
  291. package/dist/project/index.d.ts +2 -0
  292. package/dist/project/index.d.ts.map +1 -1
  293. package/dist/project/index.js +10 -2
  294. package/dist/project/index.js.map +1 -1
  295. package/dist/prompts/local/describe-screen.d.ts +7 -0
  296. package/dist/prompts/local/describe-screen.d.ts.map +1 -0
  297. package/dist/prompts/local/describe-screen.js +29 -0
  298. package/dist/prompts/local/describe-screen.js.map +1 -0
  299. package/dist/prompts/local/index.d.ts.map +1 -1
  300. package/dist/prompts/local/index.js +7 -0
  301. package/dist/prompts/local/index.js.map +1 -1
  302. package/dist/prompts/local/name-overlays.d.ts +6 -0
  303. package/dist/prompts/local/name-overlays.d.ts.map +1 -0
  304. package/dist/prompts/local/name-overlays.js +16 -0
  305. package/dist/prompts/local/name-overlays.js.map +1 -0
  306. package/dist/prompts/local/qa-api-flows.d.ts +8 -0
  307. package/dist/prompts/local/qa-api-flows.d.ts.map +1 -0
  308. package/dist/prompts/local/qa-api-flows.js +19 -0
  309. package/dist/prompts/local/qa-api-flows.js.map +1 -0
  310. package/dist/prompts/local/qa-playwright-ts-writer.d.ts +1 -1
  311. package/dist/prompts/local/qa-playwright-ts-writer.d.ts.map +1 -1
  312. package/dist/prompts/local/qa-playwright-ts-writer.js +5 -1
  313. package/dist/prompts/local/qa-playwright-ts-writer.js.map +1 -1
  314. package/dist/prompts/local/qa-testcase-from-ui.d.ts +1 -1
  315. package/dist/prompts/local/qa-testcase-from-ui.d.ts.map +1 -1
  316. package/dist/prompts/local/qa-testcase-from-ui.js +2 -0
  317. package/dist/prompts/local/qa-testcase-from-ui.js.map +1 -1
  318. package/dist/session/index.d.ts.map +1 -1
  319. package/dist/session/index.js +24 -2
  320. package/dist/session/index.js.map +1 -1
  321. package/dist/validate/index.d.ts +11 -0
  322. package/dist/validate/index.d.ts.map +1 -1
  323. package/dist/validate/index.js +21 -0
  324. package/dist/validate/index.js.map +1 -1
  325. package/dist/validate/runner.d.ts +15 -1
  326. package/dist/validate/runner.d.ts.map +1 -1
  327. package/dist/validate/runner.js +158 -25
  328. package/dist/validate/runner.js.map +1 -1
  329. package/dist/validate/write-guard.d.ts +24 -0
  330. package/dist/validate/write-guard.d.ts.map +1 -0
  331. package/dist/validate/write-guard.js +210 -0
  332. package/dist/validate/write-guard.js.map +1 -0
  333. package/dist/view/index.d.ts +9 -0
  334. package/dist/view/index.d.ts.map +1 -0
  335. package/dist/view/index.js +126 -0
  336. package/dist/view/index.js.map +1 -0
  337. package/package.json +3 -2
@@ -1,32 +1,191 @@
1
1
  import { chromium } from "playwright";
2
+ import { CLICK_EFFECT_WINDOW_MS, DEAD_CLICK_RECHECK_MS, REQUEST_ANSWER_MS, WATCH_KEY, clickEffect, SENDS_PAST_FETCH, changesServer, clickFailure, recordedPath, recordedUrl, watchScript, } from "../click-effect.js";
2
3
  import { isMissingBrowserError, missingBrowsersError } from "../preflight.js";
3
4
  import { navigateWithRecovery } from "../recovery.js";
4
- import { parseAriaSnapshot } from "../../observe/parse-aria.js";
5
+ import { overlayKey, parseAriaSnapshot } from "../../observe/parse-aria.js";
6
+ /**
7
+ * #226: the one visible element in the element's scope — never the first of several. One visible match is it. Several
8
+ * are narrowed by the accessible name of the row, card or section they sit in (nearest first), taking the first
9
+ * container after which exactly one is left. Links that all lead to the same address are one destination. Otherwise
10
+ * `ambiguous`: the caller does not click. With no visible match, the locator is of all of them and picks none: a hidden
11
+ * or removed element still fails with Playwright's own reason, and several that come back while it waits are refused by
12
+ * its strict mode rather than clicked blindly.
13
+ */
14
+ async function findOne(page, t) {
15
+ const visible = locate(page, t).filter({ visible: true });
16
+ const count = await visible.count().catch(() => 0);
17
+ if (count === 0)
18
+ return { locator: locate(page, t), count: 0 };
19
+ if (count === 1)
20
+ return { locator: visible, count };
21
+ const root = t.scope ? page.getByRole(t.scope.role, t.scope.name ? { name: t.scope.name, exact: true } : {}) : page;
22
+ for (const ctx of t.context ?? []) {
23
+ const inner = root
24
+ .getByRole(ctx.role, ctx.name ? { name: ctx.name, exact: true } : {})
25
+ .getByRole(t.role, t.name ? { name: t.name, exact: true } : {})
26
+ .filter({ visible: true });
27
+ if ((await inner.count().catch(() => 0)) === 1)
28
+ return { locator: inner, count, narrowedBy: ctx };
29
+ }
30
+ if (t.role === "link") {
31
+ const hrefs = await visible.evaluateAll((els) => els.map((e) => e.getAttribute("href"))).catch(() => []);
32
+ if (hrefs.length > 0 && hrefs[0] && hrefs.every((h) => h === hrefs[0]))
33
+ return { locator: visible.first(), count };
34
+ }
35
+ return { locator: visible.first(), count, ambiguous: true };
36
+ }
37
+ /**
38
+ * #225: the locator of an element — inside its dialog when it has one, so a same-named element on the page is not it.
39
+ * `includeHidden` looks for what is not shown (to tell a hidden element from a gone one).
40
+ */
41
+ function locate(page, t, includeHidden = false) {
42
+ const own = { ...(t.name ? { name: t.name, exact: true } : {}), ...(includeHidden ? { includeHidden: true } : {}) };
43
+ const root = t.scope
44
+ ? page.getByRole(t.scope.role, t.scope.name ? { name: t.scope.name, exact: true } : {})
45
+ : page;
46
+ return root.getByRole(t.role, own);
47
+ }
5
48
  /**
6
49
  * PRIMARY backend (ADR-0003): in-process Playwright. Owns storageState; captures ariaSnapshot+screenshot;
7
50
  * runs tests (Sprint 3). act() resolves ref→getByRole(role,{name}) based on the last observe().
8
51
  */
9
52
  /** How long getState waits on a visible element that detaches mid-read (#213). */
10
53
  const STATE_READ_TIMEOUT_MS = 2_000;
54
+ /** #224: how often a click that looks dead is read again, until DEAD_CLICK_RECHECK_MS. */
55
+ const RECHECK_STEP_MS = 100;
56
+ /** #224: how long the element observed a moment ago may take to be found for the page-side watch; when it is not
57
+ * there, the click itself says why. */
58
+ const WATCH_INSTALL_MS = 500;
59
+ /** #224: how long reading the page-side watch may take. A page on its way to another document answers no script
60
+ * until that document arrives, which may be never; the click is then unknown, not waited for. */
61
+ const WATCH_READ_MS = 500;
62
+ /** #224: a request the page sent this often (twice) within this long, outside any action, is a poll. */
63
+ const POLL_MEMORY_MS = 10_000;
64
+ /** Requests waited for while in flight, whatever their origin: they may render when they answer. */
65
+ const WAITED_REQUESTS = new Set(["document", "fetch", "xhr", "script"]);
66
+ /** …of which the page's own navigations and API calls are recorded — not scripts, images, fonts or beacons. */
67
+ const RECORDED_REQUESTS = new Set(["document", "fetch", "xhr"]);
68
+ /** The Blink features every browser of this backend runs without. */
69
+ const BLINK_OFF = "AutomationControlled";
70
+ /**
71
+ * #225 review 5: how long reading the crawler's session for the write guard may take. `storageState()` with IndexedDB has
72
+ * no limit of its own, and a page with a blocked IndexedDB upgrade held it past 240 s. Measured on a laptop: 300 MB read in
73
+ * 2.4 s, and 200 MB is already more than the browser that presses can be given. Ten seconds leave a machine four times
74
+ * slower room for more than could ever be used.
75
+ */
76
+ const SESSION_READ_TIMEOUT_MS = 10_000;
77
+ const guardFailure = (code) => Object.assign(new Error(`The write guard did not start: ${code}`), { code });
78
+ const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
79
+ /** `p`, or `fallback` when it fails or takes longer than `ms`. */
80
+ const within = (p, ms, fallback) => Promise.race([p.catch(() => fallback), pause(ms).then(() => fallback)]);
81
+ /** The page's ARIA snapshot, or undefined when it cannot be read (mid-navigation, page gone). */
82
+ const ariaOf = (page) => page.locator("body").ariaSnapshot({ timeout: STATE_READ_TIMEOUT_MS }).catch(() => undefined);
83
+ /** #225 review 4: runs in the crawler's page: its tab's sessionStorage, which no storageState holds. */
84
+ const readTabStorage = () => {
85
+ const g = globalThis;
86
+ return { origin: g.location.origin, items: Object.entries(g.sessionStorage) };
87
+ };
88
+ /** #225 review 4: runs before a page's scripts in the pressing context: the session is there when the app looks for it. */
89
+ const seedTabStorage = (tab) => {
90
+ const g = globalThis;
91
+ if (g.location.origin !== tab.origin)
92
+ return;
93
+ try {
94
+ for (const [k, v] of tab.items)
95
+ if (g.sessionStorage.getItem(k) === null)
96
+ g.sessionStorage.setItem(k, v);
97
+ }
98
+ catch {
99
+ // a sandboxed frame has no storage to fill
100
+ }
101
+ };
102
+ /**
103
+ * Only the app's own origin is recorded: an analytics call on another host answering 204 to every click would make
104
+ * every dead click look like a silent save. Kept simple on purpose: an API on another origin (api.example.com for app.example.com)
105
+ * is waited for but neither recorded nor counted; compare registrable domains instead if that matters.
106
+ */
107
+ function sameOrigin(a, b) {
108
+ try {
109
+ return new URL(a).origin === new URL(b).origin;
110
+ }
111
+ catch {
112
+ return false;
113
+ }
114
+ }
115
+ /** One endpoint, whatever its query: a poll often adds a timestamp. */
116
+ function requestKey(r) {
117
+ try {
118
+ const u = new URL(r.url());
119
+ return `${r.method()} ${u.origin}${u.pathname}`;
120
+ }
121
+ catch {
122
+ return `${r.method()} ${r.url()}`;
123
+ }
124
+ }
125
+ /**
126
+ * #229: one response, handed to the recorder; its body and its full headers are read only when the recorder asks (a JSON
127
+ * answer, the API's own traffic). `allHeaders` because `headers()` leaves the cookies out. An answer a service worker
128
+ * gave is the worker's, not the API's.
129
+ */
130
+ function noteResponse(traffic, res) {
131
+ try {
132
+ if (res.fromServiceWorker())
133
+ return;
134
+ const req = res.request();
135
+ const headers = res.headers();
136
+ const size = Number(headers["content-length"]);
137
+ traffic.note({
138
+ method: req.method(),
139
+ url: res.url(),
140
+ resourceType: req.resourceType(),
141
+ status: res.status(),
142
+ requestHeaders: req.headers(),
143
+ allHeaders: async () => [...Object.entries(await req.allHeaders()), ...Object.entries(await res.allHeaders())],
144
+ postData: req.postData(),
145
+ responseContentType: headers["content-type"],
146
+ ...(Number.isFinite(size) ? { responseSize: size } : {}),
147
+ body: () => res.text(),
148
+ });
149
+ }
150
+ catch {
151
+ // a response of a page already gone: nothing to record
152
+ }
153
+ }
11
154
  export class PlaywrightLibBackend {
12
155
  opts;
13
156
  browser;
14
157
  context;
15
158
  page;
16
159
  refMap = new Map();
160
+ /** #225: the dialogs of the last snapshot that the DOM says are not modal (`role|name`). */
161
+ nonModal = new Set();
17
162
  currentUrl = "";
18
163
  lastStatus;
19
164
  consoleErrors = [];
165
+ /** #224: the page's ARIA snapshot as last read — the "before" a watched click's changes are compared with. */
166
+ lastAria;
167
+ /** #224: an action is running; requests sent meanwhile are its own, not the page's background. */
168
+ acting = false;
169
+ /** #224: when each endpoint was requested outside any action, to tell a poll from a click's request. */
170
+ background = new Map();
171
+ /**
172
+ * #225 review 4: while the write guard is on, a second backend in a browser process of its own, which takes every
173
+ * observe, act, verify and getState. This one's context, page and fields are not touched until it is gone.
174
+ */
175
+ pressing;
176
+ /** #225 review 4: on a pressing backend, the process of its browser, to kill. */
177
+ server;
178
+ /** #225 review 3: the element (or key) pressed last, named beside each request the guard stops. */
179
+ lastPressed;
20
180
  constructor(opts = {}) {
21
181
  this.opts = opts;
22
182
  }
183
+ launchOptions(blinkOff) {
184
+ return { headless: this.opts.headless ?? true, channel: this.opts.channel, args: [`--disable-blink-features=${blinkOff}`] };
185
+ }
23
186
  async launch() {
24
187
  try {
25
- return await chromium.launch({
26
- headless: this.opts.headless ?? true,
27
- channel: this.opts.channel,
28
- args: ["--disable-blink-features=AutomationControlled"],
29
- });
188
+ return await chromium.launch(this.launchOptions(BLINK_OFF));
30
189
  }
31
190
  catch (e) {
32
191
  // Backstop for observe/design: translate Playwright's raw "Executable doesn't exist …" into
@@ -37,13 +196,21 @@ export class PlaywrightLibBackend {
37
196
  throw e;
38
197
  }
39
198
  }
199
+ /** A context with this backend's options: the crawler's, and the one the write guard presses in. */
200
+ newContext(storageState) {
201
+ return this.browser.newContext({
202
+ ...(storageState ? { storageState } : {}),
203
+ ...(this.opts.httpCredentials ? { httpCredentials: this.opts.httpCredentials } : {}),
204
+ });
205
+ }
40
206
  async ensurePage() {
41
207
  this.browser ??= await this.launch();
42
208
  if (!this.context) {
43
- this.context = await this.browser.newContext({
44
- ...(this.opts.storageState ? { storageState: this.opts.storageState } : {}),
45
- ...(this.opts.httpCredentials ? { httpCredentials: this.opts.httpCredentials } : {}),
46
- });
209
+ this.context = await this.newContext(this.opts.storageState);
210
+ // Only here: the browser the write guard presses in sets its context itself, so what it reads stays out of the draft.
211
+ const traffic = this.opts.apiTraffic;
212
+ if (traffic)
213
+ this.context.on("response", (res) => noteResponse(traffic, res));
47
214
  }
48
215
  if (!this.page) {
49
216
  this.page = await this.context.newPage();
@@ -52,6 +219,7 @@ export class PlaywrightLibBackend {
52
219
  this.consoleErrors.push(m.text());
53
220
  });
54
221
  this.page.on("pageerror", (e) => this.consoleErrors.push(e.message));
222
+ this.page.on("request", (r) => this.noteBackground(r));
55
223
  }
56
224
  return this.page;
57
225
  }
@@ -85,9 +253,12 @@ export class PlaywrightLibBackend {
85
253
  await this.page?.close().catch(() => undefined);
86
254
  this.page = undefined;
87
255
  this.refMap.clear();
256
+ this.lastAria = undefined;
88
257
  await this.ensurePage();
89
258
  }
90
259
  async observe(opts) {
260
+ if (this.pressing)
261
+ return this.pressing.observe(opts);
91
262
  let status;
92
263
  if (opts.url) {
93
264
  this.lastStatus = undefined;
@@ -114,10 +285,13 @@ export class PlaywrightLibBackend {
114
285
  if (!opts.url)
115
286
  this.currentUrl = page.url();
116
287
  const ariaSnapshot = await page.locator("body").ariaSnapshot();
288
+ this.lastAria = ariaSnapshot;
117
289
  const buf = await page.screenshot({ fullPage: opts.fullPage ?? false });
290
+ this.nonModal = await this.nonModalDialogs(page, ariaSnapshot);
291
+ const layers = await this.openLayers(page);
118
292
  this.refMap.clear();
119
- for (const el of parseAriaSnapshot(ariaSnapshot)) {
120
- this.refMap.set(el.ref, { role: el.role, name: el.name });
293
+ for (const el of parseAriaSnapshot(ariaSnapshot, { nonModal: this.nonModal })) {
294
+ this.refMap.set(el.ref, { role: el.role, name: el.name, ...(el.scope ? { scope: el.scope } : {}), ...(el.underOverlay ? { underOverlay: true } : {}), ...(el.context ? { context: el.context } : {}) });
121
295
  }
122
296
  return {
123
297
  url: this.currentUrl || page.url(),
@@ -125,10 +299,85 @@ export class PlaywrightLibBackend {
125
299
  ariaSnapshot,
126
300
  capturedBy: "lib",
127
301
  consoleErrors: [...this.consoleErrors],
302
+ nonModal: [...this.nonModal],
303
+ ...(layers.length > 0 ? { layers } : {}),
128
304
  ...(status !== undefined ? { status } : {}),
129
305
  };
130
306
  }
307
+ /**
308
+ * Dialog-like layers the ARIA snapshot does not show as dialogs (a plain `div` modal open on load): visible, fixed
309
+ * or absolute, with a positive z-index, covering at least half the viewport (or marked aria-modal), and holding no dialog, menu or
310
+ * listbox of its own (those the snapshot already has). The outermost one of each stack. A heuristic: a page that
311
+ * cannot be read gives none.
312
+ */
313
+ async openLayers(page) {
314
+ return page
315
+ .evaluate(() => {
316
+ /* eslint-disable @typescript-eslint/no-explicit-any */
317
+ const doc = globalThis.document;
318
+ const win = globalThis;
319
+ const area = win.innerWidth * win.innerHeight;
320
+ const picked = [];
321
+ for (const n of doc.body.querySelectorAll(":scope > *, :scope > * > *, :scope > * > * > *")) {
322
+ const cs = win.getComputedStyle(n);
323
+ if ((cs.position !== "fixed" && cs.position !== "absolute") || !(parseInt(cs.zIndex, 10) > 0))
324
+ continue;
325
+ if (cs.display === "none" || cs.visibility === "hidden" || Number(cs.opacity) === 0)
326
+ continue;
327
+ const r = n.getBoundingClientRect();
328
+ const w = Math.min(r.right, win.innerWidth) - Math.max(r.left, 0);
329
+ const h = Math.min(r.bottom, win.innerHeight) - Math.max(r.top, 0);
330
+ if (w <= 0 || h <= 0 || (w * h < area / 2 && n.getAttribute("aria-modal") !== "true"))
331
+ continue;
332
+ if (n.closest("[aria-hidden=true],[role=dialog],[role=alertdialog],dialog,[role=menu],[role=listbox]"))
333
+ continue;
334
+ if (n.querySelector("[role=dialog],[role=alertdialog],dialog,[role=menu],[role=listbox]"))
335
+ continue;
336
+ if (picked.some((p) => p.contains(n)))
337
+ continue;
338
+ picked.push(n);
339
+ }
340
+ const text = (n) => String(n.getAttribute("aria-label") || n.value || n.textContent || "").replace(/\s+/g, " ").trim().slice(0, 80);
341
+ return picked.map((n) => {
342
+ const heading = n.querySelector("h1,h2,h3,h4,h5,h6");
343
+ const name = n.getAttribute("aria-label") || (heading ? text(heading) : "");
344
+ const elements = [];
345
+ for (const c of n.querySelectorAll("button,a[href],input,select,textarea,[role=button],[role=link]")) {
346
+ const tag = c.tagName.toLowerCase();
347
+ const role = c.getAttribute("role") || (tag === "a" ? "link" : tag === "button" ? "button" : tag === "select" ? "combobox" : "textbox");
348
+ const label = text(c);
349
+ elements.push({ role, ...(label ? { name: label } : {}) });
350
+ }
351
+ return { ...(name ? { name } : {}), elements };
352
+ });
353
+ })
354
+ .catch(() => []);
355
+ }
356
+ /**
357
+ * #225: which dialogs of the snapshot are not modal. The ARIA snapshot does not say: the DOM does (`aria-modal`, or
358
+ * a native `<dialog>` opened with showModal()). A page whose DOM cannot be read keeps every dialog modal.
359
+ */
360
+ async nonModalDialogs(page, aria) {
361
+ const out = new Set();
362
+ for (const el of parseAriaSnapshot(aria)) {
363
+ if (el.role !== "dialog" && el.role !== "alertdialog")
364
+ continue;
365
+ const loc = locate(page, { role: el.role, name: el.name }).first();
366
+ const modal = await loc
367
+ .evaluate((node) => {
368
+ const n = node;
369
+ return n.getAttribute("aria-modal") === "true" || n.matches(":modal") || n.getAttribute("role") === "alertdialog";
370
+ }, undefined, { timeout: 1_000 })
371
+ .catch(() => true);
372
+ if (!modal)
373
+ out.add(overlayKey(el.role, el.name));
374
+ }
375
+ return out;
376
+ }
131
377
  async act(action) {
378
+ if (this.pressing)
379
+ return this.pressing.act(action);
380
+ this.acting = true;
132
381
  try {
133
382
  const page = await this.ensurePage();
134
383
  if (action.kind === "navigate") {
@@ -136,46 +385,314 @@ export class PlaywrightLibBackend {
136
385
  this.currentUrl = action.url;
137
386
  return { ok: true };
138
387
  }
388
+ if (action.kind === "press") {
389
+ this.lastPressed = { role: "key", name: action.key };
390
+ await page.keyboard.press(action.key);
391
+ return { ok: true };
392
+ }
393
+ if (action.kind === "click-outside") {
394
+ const point = await this.safePointOutside(page, action.scope);
395
+ if (!point)
396
+ return { ok: false, error: "no point outside the overlay that is safe to click; click outside not tried" };
397
+ this.lastPressed = { role: "click-outside", ...(action.scope.name !== undefined ? { name: action.scope.name } : {}) };
398
+ await page.mouse.click(point.x, point.y);
399
+ return { ok: true };
400
+ }
139
401
  const target = this.refMap.get(action.ref);
140
402
  if (!target) {
141
403
  return { ok: false, ref: action.ref, error: `Unknown ref '${action.ref}' — call observe() first.` };
142
404
  }
143
- const locator = page
144
- .getByRole(target.role, target.name ? { name: target.name, exact: true } : {})
145
- .first();
146
- if (action.kind === "click")
147
- await locator.click(action.timeoutMs === undefined ? undefined : { timeout: action.timeoutMs });
148
- else
405
+ if (target.underOverlay) {
406
+ // #225: a modal overlay is open and this element lies under it: never touched, the click would only time out.
407
+ return {
408
+ ok: false,
409
+ ref: action.ref,
410
+ error: `${target.role}${target.name ? ` "${target.name}"` : ""} lies under an open modal overlay; close it first.`,
411
+ outcome: "under-overlay",
412
+ };
413
+ }
414
+ const found = await findOne(page, target);
415
+ if (found.ambiguous) {
416
+ // #226: several visible elements and nothing tells them apart: no click at all rather than a blind first one.
417
+ return {
418
+ ok: false,
419
+ ref: action.ref,
420
+ error: `${found.count} visible ${target.role}${target.name ? ` "${target.name}"` : ""} elements and nothing tells them apart (no named row, card or section); not clicked.`,
421
+ outcome: "ambiguous",
422
+ ambiguous: { role: target.role, ...(target.name !== undefined ? { name: target.name } : {}), count: found.count, ...(target.scope ? { scope: target.scope } : {}) },
423
+ };
424
+ }
425
+ const locator = found.locator;
426
+ if (action.kind === "fill") {
149
427
  await locator.fill(action.value);
150
- return { ok: true, ref: action.ref };
428
+ return { ok: true, ref: action.ref };
429
+ }
430
+ this.lastPressed = { role: target.role, ...(target.name !== undefined ? { name: target.name } : {}) };
431
+ if (action.watch === false) {
432
+ await locator.click(action.timeoutMs === undefined ? undefined : { timeout: action.timeoutMs });
433
+ return { ok: true, ref: action.ref };
434
+ }
435
+ const effect = await this.clickAndWatch(page, locator, target, action.timeoutMs);
436
+ return { ok: true, ref: action.ref, outcome: effect.outcome, effect };
151
437
  }
152
438
  catch (e) {
153
439
  const ref = "ref" in action ? action.ref : undefined;
154
- return { ok: false, ref, error: e.message };
440
+ const message = e.message;
441
+ let cause = action.kind === "click" ? clickFailure(message) : undefined;
442
+ if (cause === "not-found" && ref)
443
+ cause = await this.hiddenOrGone(ref);
444
+ return { ok: false, ref, error: message, ...(cause ? { outcome: cause } : {}) };
445
+ }
446
+ finally {
447
+ this.acting = false;
155
448
  }
156
449
  }
450
+ /**
451
+ * #225 review: a point to click "outside" the overlay `scope`. A blind corner click pressed a fixed «Sign out» link,
452
+ * so each candidate point is checked first: what `elementFromPoint` finds there must lie outside the overlay and be
453
+ * nothing a click acts on — no link, button, field, label, summary, element with a click role, a tabindex, an inline
454
+ * handler, or a pointer cursor. Corners first, then the edges, then a grid; undefined when none is safe.
455
+ */
456
+ async safePointOutside(page, scope) {
457
+ const overlay = locate(page, scope).first();
458
+ const point = await overlay
459
+ .evaluate((node) => {
460
+ const doc = globalThis.document;
461
+ const win = globalThis;
462
+ const overlayEl = node;
463
+ const ACTS = "a[href],button,input,select,textarea,label,summary,option,[contenteditable=''],[contenteditable='true'],[onclick],[tabindex]:not([tabindex='-1'])," +
464
+ ["button", "link", "checkbox", "radio", "switch", "tab", "menuitem", "menuitemcheckbox", "menuitemradio", "option", "treeitem", "gridcell", "combobox", "textbox", "slider", "spinbutton", "searchbox"]
465
+ .map((r) => `[role='${r}']`)
466
+ .join(",");
467
+ const w = win.innerWidth;
468
+ const h = win.innerHeight;
469
+ const xs = [2, w - 3, Math.round(w / 2)];
470
+ const ys = [2, h - 3, Math.round(h / 2)];
471
+ const points = [];
472
+ for (const y of [ys[0], ys[1]])
473
+ for (const x of [xs[0], xs[1]])
474
+ points.push([x, y]);
475
+ for (const [x, y] of [[xs[2], ys[0]], [xs[2], ys[1]], [xs[0], ys[2]], [xs[1], ys[2]]])
476
+ points.push([x, y]);
477
+ for (let gy = 1; gy < 8; gy++)
478
+ for (let gx = 1; gx < 8; gx++)
479
+ points.push([Math.round((w * gx) / 8), Math.round((h * gy) / 8)]);
480
+ for (const [x, y] of points) {
481
+ const el = doc.elementFromPoint(x, y);
482
+ if (!el || overlayEl.contains(el) || el.closest(ACTS))
483
+ continue;
484
+ let pointer = false;
485
+ for (let e = el; e && !pointer; e = e.parentElement) {
486
+ if (e === overlayEl)
487
+ break;
488
+ pointer = win.getComputedStyle(e).cursor === "pointer";
489
+ }
490
+ if (!pointer)
491
+ return { x, y };
492
+ }
493
+ return null;
494
+ }, undefined, { timeout: STATE_READ_TIMEOUT_MS })
495
+ .catch(() => null);
496
+ return point ?? undefined;
497
+ }
498
+ /** #224: nothing matched the element — it is still there, hidden (not-visible), or it is gone (not-found). */
499
+ async hiddenOrGone(ref) {
500
+ const target = this.refMap.get(ref);
501
+ if (!target || !this.page)
502
+ return "not-found";
503
+ const hidden = await locate(this.page, target, true)
504
+ .count()
505
+ .catch(() => 0);
506
+ return hidden > 0 ? "not-visible" : "not-found";
507
+ }
508
+ /** #224: a request started while no action runs; one endpoint seen twice within POLL_MEMORY_MS is a poll. */
509
+ noteBackground(r) {
510
+ if (this.acting || !WAITED_REQUESTS.has(r.resourceType()))
511
+ return;
512
+ const now = Date.now();
513
+ const key = requestKey(r);
514
+ this.background.set(key, [...(this.background.get(key) ?? []).filter((t) => now - t < POLL_MEMORY_MS), now].slice(-2));
515
+ if (this.background.size > 500) {
516
+ for (const [k, times] of this.background)
517
+ if (now - (times.at(-1) ?? 0) >= POLL_MEMORY_MS)
518
+ this.background.delete(k);
519
+ }
520
+ }
521
+ isPoll(r) {
522
+ const now = Date.now();
523
+ return (this.background.get(requestKey(r)) ?? []).filter((t) => now - t < POLL_MEMORY_MS).length >= 2;
524
+ }
525
+ /**
526
+ * #224: click, then record what changed. Before the click a page-side watch notes the element's state, the focus
527
+ * and the scroll, and starts noting DOM changes; the backend listens for requests, a new tab and a download. After
528
+ * the click it waits CLICK_EFFECT_WINDOW_MS, and for the requests in flight up to REQUEST_ANSWER_MS; it reads the
529
+ * ARIA snapshot again only when the DOM changed. A click that looks dead is read again until DEAD_CLICK_RECHECK_MS.
530
+ * Only the click itself can throw: once it is made, a read that fails makes the outcome unknown, not a failure.
531
+ */
532
+ async clickAndWatch(page, locator, target, timeoutMs) {
533
+ const from = page.url();
534
+ const before = this.lastAria;
535
+ const watched = await this.installWatch(page, locator);
536
+ const traffic = this.watchTraffic(page, from);
537
+ try {
538
+ await locator.click(timeoutMs === undefined ? undefined : { timeout: timeoutMs });
539
+ const clicked = Date.now();
540
+ await pause(CLICK_EFFECT_WINDOW_MS);
541
+ let after;
542
+ for (;;) {
543
+ // The answers render after they arrive: give them the same window before reading the page again.
544
+ if (await traffic.settle(clicked + REQUEST_ANSWER_MS))
545
+ await pause(CLICK_EFFECT_WINDOW_MS);
546
+ // A page whose next document is still on its way is not read: it would answer only once that document came.
547
+ const navigating = traffic.navigating();
548
+ const seen = watched && !navigating ? await within(page.evaluate(watchScript.read), WATCH_READ_MS, null) : null;
549
+ const url = page.url(); // after the read: a document that arrived meanwhile counts as navigated
550
+ if (seen?.fresh && url === from)
551
+ after = await ariaOf(page);
552
+ const effect = clickEffect({
553
+ page: from,
554
+ url,
555
+ ...target,
556
+ ...traffic.elsewhere(),
557
+ ...(seen ? { seen } : {}),
558
+ before,
559
+ after,
560
+ requests: traffic.recorded(),
561
+ navigating,
562
+ stopped: traffic.stopped(),
563
+ });
564
+ // A link into another tab is given as long as a request: the browser can take more than a second to open it.
565
+ if (effect.outcome !== "no-effect" || Date.now() - clicked >= (watched?.newTab ? REQUEST_ANSWER_MS : DEAD_CLICK_RECHECK_MS)) {
566
+ if (after !== undefined)
567
+ this.lastAria = after;
568
+ return effect;
569
+ }
570
+ await pause(RECHECK_STEP_MS);
571
+ }
572
+ }
573
+ finally {
574
+ traffic.stop();
575
+ if (!traffic.navigating())
576
+ await within(page.evaluate(watchScript.remove), WATCH_READ_MS, undefined); // a leaving page takes it along
577
+ }
578
+ }
579
+ /**
580
+ * Puts the page-side watch in place; undefined when it could not be (the element is not there, the page is
581
+ * leaving). `newTab`: the element is in a link that opens its page in another tab (`target="_blank"` or a name).
582
+ */
583
+ async installWatch(page, locator) {
584
+ try {
585
+ const newTab = await locator.evaluate((el, key) => {
586
+ globalThis[key] = { target: el };
587
+ const link = el.closest("a[href][target], area[href][target]");
588
+ return !!link && !["", "_self", "_parent", "_top"].includes(link.target.toLowerCase());
589
+ }, WATCH_KEY, { timeout: WATCH_INSTALL_MS });
590
+ await page.evaluate(watchScript.install);
591
+ return { newTab };
592
+ }
593
+ catch {
594
+ return undefined;
595
+ }
596
+ }
597
+ /** The requests a click starts (polls left out), the tab it opens and the file it downloads; the tab is closed again. */
598
+ watchTraffic(page, from) {
599
+ const started = [];
600
+ let tab;
601
+ let download;
602
+ const onRequest = (r) => {
603
+ if (!WAITED_REQUESTS.has(r.resourceType()) || this.isPoll(r))
604
+ return;
605
+ // #252: in the browser that presses, the write guard stops every such request: it never reached the server, so it
606
+ // is no request of the run (it is in `blocked`), and the click it followed cannot be judged without its answer.
607
+ const stopped = this.server !== undefined && changesServer(r.method());
608
+ const entry = { r, done: false, recorded: !stopped && RECORDED_REQUESTS.has(r.resourceType()) && sameOrigin(r.url(), from), stopped };
609
+ started.push(entry);
610
+ void r
611
+ .response()
612
+ .then((res) => {
613
+ if (res)
614
+ entry.status = res.status();
615
+ }, () => undefined)
616
+ .finally(() => {
617
+ entry.done = true;
618
+ });
619
+ };
620
+ const onPopup = (p) => {
621
+ tab ??= recordedUrl(p.url());
622
+ void p.close().catch(() => undefined);
623
+ };
624
+ const onDownload = (d) => {
625
+ download ??= d.suggestedFilename();
626
+ void d.cancel().catch(() => undefined);
627
+ };
628
+ page.on("request", onRequest);
629
+ page.on("popup", onPopup);
630
+ page.on("download", onDownload);
631
+ return {
632
+ /** Waits while a request is in flight, until `deadline`; true when there was one to wait for. */
633
+ async settle(deadline) {
634
+ if (started.every((e) => e.done))
635
+ return false;
636
+ while (started.some((e) => !e.done) && Date.now() < deadline)
637
+ await pause(50);
638
+ return true;
639
+ },
640
+ elsewhere: () => ({ ...(tab ? { tab } : {}), ...(download ? { download } : {}) }),
641
+ recorded: () => started
642
+ .filter((e) => e.recorded)
643
+ .map((e) => ({ method: e.r.method(), path: recordedPath(e.r.url()), ...(e.status !== undefined ? { status: e.status } : {}) })),
644
+ navigating: () => started.some((e) => !e.done && e.r.isNavigationRequest() && e.r.frame() === page.mainFrame()),
645
+ stopped: () => started.some((e) => e.stopped),
646
+ stop: () => {
647
+ page.off("request", onRequest);
648
+ page.off("popup", onPopup);
649
+ page.off("download", onDownload);
650
+ },
651
+ };
652
+ }
157
653
  async verify(elements) {
654
+ if (this.pressing)
655
+ return this.pressing.verify(elements);
158
656
  const page = await this.ensurePage();
159
657
  const out = [];
160
658
  for (const el of elements) {
161
659
  let count = -1;
162
660
  try {
163
- count = await page
164
- .getByRole(el.role, el.name ? { name: el.name, exact: true } : {})
165
- .count();
661
+ const found = await findOne(page, el);
662
+ // outside the page, where no scrolling reaches: a skip link parked at `top: -10em`
663
+ const offViewport = found.count === 1 &&
664
+ (await found.locator
665
+ .evaluate((n) => {
666
+ const w = globalThis;
667
+ const r = n.getBoundingClientRect();
668
+ return r.right + w.scrollX <= 0 || r.bottom + w.scrollY <= 0;
669
+ }, undefined, { timeout: 1_000 })
670
+ .catch(() => false));
671
+ out.push({
672
+ ...el,
673
+ count: found.count,
674
+ verified: found.count === 1 || found.narrowedBy !== undefined,
675
+ ...(offViewport ? { offViewport: true } : {}),
676
+ ...(found.narrowedBy ? { narrowedBy: found.narrowedBy } : {}),
677
+ ...(found.ambiguous ? { ambiguous: true } : {}),
678
+ });
679
+ continue;
166
680
  }
167
681
  catch {
168
682
  count = -1;
169
683
  }
170
- out.push({ ...el, count, verified: count === 1 });
684
+ out.push({ ...el, count, verified: false });
171
685
  }
172
686
  return out;
173
687
  }
174
688
  async getState(el) {
689
+ if (this.pressing)
690
+ return this.pressing.getState(el);
175
691
  const page = await this.ensurePage();
176
- const loc = page
177
- .getByRole(el.role, el.name ? { name: el.name, exact: true } : {})
178
- .first();
692
+ const found = await findOne(page, el);
693
+ if (found.ambiguous)
694
+ return { visible: false, enabled: false, ambiguous: found.count }; // not told apart: nothing is read from a blind first one
695
+ const loc = found.locator;
179
696
  const visible = await loc.isVisible().catch(() => false);
180
697
  // #213: an element of another view (exploreStates) is not on the page, and isEnabled/isChecked wait for it
181
698
  // with Playwright's 30 s default - per element, minutes for a page of views. A hidden element is not read.
@@ -189,7 +706,137 @@ export class PlaywrightLibBackend {
189
706
  checked = undefined; // not checkable, or gone since isVisible
190
707
  }
191
708
  }
192
- return { visible, enabled, checked };
709
+ // #225 review: what the element says it opens; only such an element is pressed to look for an overlay.
710
+ // #225 review 2: and whether pressing it submits a form (a submit button inside a form), which is never pressed.
711
+ const read = visible
712
+ ? await loc
713
+ .evaluate((node) => {
714
+ const n = node;
715
+ const hasPopup = n.getAttribute("aria-haspopup");
716
+ const expanded = n.getAttribute("aria-expanded");
717
+ const controls = n.getAttribute("aria-controls");
718
+ const tag = n.tagName.toLowerCase();
719
+ // `type` is the property: a <button> with no (or an unknown) type attribute reads "submit".
720
+ const submitter = (tag === "button" && n.type === "submit") || (tag === "input" && (n.type === "submit" || n.type === "image"));
721
+ return {
722
+ popup: {
723
+ ...(hasPopup !== null && hasPopup !== "false" ? { hasPopup: hasPopup || "true" } : {}),
724
+ ...(expanded === "true" || expanded === "false" ? { expanded: expanded === "true" } : {}),
725
+ ...(controls ? { controls } : {}),
726
+ },
727
+ submitsForm: submitter && !!n.form,
728
+ // #24: what the docs call a required field
729
+ required: n.required === true || n.getAttribute("aria-required") === "true",
730
+ };
731
+ }, undefined, { timeout: STATE_READ_TIMEOUT_MS })
732
+ .catch(() => undefined)
733
+ : undefined;
734
+ const popup = read?.popup;
735
+ return {
736
+ visible,
737
+ enabled,
738
+ checked,
739
+ ...(popup && Object.keys(popup).length > 0 ? { popup } : {}),
740
+ ...(read?.submitsForm ? { submitsForm: true } : {}),
741
+ ...(read?.required ? { required: true } : {}),
742
+ };
743
+ }
744
+ /**
745
+ * #225 review 4: the write guard has no release moment. Pressing happens in a throwaway browser process, in a context
746
+ * made from the crawler's storage with the same options. Before that context exists, a Fetch interception on the
747
+ * browser itself is on, and it is never taken off: every request whose method is not GET, HEAD or OPTIONS — from a
748
+ * page, a tab it opens, a frame, any worker — is aborted (a form post, a fetch or XHR write, a beacon, whatever the
749
+ * button that sent it was called) and recorded with the element pressed last before it. `release` kills the process.
750
+ * Nothing flows back: the crawler's own context and page never saw a press.
751
+ *
752
+ * Why not a route on a context, closed at the end: a route's interception belongs to each page, frame and worker, and
753
+ * goes when they go. What it holds is then let go: POSTs reached a probe server with the route on from a popup closing
754
+ * itself, a cross-origin frame removed, a context closing (in full Chromium and Chrome), and also from a SharedWorker
755
+ * and fetchLater, which it never saw. The browser's own interception saw them all, and a killed process runs no teardown.
756
+ * Not covered: WebSocket messages, a GET that changes the server against HTTP's rule, and one POST the app has no hand in:
757
+ * on a configured channel (full Chromium) over HTTPS, the browser's own Reporting API report (`Reporting-Endpoints` and
758
+ * a CSP `report-to`) reaches the server and is not in `blocked`. It stays on: `--disable-features` would replace the list
759
+ * Playwright passes there itself, and that list is no public API. Network Error Logging was not checked.
760
+ */
761
+ async guardWrites() {
762
+ if (this.pressing)
763
+ throw new Error("The write guard is already on.");
764
+ const page = await this.ensurePage();
765
+ // A plain storageState leaves out IndexedDB and the tab's sessionStorage, where an app may keep its session.
766
+ // Kept simple on purpose: IndexedDB is copied whole, however large; sessionStorage only of the origin the crawler's page is on.
767
+ const state = await within(this.context.storageState({ indexedDB: true }), SESSION_READ_TIMEOUT_MS, undefined);
768
+ if (!state)
769
+ throw guardFailure("SESSION_READ_FAILED");
770
+ const tab = await within(page.evaluate(readTabStorage), STATE_READ_TIMEOUT_MS, undefined);
771
+ const server = await chromium.launchServer(this.launchOptions(`${BLINK_OFF},${SENDS_PAST_FETCH}`)).catch(() => {
772
+ throw guardFailure("BROWSER_START_FAILED");
773
+ });
774
+ const pressing = new PlaywrightLibBackend(this.opts);
775
+ pressing.server = server;
776
+ const blocked = [];
777
+ let step = "BROWSER_START_FAILED";
778
+ try {
779
+ pressing.browser = await chromium.connect(server.wsEndpoint());
780
+ const cdp = await pressing.browser.newBrowserCDPSession();
781
+ cdp.on("Fetch.requestPaused", ({ requestId, request }) => {
782
+ const method = request.method.toUpperCase();
783
+ if (!changesServer(method)) {
784
+ void cdp.send("Fetch.continueRequest", { requestId }).catch(() => undefined);
785
+ return;
786
+ }
787
+ const path = pressing.blockedPath(request.url);
788
+ const pressed = pressing.lastPressed;
789
+ const same = blocked.find((b) => b.method === method && b.path === path && b.pressed?.role === pressed?.role && b.pressed?.name === pressed?.name);
790
+ if (same)
791
+ same.count++;
792
+ else
793
+ blocked.push({ method, path, ...(pressed ? { pressed: { ...pressed } } : {}), count: 1 });
794
+ // "Aborted" (net::ERR_ABORTED): a stopped form post leaves the page where it was, with no error page over it
795
+ void cdp.send("Fetch.failRequest", { requestId, errorReason: "Aborted" }).catch(() => undefined);
796
+ });
797
+ await cdp.send("Fetch.enable", { patterns: [{ urlPattern: "*" }] });
798
+ step = "SESSION_RESTORE_FAILED";
799
+ pressing.context = await pressing.newContext(state);
800
+ if (tab)
801
+ await pressing.context.addInitScript(seedTabStorage, tab);
802
+ }
803
+ catch {
804
+ await server.kill().catch(() => undefined);
805
+ throw guardFailure(step);
806
+ }
807
+ this.pressing = pressing;
808
+ // #252: a cookie set by script cannot be httpOnly, so an analytics cookie that changes on every page view is no session.
809
+ // Known limit: a session cookie a site leaves readable by script is not looked at.
810
+ const held = state.cookies.filter((c) => c.httpOnly);
811
+ return {
812
+ release: async () => {
813
+ if (this.pressing === pressing)
814
+ await this.discardPressing();
815
+ return blocked.map((b) => ({ ...b }));
816
+ },
817
+ sessionReplaced: async () => {
818
+ if (this.pressing !== pressing || held.length === 0)
819
+ return 0;
820
+ const now = await within(pressing.context.cookies(), STATE_READ_TIMEOUT_MS, undefined);
821
+ if (!now)
822
+ return 0;
823
+ return held.filter((c) => !now.some((n) => n.name === c.name && n.domain === c.domain && n.path === c.path && n.value === c.value)).length;
824
+ },
825
+ };
826
+ }
827
+ async discardPressing() {
828
+ await this.pressing?.server?.kill().catch(() => undefined);
829
+ this.pressing = undefined;
830
+ }
831
+ /** A stopped request's path, written like a recorded one; with its origin when that is not the page's. */
832
+ blockedPath(url) {
833
+ try {
834
+ const own = this.page ? new URL(this.page.url()).origin : undefined;
835
+ return new URL(url).origin === own ? recordedPath(url) : recordedUrl(url);
836
+ }
837
+ catch {
838
+ return recordedUrl(url);
839
+ }
193
840
  }
194
841
  session() {
195
842
  return {
@@ -198,10 +845,7 @@ export class PlaywrightLibBackend {
198
845
  await this.context?.close().catch(() => undefined);
199
846
  this.page = undefined;
200
847
  this.browser ??= await this.launch();
201
- this.context = await this.browser.newContext({
202
- storageState: state,
203
- ...(this.opts.httpCredentials ? { httpCredentials: this.opts.httpCredentials } : {}),
204
- });
848
+ this.context = await this.newContext(state);
205
849
  this.page = await this.context.newPage();
206
850
  },
207
851
  save: async () => {
@@ -216,6 +860,7 @@ export class PlaywrightLibBackend {
216
860
  throw new Error("runTests is implemented in Sprint 3.");
217
861
  }
218
862
  async close() {
863
+ await this.discardPressing();
219
864
  await this.page?.close().catch(() => undefined);
220
865
  await this.context?.close().catch(() => undefined);
221
866
  await this.browser?.close().catch(() => undefined);