dsh-builtin-browser 1.0.3 → 1.1.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 (305) hide show
  1. package/CHANGELOG.md +16 -1
  2. package/README.en.md +89 -0
  3. package/browser-extension/constants.mjs +20 -0
  4. package/browser-extension/controller.mjs +293 -0
  5. package/browser-extension/locales.mjs +15 -0
  6. package/browser-extension/manifest.json +12 -0
  7. package/browser-extension/options.html +14 -0
  8. package/browser-extension/options.mjs +9 -0
  9. package/browser-extension/permission-guard.mjs +13 -0
  10. package/browser-extension/worker.mjs +74 -0
  11. package/desktop-bridge/desktop-identity.json +10 -2
  12. package/desktop-bridge/install.mjs +28 -2
  13. package/docs/issue-replies-2026-11-28.md +141 -0
  14. package/dsh-host-patch/apply.mjs +1 -1
  15. package/dsh-host-patch/rc3.json +4 -4
  16. package/dsh-host-patch/rc5.json +4 -4
  17. package/dsh-host-patch/v023-alpha2.json +2 -2
  18. package/lib/browser-electron/bridge-status.js +24 -1
  19. package/lib/browser-electron/desktop-identity.js +47 -8
  20. package/lib/client.js +2 -1
  21. package/native-host/install.mjs +5 -0
  22. package/package.json +20 -2
  23. package/scripts/build-client.mjs +305 -0
  24. package/scripts/build.mjs +69 -0
  25. package/scripts/bundle-host.mjs +28 -0
  26. package/scripts/fix-exports.mjs +40 -0
  27. package/scripts/install-electron.mjs +101 -0
  28. package/scripts/pack.mjs +99 -0
  29. package/scripts/publish-manifest.mjs +56 -0
  30. package/scripts/verify-exports.mjs +58 -0
  31. package/scripts/verify-preview-sdk.mjs +93 -0
  32. package/skills/dsh-builtin-browser/SKILL.md +98 -0
  33. package/skills/dsh-builtin-browser/references/batch.md +68 -0
  34. package/skills/dsh-builtin-browser/references/deliver.md +31 -0
  35. package/skills/dsh-builtin-browser/references/locate.md +11 -0
  36. package/skills/dsh-builtin-browser/references/recover.md +11 -0
  37. package/skills/dsh-builtin-browser/references/verify.md +13 -0
  38. package/skills/dsh-debug-host/SKILL.md +56 -0
  39. package/skills/dsh-debug-self/SKILL.md +50 -0
  40. package/src/bridge-compatibility.ts +39 -0
  41. package/src/browser/anti-bot.ts +251 -0
  42. package/src/browser/deep-dom.ts +40 -0
  43. package/src/browser/handles.ts +89 -0
  44. package/src/browser/runtime.ts +578 -0
  45. package/src/browser/takeover-target.ts +45 -0
  46. package/src/browser/types.ts +870 -0
  47. package/src/browser-electron/authenticated-route.ts +109 -0
  48. package/src/browser-electron/automatic-maintenance.ts +736 -0
  49. package/src/browser-electron/bridge-auto.ts +159 -0
  50. package/src/browser-electron/bridge-connection.ts +386 -0
  51. package/src/browser-electron/bridge-endpoint.ts +129 -0
  52. package/src/browser-electron/bridge-install.ts +290 -0
  53. package/src/browser-electron/bridge-maintenance.ts +189 -0
  54. package/src/browser-electron/bridge-status.ts +412 -0
  55. package/src/browser-electron/desktop-bridge-host.ts +253 -0
  56. package/src/browser-electron/desktop-identity.ts +400 -0
  57. package/src/browser-electron/desktop-shell.ts +100 -0
  58. package/src/browser-electron/document-readiness.ts +45 -0
  59. package/src/browser-electron/electron-provision.ts +347 -0
  60. package/src/browser-electron/entry.ts +1378 -0
  61. package/src/browser-electron/ephemeral-profile.ts +189 -0
  62. package/src/browser-electron/extension-browser.ts +230 -0
  63. package/src/browser-electron/extension-setup.ts +67 -0
  64. package/src/browser-electron/file-write.ts +31 -0
  65. package/src/browser-electron/foreground-watch.ts +142 -0
  66. package/src/browser-electron/guest-cookie-jar.ts +177 -0
  67. package/src/browser-electron/guest-cookie-store.ts +59 -0
  68. package/src/browser-electron/guest-css-runtime.ts +76 -0
  69. package/src/browser-electron/guest-css.ts +68 -0
  70. package/src/browser-electron/guest-route.ts +716 -0
  71. package/src/browser-electron/guest-runtime.ts +408 -0
  72. package/src/browser-electron/guest-storage-runtime.ts +54 -0
  73. package/src/browser-electron/guest-storage.ts +120 -0
  74. package/src/browser-electron/history-store.ts +224 -0
  75. package/src/browser-electron/host-main.ts +1385 -0
  76. package/src/browser-electron/host-patch-maintenance.ts +121 -0
  77. package/src/browser-electron/http-body.ts +65 -0
  78. package/src/browser-electron/json-reply.ts +47 -0
  79. package/src/browser-electron/maintenance-broker.ts +166 -0
  80. package/src/browser-electron/maintenance-lifecycle.ts +91 -0
  81. package/src/browser-electron/maintenance-route.ts +68 -0
  82. package/src/browser-electron/missing-system-browser.ts +114 -0
  83. package/src/browser-electron/open-slot.ts +49 -0
  84. package/src/browser-electron/paths.ts +25 -0
  85. package/src/browser-electron/preferred-browser.ts +130 -0
  86. package/src/browser-electron/preview-route.ts +215 -0
  87. package/src/browser-electron/process-ownership.ts +174 -0
  88. package/src/browser-electron/process.ts +23 -0
  89. package/src/browser-electron/profile-checkpoint.ts +187 -0
  90. package/src/browser-electron/profile-command.ts +47 -0
  91. package/src/browser-electron/profile-extension.ts +129 -0
  92. package/src/browser-electron/profile-lease.ts +211 -0
  93. package/src/browser-electron/profile-residue.ts +49 -0
  94. package/src/browser-electron/provider-core.ts +1107 -0
  95. package/src/browser-electron/provider-interaction.ts +1034 -0
  96. package/src/browser-electron/provider-media.ts +589 -0
  97. package/src/browser-electron/provider-navigation.ts +323 -0
  98. package/src/browser-electron/provider-observation.ts +664 -0
  99. package/src/browser-electron/provider-tabs.ts +372 -0
  100. package/src/browser-electron/provider.ts +666 -0
  101. package/src/browser-electron/reference-route.ts +598 -0
  102. package/src/browser-electron/remote-host.ts +1538 -0
  103. package/src/browser-electron/rpc-input.ts +13 -0
  104. package/src/browser-electron/rpc-ops.ts +41 -0
  105. package/src/browser-electron/runtime-diagnostics.ts +38 -0
  106. package/src/browser-electron/runtime-route.ts +105 -0
  107. package/src/browser-electron/runtime-status.ts +309 -0
  108. package/src/browser-electron/settings-route.ts +64 -0
  109. package/src/browser-electron/settings-store.ts +593 -0
  110. package/src/browser-electron/shortcuts-route.ts +112 -0
  111. package/src/browser-electron/sidebar-only-host.ts +300 -0
  112. package/src/browser-electron/startpage-shortcuts.ts +213 -0
  113. package/src/browser-electron/system-browser.ts +1850 -0
  114. package/src/browser-electron/tauri-host.ts +194 -0
  115. package/src/browser-electron/timing.ts +16 -0
  116. package/src/browser-electron/virtual-cursor.ts +162 -0
  117. package/src/browser-electron/windows-system.ts +24 -0
  118. package/src/browser-reference/delivery.ts +384 -0
  119. package/src/browser-reference/entry.ts +631 -0
  120. package/src/browser-reference/export.ts +339 -0
  121. package/src/browser-reference/import.ts +303 -0
  122. package/src/browser-reference/page-script.ts +1537 -0
  123. package/src/browser-reference/service.ts +1346 -0
  124. package/src/browser-reference/store.ts +172 -0
  125. package/src/browser-reference/text-quote.ts +219 -0
  126. package/src/browser-reference/types.ts +195 -0
  127. package/src/browser-reference/visible.ts +367 -0
  128. package/src/browser-reference/web-sources.ts +106 -0
  129. package/src/client/apply-guard.ts +22 -0
  130. package/src/client/browser/BrowserController.ts +693 -0
  131. package/src/client/browser/BrowserFrame.ts +78 -0
  132. package/src/client/browser/BrowserNavigation.ts +169 -0
  133. package/src/client/browser/BrowserPage.ts +23 -0
  134. package/src/client/browser/BrowserPersistence.ts +44 -0
  135. package/src/client/browser/IframeImpl.ts +182 -0
  136. package/src/client/browser/child-tabs.ts +14 -0
  137. package/src/client/browser/frame-history.ts +125 -0
  138. package/src/client/browser/frame-state.ts +27 -0
  139. package/src/client/browser/iframe-reference.ts +67 -0
  140. package/src/client/browser/initialization.ts +262 -0
  141. package/src/client/browser/omnibox.ts +243 -0
  142. package/src/client/browser/store.ts +38 -0
  143. package/src/client/browser/takeover-channel.ts +72 -0
  144. package/src/client/browser/url.ts +46 -0
  145. package/src/client/browser/web-reference-source.ts +56 -0
  146. package/src/client/css-modules.d.ts +4 -0
  147. package/src/client/definition.tsx +36 -0
  148. package/src/client/electron/ElectronWebViewImpl.ts +371 -0
  149. package/src/client/electron/ElectronWebviewPresentation.ts +140 -0
  150. package/src/client/electron/NativeChildPresentation.ts +53 -0
  151. package/src/client/electron/NativeViewPage.ts +265 -0
  152. package/src/client/electron/pages.ts +23 -0
  153. package/src/client/electron/reference-overlay.ts +53 -0
  154. package/src/client/electron/workspace.ts +33 -0
  155. package/src/client/index.ts +333 -0
  156. package/src/client/locales.ts +860 -0
  157. package/src/client/pages.ts +28 -0
  158. package/src/client/reference/client/BrowserRefLink.tsx +142 -0
  159. package/src/client/reference/client/draft-reference.ts +167 -0
  160. package/src/client/reference/client/index.ts +7 -0
  161. package/src/client/reference/client/ordered-submission.ts +108 -0
  162. package/src/client/reference/client/pending-delivery.ts +216 -0
  163. package/src/client/reference/client/plugin.ts +208 -0
  164. package/src/client/reference/client/production/ReferenceCapsules.tsx +345 -0
  165. package/src/client/reference/client/production/ReferenceDock.module.css +193 -0
  166. package/src/client/reference/client/production/ReferenceDock.tsx +6 -0
  167. package/src/client/reference/client/production/ReferenceFeedback.tsx +15 -0
  168. package/src/client/reference/client/production/ReferenceMath.tsx +44 -0
  169. package/src/client/reference/client/production/ReferenceText.tsx +36 -0
  170. package/src/client/reference/client/production/assembly.ts +447 -0
  171. package/src/client/reference/client/production/asset-store.ts +144 -0
  172. package/src/client/reference/client/production/availability.ts +72 -0
  173. package/src/client/reference/client/production/bytes.ts +36 -0
  174. package/src/client/reference/client/production/composer-attachments.ts +44 -0
  175. package/src/client/reference/client/production/delivery-client.ts +211 -0
  176. package/src/client/reference/client/production/draft-adapter.ts +512 -0
  177. package/src/client/reference/client/production/http-transport.ts +212 -0
  178. package/src/client/reference/client/production/production-submission.ts +70 -0
  179. package/src/client/reference/client/production/protocol.ts +234 -0
  180. package/src/client/reference/client/production/reference-card.ts +240 -0
  181. package/src/client/reference/client/production/reference-labels.ts +29 -0
  182. package/src/client/reference/client/production/reply-link-bridge.ts +222 -0
  183. package/src/client/reference/client/production/reveal.ts +215 -0
  184. package/src/client/reference/client/production/runtime.ts +1056 -0
  185. package/src/client/reference/client/production/snapshot-adapter.ts +154 -0
  186. package/src/client/reference/client/production/source-marker.ts +99 -0
  187. package/src/client/reference/client/production/source-opener.ts +55 -0
  188. package/src/client/reference/client/production/styles.ts +104 -0
  189. package/src/client/reference/client/production/user-text-rule.ts +67 -0
  190. package/src/client/reference/client/reveal.ts +109 -0
  191. package/src/client/reference/client/scheme.ts +114 -0
  192. package/src/client/reference/client/session-schedule.ts +36 -0
  193. package/src/client/reference/client/types.ts +168 -0
  194. package/src/client/reference/css-modules.d.ts +4 -0
  195. package/src/client/reference/index.ts +11 -0
  196. package/src/client/reference-capture-owner.ts +162 -0
  197. package/src/client/reference-intents.ts +36 -0
  198. package/src/client/settings/index.ts +42 -0
  199. package/src/client/settings/mount-guard.ts +31 -0
  200. package/src/client/settings/panel.ts +2773 -0
  201. package/src/client/shortcut-open.ts +30 -0
  202. package/src/client/startpage/binding.ts +99 -0
  203. package/src/client/startpage/controller.ts +300 -0
  204. package/src/client/startpage/model.ts +279 -0
  205. package/src/client/view/Browser.module.css +751 -0
  206. package/src/client/view/BrowserBody.tsx +315 -0
  207. package/src/client/view/BrowserPresentation.ts +9 -0
  208. package/src/client/view/BrowserTitle.tsx +17 -0
  209. package/src/client/view/IframePresentation.ts +365 -0
  210. package/src/client/view/StartPage.tsx +598 -0
  211. package/src/client/view/TakeoverBanner.tsx +21 -0
  212. package/src/compat/host-features.ts +92 -0
  213. package/src/index.ts +110 -0
  214. package/src/reference-owner.ts +5 -0
  215. package/src/reference-page.ts +9 -0
  216. package/src/reference-source.ts +3 -0
  217. package/src/reference-text.ts +219 -0
  218. package/src/startpage-settings.ts +103 -0
  219. package/src/startpage.ts +71 -0
  220. package/src/takeover-protocol.ts +28 -0
  221. package/src/tool-browser/block-recovery.ts +85 -0
  222. package/src/tool-browser/code-tool.ts +555 -0
  223. package/src/tool-browser/code-worker.ts +725 -0
  224. package/src/tool-browser/element-fields.ts +167 -0
  225. package/src/tool-browser/errors.ts +40 -0
  226. package/src/tool-browser/index.ts +265 -0
  227. package/src/tool-browser/page-probe.ts +675 -0
  228. package/src/tool-browser/panel-page.ts +126 -0
  229. package/src/tool-browser/probe-client.ts +183 -0
  230. package/src/tool-browser/screenshot-annotations.ts +131 -0
  231. package/src/tool-browser/screenshot-image.ts +49 -0
  232. package/src/tool-browser/state.ts +375 -0
  233. package/src/tool-browser/takeover.ts +199 -0
  234. package/src/tool-browser/tools-debug.ts +806 -0
  235. package/src/tool-browser/tools-interaction.ts +956 -0
  236. package/src/tool-browser/tools-navigation.ts +786 -0
  237. package/src/tool-browser/tools-observation.ts +474 -0
  238. package/src/tool-browser/tools-reference.ts +294 -0
  239. package/src/types/electron-shim.d.ts +144 -0
  240. package/src/types.ts +85 -0
  241. package/src/web-guest.ts +35 -0
  242. package/tools/accept-desktop.mjs +148 -0
  243. package/dist/client.d.cts +0 -516
  244. package/dist/client.d.mts +0 -516
  245. package/dist/index.cjs +0 -92
  246. package/dist/index.d.mts +0 -2960
  247. package/dist/index.mjs +0 -24
  248. package/dsh-builtin-browser-1.0.3-publish.tgz +0 -0
  249. package/dsh-builtin-browser-1.0.3.tgz +0 -0
  250. package/dsh-host-patch/sources/main/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  251. package/dsh-host-patch/sources/main/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  252. package/dsh-host-patch/sources/main/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  253. package/dsh-host-patch/sources/main/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  254. package/dsh-host-patch/sources/main/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  255. package/dsh-host-patch/sources/main/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  256. package/dsh-host-patch/sources/main/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  257. package/dsh-host-patch/sources/main/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  258. package/dsh-host-patch/sources/main/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  259. package/dsh-host-patch/sources/main/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  260. package/dsh-host-patch/sources/main/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  261. package/dsh-host-patch/sources/main/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  262. package/dsh-host-patch/sources/main/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  263. package/dsh-host-patch/sources/main/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  264. package/dsh-host-patch/sources/main/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  265. package/dsh-host-patch/sources/main/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  266. package/dsh-host-patch/sources/main/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  267. package/dsh-host-patch/sources/main/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  268. package/dsh-host-patch/sources/manifest.json +0 -218
  269. package/dsh-host-patch/sources/rc3/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  270. package/dsh-host-patch/sources/rc3/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  271. package/dsh-host-patch/sources/rc3/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  272. package/dsh-host-patch/sources/rc3/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  273. package/dsh-host-patch/sources/rc3/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  274. package/dsh-host-patch/sources/rc3/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  275. package/dsh-host-patch/sources/rc3/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  276. package/dsh-host-patch/sources/rc3/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  277. package/dsh-host-patch/sources/rc3/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  278. package/dsh-host-patch/sources/rc3/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  279. package/dsh-host-patch/sources/rc3/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  280. package/dsh-host-patch/sources/rc3/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  281. package/dsh-host-patch/sources/rc3/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  282. package/dsh-host-patch/sources/rc3/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  283. package/dsh-host-patch/sources/rc3/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  284. package/dsh-host-patch/sources/rc3/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  285. package/dsh-host-patch/sources/rc3/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  286. package/dsh-host-patch/sources/rc3/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  287. package/dsh-host-patch/sources/rc5/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
  288. package/dsh-host-patch/sources/rc5/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
  289. package/dsh-host-patch/sources/rc5/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
  290. package/dsh-host-patch/sources/rc5/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
  291. package/dsh-host-patch/sources/rc5/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
  292. package/dsh-host-patch/sources/rc5/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
  293. package/dsh-host-patch/sources/rc5/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
  294. package/dsh-host-patch/sources/rc5/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
  295. package/dsh-host-patch/sources/rc5/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
  296. package/dsh-host-patch/sources/rc5/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
  297. package/dsh-host-patch/sources/rc5/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
  298. package/dsh-host-patch/sources/rc5/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
  299. package/dsh-host-patch/sources/rc5/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
  300. package/dsh-host-patch/sources/rc5/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
  301. package/dsh-host-patch/sources/rc5/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
  302. package/dsh-host-patch/sources/rc5/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
  303. package/dsh-host-patch/sources/rc5/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
  304. package/dsh-host-patch/sources/rc5/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
  305. package/dsh-host-patch/sources/series.json +0 -260
@@ -0,0 +1,675 @@
1
+ /**
2
+ * The page-side probe: one script that makes a page observable without touching the host.
3
+ *
4
+ * WHY THIS EXISTS
5
+ * Three capabilities the model needs are not tools here yet: what the console said, which network
6
+ * responses arrived, and what happened to a JavaScript dialog. All three live *inside* the page, and
7
+ * a dialog blocks the page until someone answers it — which is why a `confirm()` used to hang a whole
8
+ * tool call with no explanation.
9
+ *
10
+ * The obvious implementation is CDP event capture (`Runtime.consoleAPICalled`, `Network.*`,
11
+ * `Page.javascriptDialogOpening`) inside the host. That would mean a new capability in all three
12
+ * carriers — the self-hosted child, the driven Chrome and the sidebar bridge — plus a protocol
13
+ * version for the bridge. This probe instead installs itself with the `execute` path every carrier
14
+ * already has, so it works everywhere on day one and cannot drift per carrier.
15
+ *
16
+ * What it costs, stated plainly:
17
+ * - `console` and `network` see what the PAGE can see. A response that never reached `fetch`/`XHR`
18
+ * (a document navigation, an `<img>` failure the browser handled internally) appears only as a
19
+ * resource-timing entry, with no status code. CDP would know more.
20
+ * - Dialog capture works by replacing `window.alert/confirm/prompt` BEFORE they are called. A dialog
21
+ * produced by the browser itself (`beforeunload`, HTTP auth, permission prompts) is not covered.
22
+ * - It is an override, so a page that captured `window.fetch` earlier keeps its own copy. Installed
23
+ * at first use, which is early enough for every ordinary page and honest about the rest.
24
+ *
25
+ * Idempotent by version: installing twice keeps the buffers that already exist.
26
+ * @module dsh-browser/tool-browser/page-probe
27
+ */
28
+
29
+ import type { BrowserPageOperationRequest, BrowserProbeMethod } from '../browser/types.ts'
30
+ import { DEEP_DOM_SOURCE } from '../browser/deep-dom.ts'
31
+
32
+ /** Bumped when the probe's shape changes; an older probe is replaced rather than trusted. */
33
+ export const PROBE_VERSION = 10
34
+
35
+ /** Where the probe keeps itself, and the only global it adds. */
36
+ const PROBE_KEY = '__dshProbe'
37
+
38
+ /**
39
+ * The installer, as one expression that returns the installed version.
40
+ *
41
+ * Written as a string because it runs in the page, not here. Keep it dependency-free and ES5-safe:
42
+ * a page may be older than the harness.
43
+ */
44
+ export const PROBE_INSTALL_SCRIPT = `(() => {${DEEP_DOM_SOURCE}
45
+ const frameOffset = (node) => {
46
+ let x = 0, y = 0
47
+ let doc = node && node.ownerDocument
48
+ while (doc && doc.defaultView && doc.defaultView.frameElement) {
49
+ const frame = doc.defaultView.frameElement
50
+ const r = frame.getBoundingClientRect()
51
+ x += r.left + (Number(frame.clientLeft) || 0)
52
+ y += r.top + (Number(frame.clientTop) || 0)
53
+ doc = frame.ownerDocument
54
+ }
55
+ return { x: x, y: y }
56
+ }
57
+ const KEY = ${JSON.stringify(PROBE_KEY)}
58
+ const VERSION = ${PROBE_VERSION}
59
+ const previous = globalThis[KEY]
60
+ if (previous && previous.version === VERSION) return VERSION
61
+ if (previous) {
62
+ if (typeof previous.dispose !== 'function') throw new Error('reload this page to replace the older browser probe')
63
+ previous.dispose()
64
+ }
65
+ const restore = []
66
+ const replace = (target, key, value) => {
67
+ const original = target[key]
68
+ target[key] = value
69
+ restore.push(() => { if (target[key] === value) target[key] = original })
70
+ }
71
+
72
+ const state = {
73
+ version: VERSION,
74
+ startedAt: Date.now(),
75
+ console: [],
76
+ network: [],
77
+ dialogs: [],
78
+ dialogPolicy: 'native',
79
+ networkSequence: 0,
80
+ pending: 0,
81
+ lastNetworkAt: Date.now(),
82
+ lastMutationAt: Date.now(),
83
+ }
84
+ const cap = (list, item, limit) => { list.push(item); if (list.length > limit) list.splice(0, list.length - limit) }
85
+ const asText = (value) => {
86
+ try { return typeof value === 'string' ? value : JSON.stringify(value) } catch (error) { return String(value) }
87
+ }
88
+ const short = (value, limit) => { const text = String(value == null ? '' : value); return text.length > limit ? text.slice(0, limit) + '…' : text }
89
+
90
+ for (const level of ['log', 'info', 'warn', 'error', 'debug']) {
91
+ const original = console[level]
92
+ if (typeof original !== 'function') continue
93
+ replace(console, level, function () {
94
+ const parts = []
95
+ for (let i = 0; i < arguments.length; i += 1) parts.push(asText(arguments[i]))
96
+ cap(state.console, { at: Date.now(), level: level, text: short(parts.join(' '), 500) }, 200)
97
+ return original.apply(this, arguments)
98
+ })
99
+ }
100
+
101
+ const note = (entry) => { state.lastNetworkAt = Date.now(); entry.receivedAt = state.lastNetworkAt; entry.sequence = ++state.networkSequence; cap(state.network, entry, 300) }
102
+ const nativeFetch = globalThis.fetch
103
+ if (typeof nativeFetch === 'function') {
104
+ replace(globalThis, 'fetch', function (input, init) {
105
+ const url = typeof input === 'string' ? input : (input && input.url) || String(input)
106
+ const method = String((init && init.method) || (input && input.method) || 'GET').toUpperCase()
107
+ const started = Date.now()
108
+ state.pending += 1
109
+ const settle = (status, type) => {
110
+ state.pending = Math.max(0, state.pending - 1)
111
+ note({ at: started, kind: 'fetch', method: method, url: short(url, 300), status: status, type: short(type || '', 80), ms: Date.now() - started })
112
+ }
113
+ return nativeFetch.apply(this, arguments).then(
114
+ (response) => { let type = ''; try { type = response.headers.get('content-type') || '' } catch (error) { /* opaque */ } settle(response.status, type); return response },
115
+ (error) => { settle(0); throw error },
116
+ )
117
+ })
118
+ }
119
+
120
+ const XHR = globalThis.XMLHttpRequest
121
+ if (XHR && XHR.prototype && typeof XHR.prototype.send === 'function') {
122
+ const open = XHR.prototype.open
123
+ const send = XHR.prototype.send
124
+ replace(XHR.prototype, 'open', function (method, url) {
125
+ this.__dshNetwork = { method: String(method || 'GET').toUpperCase(), url: String(url || ''), at: Date.now() }
126
+ return open.apply(this, arguments)
127
+ })
128
+ replace(XHR.prototype, 'send', function () {
129
+ const meta = this.__dshNetwork || { method: 'GET', url: '', at: Date.now() }
130
+ state.pending += 1
131
+ const done = () => {
132
+ state.pending = Math.max(0, state.pending - 1)
133
+ let type = ''
134
+ try { type = this.getResponseHeader('content-type') || '' } catch (error) { /* not readable */ }
135
+ note({ at: meta.at, kind: 'xhr', method: meta.method, url: short(meta.url, 300), status: this.status || 0, type: short(type, 80), ms: Date.now() - meta.at })
136
+ this.removeEventListener('loadend', done)
137
+ }
138
+ this.addEventListener('loadend', done)
139
+ return send.apply(this, arguments)
140
+ })
141
+ }
142
+
143
+ if (typeof PerformanceObserver === 'function') {
144
+ try {
145
+ const seen = new Set()
146
+ const observer = new PerformanceObserver((list) => {
147
+ const entries = list.getEntries()
148
+ for (let i = 0; i < entries.length; i += 1) {
149
+ const entry = entries[i]
150
+ const key = entry.name + '|' + entry.startTime
151
+ if (seen.has(key)) continue
152
+ seen.add(key)
153
+ note({ at: Math.round((performance.timeOrigin || Date.now()) + entry.startTime), kind: 'resource', method: 'GET', url: short(entry.name, 300), status: 0, ms: Math.round(entry.duration), bytes: entry.transferSize || 0 })
154
+ }
155
+ })
156
+ observer.observe({ type: 'resource', buffered: true })
157
+ restore.push(() => observer.disconnect())
158
+ } catch (error) { /* a page with no resource timing still has fetch and XHR */ }
159
+ }
160
+
161
+ const nativeDialogs = {}
162
+ const dialogWrappers = {}
163
+ for (const kind of ['alert', 'confirm', 'prompt']) {
164
+ const original = globalThis[kind]
165
+ if (typeof original !== 'function') continue
166
+ nativeDialogs[kind] = original
167
+ const wrapper = function (message, value) {
168
+ const accept = state.dialogPolicy === 'accept'
169
+ cap(state.dialogs, { at: Date.now(), kind: kind, message: short(message, 300), policy: state.dialogPolicy, answered: accept ? 'accepted' : 'dismissed' }, 50)
170
+ if (!accept) return kind === 'confirm' ? false : kind === 'prompt' ? null : undefined
171
+ return kind === 'prompt' ? String(value == null ? '' : value) : kind === 'confirm' ? true : undefined
172
+ }
173
+ dialogWrappers[kind] = wrapper
174
+ restore.push(() => { if (globalThis[kind] === wrapper) globalThis[kind] = nativeDialogs[kind] })
175
+ }
176
+
177
+ try {
178
+ const observer = new MutationObserver(() => { state.lastMutationAt = Date.now() })
179
+ observer.observe(document.documentElement || document, { subtree: true, childList: true, attributes: true })
180
+ restore.push(() => observer.disconnect())
181
+ } catch (error) { /* no observer: quiet time falls back to network only */ }
182
+
183
+ const describe = (node) => {
184
+ if (!node || !node.tagName) return 'unknown'
185
+ const name = (node.getAttribute && (node.getAttribute('aria-label') || node.getAttribute('name'))) || ''
186
+ const text = short((node.innerText || '').trim().replace(/\\s+/g, ' '), 60)
187
+ return node.tagName.toLowerCase() + (name ? '[' + name + ']' : '') + (text ? ' "' + text + '"' : '')
188
+ }
189
+
190
+ state.settle = function () {
191
+ const quietFrom = Math.max(state.lastNetworkAt, state.lastMutationAt)
192
+ return { pending: state.pending, quietMs: Date.now() - quietFrom, readyState: String(document.readyState) }
193
+ }
194
+
195
+ state.find = function (target, scroll) {
196
+ if (!target) return null
197
+ let node = null
198
+ try {
199
+ if (target.css) node = __dshQuery(String(target.css))
200
+ else if (target.xpath) node = document.evaluate(String(target.xpath), document, null, 9, null).singleNodeValue
201
+ else if (target.text) {
202
+ const wanted = String(target.text).trim().toLowerCase()
203
+ const nodes = __dshQueryAll('button, a, [role=button], input, label, [role=tab], [role=option], [role=link]')
204
+ for (let i = 0; i < nodes.length; i += 1) {
205
+ const value = ((nodes[i].innerText || nodes[i].getAttribute('aria-label') || nodes[i].value || '') + '').trim().toLowerCase()
206
+ if (value && value.indexOf(wanted) !== -1) { node = nodes[i]; break }
207
+ }
208
+ }
209
+ } catch (error) { return null }
210
+ if (!node) return null
211
+ if (scroll === true && typeof node.scrollIntoView === 'function') node.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' })
212
+ const rect = node.getBoundingClientRect()
213
+ const offset = frameOffset(node)
214
+ state.lastFound = node
215
+ return { x: Math.round(offset.x + rect.left + rect.width / 2), y: Math.round(offset.y + rect.top + rect.height / 2), w: Math.round(rect.width), h: Math.round(rect.height), described: describe(node) }
216
+ }
217
+
218
+ const composedParent = (node) => {
219
+ if (node.parentElement) return node.parentElement
220
+ if (node.parentNode && node.parentNode.host) return node.parentNode.host
221
+ const doc = node.ownerDocument
222
+ if (doc && (node === doc.documentElement || node.parentNode === doc)) {
223
+ const frame = doc.defaultView && doc.defaultView.frameElement
224
+ if (frame && frame !== node) return frame
225
+ }
226
+ return null
227
+ }
228
+ const deepHit = (x, y) => {
229
+ let cx = x, cy = y
230
+ let node = document.elementFromPoint(cx, cy)
231
+ for (let i = 0; node && i < 16; i += 1) {
232
+ if (node.shadowRoot && typeof node.shadowRoot.elementFromPoint === 'function') {
233
+ const inner = node.shadowRoot.elementFromPoint(cx, cy)
234
+ if (!inner || inner === node) break
235
+ node = inner
236
+ continue
237
+ }
238
+ if (node.tagName === 'IFRAME' || node.tagName === 'FRAME') {
239
+ let doc = null
240
+ try { doc = node.contentDocument } catch (error) { doc = null }
241
+ if (!doc || typeof doc.elementFromPoint !== 'function') break
242
+ const r = node.getBoundingClientRect()
243
+ cx = cx - r.left - (Number(node.clientLeft) || 0)
244
+ cy = cy - r.top - (Number(node.clientTop) || 0)
245
+ const inner = doc.elementFromPoint(cx, cy)
246
+ if (!inner || inner === node) break
247
+ node = inner
248
+ continue
249
+ }
250
+ break
251
+ }
252
+ return node
253
+ }
254
+ const computedStyle = (node) => {
255
+ try {
256
+ const win = node && node.ownerDocument && node.ownerDocument.defaultView
257
+ return (win && typeof win.getComputedStyle === 'function' ? win.getComputedStyle : getComputedStyle)(node)
258
+ } catch (error) { return null }
259
+ }
260
+ const floats = (node) => {
261
+ const style = computedStyle(node)
262
+ return !!style && (style.position === 'fixed' || style.position === 'sticky' || Number(style.zIndex) >= 100)
263
+ }
264
+ // A click at the point lands on the target when what is there is the target or inside it (an icon or label in a
265
+ // button, including inside open shadow roots and same-origin iframes), unless a floating layer between them
266
+ // (a modal inside the target) is what takes the click.
267
+ const lands = (target, hit) => {
268
+ for (let node = hit, depth = 0; node && depth < 64; node = composedParent(node), depth += 1) {
269
+ if (node === target) return true
270
+ if (floats(node)) return false
271
+ }
272
+ return false
273
+ }
274
+
275
+ const DISMISS = /(accept|agree|allow|continue|close|got it|dismiss|ok|agree|同意|接受|允许|继续|关闭|知道了|我知道了|我同意)/i
276
+
277
+ state.overlayAt = function (x, y) {
278
+ const px = Number(x), py = Number(y)
279
+ const top = deepHit(px, py)
280
+ if (!top) return { covers: null, dismiss: null }
281
+ if (state.lastFound && lands(state.lastFound, top)) return { covers: null, dismiss: null }
282
+ let node = top
283
+ let depth = 0
284
+ while (node && depth < 16) {
285
+ if (floats(node)) {
286
+ const buttons = node.querySelectorAll ? node.querySelectorAll('button, [role=button], a') : []
287
+ for (let i = 0; i < buttons.length && i < 60; i += 1) {
288
+ const label = ((buttons[i].innerText || '') + ' ' + (buttons[i].getAttribute('aria-label') || '')).trim()
289
+ if (DISMISS.test(label)) {
290
+ const rect = buttons[i].getBoundingClientRect()
291
+ const offset = frameOffset(buttons[i])
292
+ return { covers: describe(top), dismiss: { label: short(label, 40), x: Math.round(offset.x + rect.left + rect.width / 2), y: Math.round(offset.y + rect.top + rect.height / 2) } }
293
+ }
294
+ }
295
+ return { covers: describe(top), dismiss: null }
296
+ }
297
+ node = composedParent(node)
298
+ depth += 1
299
+ }
300
+ return { covers: describe(top), dismiss: null }
301
+ }
302
+
303
+ state.read = function (kind, filter, limit) {
304
+ const list = kind === 'console' ? state.console : kind === 'network' ? state.network : state.dialogs
305
+ const needle = filter ? String(filter).toLowerCase() : ''
306
+ const rows = needle === '' ? list : list.filter((row) => ((row.url || '') + ' ' + (row.text || '') + ' ' + (row.message || '')).toLowerCase().indexOf(needle) !== -1)
307
+ const max = Math.max(0, Math.min(Number(limit) || 20, 100))
308
+ return rows.slice(Math.max(0, rows.length - max))
309
+ }
310
+
311
+ state.clear = function (kind) {
312
+ if (kind === 'console') state.console.length = 0
313
+ else if (kind === 'network') state.network.length = 0
314
+ else if (kind === 'dialogs') state.dialogs.length = 0
315
+ return true
316
+ }
317
+
318
+ state.setDialogPolicy = function (policy) {
319
+ if (policy !== 'native' && policy !== 'accept' && policy !== 'dismiss') return state.dialogPolicy
320
+ const previousPolicy = state.dialogPolicy
321
+ state.dialogPolicy = policy
322
+ for (const kind of Object.keys(nativeDialogs)) {
323
+ if (policy === 'native') {
324
+ if (globalThis[kind] === dialogWrappers[kind]) globalThis[kind] = nativeDialogs[kind]
325
+ } else {
326
+ if (previousPolicy === 'native' && globalThis[kind] !== dialogWrappers[kind]) nativeDialogs[kind] = globalThis[kind]
327
+ globalThis[kind] = dialogWrappers[kind]
328
+ }
329
+ }
330
+ return state.dialogPolicy
331
+ }
332
+
333
+ state.dialogStatus = function () { return state.dialogPolicy }
334
+ state.networkCursor = function () { return { startedAt: state.startedAt, sequence: state.networkSequence } }
335
+ state.dispose = function () {
336
+ for (const undo of restore.reverse()) { try { undo() } catch (error) {} }
337
+ if (globalThis[KEY] === state) delete globalThis[KEY]
338
+ }
339
+
340
+ state.findText = function (text, all) {
341
+ const needle = String(text || '')
342
+ const out = []
343
+ if (needle === '') return out
344
+ const wanted = needle.toLowerCase()
345
+ const roots = __dshRoots()
346
+ for (let r = 0; r < roots.length; r += 1) {
347
+ const scope = roots[r]
348
+ const owner = scope.ownerDocument || scope
349
+ const root = scope.nodeType === 9 ? (scope.body || scope.documentElement) : scope
350
+ if (!root || typeof owner.createTreeWalker !== 'function') continue
351
+ const walker = owner.createTreeWalker(root, 4, null) // 4 = SHOW_TEXT
352
+ let node = walker.nextNode()
353
+ while (node) {
354
+ const parent = node.parentElement
355
+ const value = parent && /^(SCRIPT|STYLE|NOSCRIPT|TEMPLATE)$/.test(parent.tagName) ? '' : node.nodeValue || ''
356
+ let at = value.toLowerCase().indexOf(wanted)
357
+ while (at !== -1) {
358
+ const range = owner.createRange()
359
+ range.setStart(node, at)
360
+ range.setEnd(node, at + needle.length)
361
+ const rect = range.getBoundingClientRect()
362
+ const offset = frameOffset(node)
363
+ out.push({
364
+ text: short(value.slice(Math.max(0, at - 20), at + needle.length + 20).replace(/\\s+/g, ' ').trim(), 80),
365
+ x: Math.round(offset.x + rect.left + rect.width / 2),
366
+ y: Math.round(offset.y + rect.top + rect.height / 2),
367
+ host: node.parentElement ? describe(node.parentElement) : 'text',
368
+ })
369
+ if (out.length >= (all ? 50 : 5)) return out
370
+ at = value.toLowerCase().indexOf(wanted, at + 1)
371
+ }
372
+ node = walker.nextNode()
373
+ }
374
+ }
375
+ return out
376
+ }
377
+
378
+ const hoverEvent = (type, node, x, y) => {
379
+ const init = { bubbles: type.indexOf('enter') === -1, cancelable: true, composed: true, clientX: x, clientY: y, button: 0, buttons: 0 }
380
+ try {
381
+ if (type.indexOf('pointer') === 0 && typeof PointerEvent === 'function') return new PointerEvent(type, Object.assign({ pointerId: 1, pointerType: 'mouse', isPrimary: true }, init))
382
+ if (typeof MouseEvent === 'function') return new MouseEvent(type.replace('pointer', 'mouse'), init)
383
+ } catch (error) { return null }
384
+ return null
385
+ }
386
+
387
+ state.hoverAt = function (x, y) {
388
+ const node = document.elementFromPoint(Number(x), Number(y))
389
+ if (!node) return false
390
+ const types = ['pointerover', 'pointerenter', 'mouseover', 'mouseenter', 'mousemove']
391
+ let fired = 0
392
+ for (let i = 0; i < types.length; i += 1) {
393
+ const event = hoverEvent(types[i], node, Number(x), Number(y))
394
+ if (event && typeof node.dispatchEvent === 'function') { node.dispatchEvent(event); fired += 1 }
395
+ }
396
+ return fired > 0
397
+ }
398
+
399
+ state.summary = function () {
400
+ const body = document.body ? document.body.innerText : ''
401
+ const query = (selector) => { try { return document.querySelectorAll(selector).length } catch (error) { return 0 } }
402
+ const settled = state.settle()
403
+ return {
404
+ url: String(location.href),
405
+ title: String(document.title || ''),
406
+ readyState: settled.readyState,
407
+ pending: settled.pending,
408
+ quietMs: settled.quietMs,
409
+ inputs: query('input, textarea, select'),
410
+ buttons: query('button, [role=button]'),
411
+ links: query('a[href]'),
412
+ scrollX: Math.round(globalThis.scrollX || 0),
413
+ scrollY: Math.round(globalThis.scrollY || 0),
414
+ // The page's own geometry (issue #140): a screenshot that disagrees with these numbers was
415
+ // captured from a different surface, which is a fact only the page can prove.
416
+ vpWidth: Math.round(globalThis.innerWidth || 0),
417
+ vpHeight: Math.round(globalThis.innerHeight || 0),
418
+ dpr: Number(globalThis.devicePixelRatio || 1),
419
+ winWidth: Math.round(globalThis.outerWidth || 0),
420
+ winHeight: Math.round(globalThis.outerHeight || 0),
421
+ selection: short(globalThis.getSelection ? String(globalThis.getSelection()) : '', 120),
422
+ text: short(String(body || '').replace(/\\s+/g, ' ').trim(), 400),
423
+ }
424
+ }
425
+ // Where a page keeps its data before it becomes DOM: embedded state, the JSON APIs it called,
426
+ // resources it fetched before the probe existed, and endpoints it declares. Shapes only, never
427
+ // bodies, so the answer stays around 1-2 KB.
428
+ state.dataSources = function () {
429
+ const DATA_URL = /[.]json([?#]|$)|[/]api[/]|graphql|[/](locations?|stores?|search|query|products?|items?|listings?)([/?#.]|$)/i
430
+ const bytes = (text) => { try { return new Blob([text]).size } catch (error) { return String(text).length } }
431
+ const shape = (value) => {
432
+ const keys = value && typeof value === 'object' && !Array.isArray(value) ? Object.keys(value).slice(0, 12) : []
433
+ const arrays = []
434
+ const seen = new Set()
435
+ const walk = (node, path, depth) => {
436
+ if (!node || typeof node !== 'object' || seen.has(node) || depth > 6 || seen.size > 2000) return
437
+ seen.add(node)
438
+ if (Array.isArray(node)) {
439
+ if (node.length >= 3) arrays.push({ path: path || '(root)', length: node.length })
440
+ walk(node[0], path + '[0]', depth + 1)
441
+ return
442
+ }
443
+ for (const key of Object.keys(node).slice(0, 60)) walk(node[key], path ? path + '.' + key : key, depth + 1)
444
+ }
445
+ walk(value, '', 0)
446
+ arrays.sort((a, b) => b.length - a.length)
447
+ return { keys: keys, arrays: arrays.slice(0, 5) }
448
+ }
449
+ const embedded = []
450
+ const counts = {}
451
+ const scripts = Array.from(document.querySelectorAll('script#__NEXT_DATA__, script#__NUXT_DATA__, script[type="application/json"], script[type="application/ld+json"]'))
452
+ for (const node of scripts) {
453
+ const type = node.type || 'text/javascript'
454
+ const index = counts[type] = (counts[type] === undefined ? 0 : counts[type] + 1)
455
+ const text = node.textContent || ''
456
+ if (text.trim().length < 2 || embedded.length >= 8) continue
457
+ let parsed
458
+ try { parsed = JSON.parse(text) } catch (error) { parsed = undefined }
459
+ const name = node.id ? '#' + node.id : 'script[type="' + type + '"][' + index + ']'
460
+ embedded.push(Object.assign({ name: short(name, 80), bytes: bytes(text) }, parsed === undefined ? { parsed: false } : shape(parsed)))
461
+ }
462
+ for (const key of ['__NEXT_DATA__', '__NUXT__', '__INITIAL_STATE__', '__PRELOADED_STATE__', '__APOLLO_STATE__', '__remixContext']) {
463
+ let value
464
+ try { value = globalThis[key] } catch (error) { value = undefined }
465
+ if (value === undefined || value === null || typeof value !== 'object' || embedded.length >= 10) continue
466
+ let size = 0
467
+ try { size = bytes(JSON.stringify(value)) } catch (error) { size = 0 }
468
+ embedded.push(Object.assign({ name: 'window.' + key, bytes: size }, shape(value)))
469
+ }
470
+ const apis = []
471
+ const called = new Map()
472
+ for (const row of state.network) {
473
+ if ((row.kind !== 'fetch' && row.kind !== 'xhr') || !(row.status > 0)) continue
474
+ const id = row.method + ' ' + String(row.url).split('?')[0]
475
+ const json = /json/i.test(String(row.type || ''))
476
+ const hit = called.get(id)
477
+ if (hit) { hit.calls += 1; hit.url = row.url; hit.status = row.status; continue }
478
+ const entry = { method: row.method, url: row.url, status: row.status, type: short(String(row.type || '').split(';')[0], 40), calls: 1, json: json }
479
+ called.set(id, entry)
480
+ apis.push(entry)
481
+ }
482
+ apis.sort((a, b) => Number(b.json) - Number(a.json) || Number(DATA_URL.test(b.url)) - Number(DATA_URL.test(a.url)))
483
+ const known = new Set(apis.map(entry => String(entry.url).split('?')[0]))
484
+ const resources = []
485
+ let timings = []
486
+ try { timings = performance.getEntriesByType('resource') } catch (error) { timings = [] }
487
+ for (const entry of timings) {
488
+ const url = String(entry.name || '')
489
+ const initiator = String(entry.initiatorType || '')
490
+ if (initiator !== 'fetch' && initiator !== 'xmlhttprequest' && !DATA_URL.test(url)) continue
491
+ if (/^(script|css|img|link|image)$/.test(initiator) && !/[.]json([?#]|$)/i.test(url)) continue
492
+ const base = url.split('?')[0]
493
+ if (url.length > 2048 || known.has(base)) continue
494
+ known.add(base)
495
+ resources.push({ url: url, initiator: initiator, bytes: entry.transferSize || entry.encodedBodySize || 0 })
496
+ if (resources.length >= 12) break
497
+ }
498
+ const declared = []
499
+ const declare = (from, url) => { if (url && url.length <= 2048 && declared.length < 10 && !declared.some(entry => entry.url === url)) declared.push({ from: from, url: url }) }
500
+ try {
501
+ for (const link of Array.from(document.querySelectorAll('link[rel~="preload"][as="fetch"], link[rel~="prefetch"][as="fetch"]'))) declare('link[rel=' + link.rel + ']', link.href)
502
+ for (const node of Array.from(document.querySelectorAll('[data-api], [data-endpoint]')).slice(0, 20)) declare(node.hasAttribute('data-api') ? 'data-api' : 'data-endpoint', String(node.getAttribute('data-api') || node.getAttribute('data-endpoint') || ''))
503
+ } catch (error) { /* a document without these still answers the rest */ }
504
+ return { url: String(location.href), embedded: embedded, apis: apis.slice(0, 12), resources: resources, declared: declared }
505
+ }
506
+ globalThis[KEY] = state
507
+ return VERSION
508
+ })()`
509
+
510
+ /**
511
+ * One probe call, evaluated in the page, with its result serialised as JSON.
512
+ *
513
+ * JSON in, JSON out, because that is the only shape every carrier's `execute` can carry reliably.
514
+ * @param method - the probe function to call (`read`, `settle`, `find`, `overlayAt`, `clear`, …).
515
+ * @param args - arguments, already JSON-serialisable.
516
+ * @returns a script whose value is the JSON text of the result (or an error object).
517
+ */
518
+ export function probeCallScript(method: string, args: readonly unknown[] = []): string {
519
+ return `(() => {
520
+ const probe = globalThis[${JSON.stringify(PROBE_KEY)}]
521
+ if (!probe) return JSON.stringify({ error: 'probe-not-installed' })
522
+ if (typeof probe[${JSON.stringify(method)}] !== 'function') return JSON.stringify({ error: 'probe-method-missing' })
523
+ try { return JSON.stringify(probe[${JSON.stringify(method)}].apply(probe, ${JSON.stringify(args)})) } catch (error) { return JSON.stringify({ error: String(error) }) }
524
+ })()`
525
+ }
526
+
527
+ /**
528
+ * Dispatch a pointer drag in the page, for elements that accept synthetic pointer events.
529
+ *
530
+ * Uses `PointerEvent` when the page has it and `MouseEvent` otherwise, because a canvas app that
531
+ * listens for `mousedown` never sees a pointer event. This is a page-level gesture: a page that
532
+ * demands trusted input (some canvas editors) ignores it, exactly like `click_sequence`'s
533
+ * coordinate clicks are the trusted counterpart.
534
+ * @param from - start point in viewport CSS pixels.
535
+ * @param to - end point.
536
+ * @param steps - intermediate moves; more steps make a slider or a canvas app follow the path.
537
+ * @returns a script value: `{ ok: true, moved, at }` or `{ ok: false, reason }`.
538
+ */
539
+ export function dragScript(
540
+ from: { readonly x: number; readonly y: number },
541
+ to: { readonly x: number; readonly y: number },
542
+ steps = 12,
543
+ ): string {
544
+ const points = JSON.stringify({ from, to, steps })
545
+ return `(() => {
546
+ const spec = ${points}
547
+ const at = (x, y) => document.elementFromPoint(x, y)
548
+ const start = at(spec.from.x, spec.from.y)
549
+ if (!start) return JSON.stringify({ ok: false, reason: 'nothing at the start point' })
550
+ const make = (type, x, y, extra) => {
551
+ const init = Object.assign({ bubbles: true, cancelable: true, composed: true, clientX: x, clientY: y, button: 0, buttons: type === 'pointerup' || type === 'mouseup' ? 0 : 1 }, extra || {})
552
+ try {
553
+ if (type.indexOf('pointer') === 0 && typeof PointerEvent === 'function') return new PointerEvent(type, Object.assign({ pointerId: 1, pointerType: 'mouse', isPrimary: true }, init))
554
+ if (typeof MouseEvent === 'function') return new MouseEvent(type.replace('pointer', 'mouse'), init)
555
+ } catch (error) { /* fall through to the null below */ }
556
+ return null
557
+ }
558
+ const fire = (node, type, x, y, extra) => {
559
+ const event = make(type, x, y, extra)
560
+ if (event !== null && node && typeof node.dispatchEvent === 'function') { node.dispatchEvent(event); return true }
561
+ return false
562
+ }
563
+ if (!fire(start, 'pointerdown', spec.from.x, spec.from.y)) {
564
+ return JSON.stringify({ ok: false, reason: 'this page exposes no event constructors to dispatch a drag' })
565
+ }
566
+ fire(start, 'mousedown', spec.from.x, spec.from.y)
567
+ const total = Math.max(1, Math.min(Number(spec.steps) || 12, 60))
568
+ for (let i = 1; i <= total; i += 1) {
569
+ const x = Math.round(spec.from.x + (spec.to.x - spec.from.x) * (i / total))
570
+ const y = Math.round(spec.from.y + (spec.to.y - spec.from.y) * (i / total))
571
+ const node = at(x, y) || start
572
+ fire(node, 'pointermove', x, y)
573
+ fire(node, 'mousemove', x, y)
574
+ }
575
+ const end = at(spec.to.x, spec.to.y) || start
576
+ fire(end, 'pointerup', spec.to.x, spec.to.y)
577
+ fire(end, 'mouseup', spec.to.x, spec.to.y)
578
+ return JSON.stringify({ ok: true, moved: total, at: spec.to })
579
+ })()`
580
+ }
581
+
582
+ /**
583
+ * Put a local file into an `<input type=file>`, without CDP.
584
+ *
585
+ * The page cannot read a disk path, so the bytes travel in as base64 and are rebuilt as a `File`
586
+ * in page context, then attached through a `DataTransfer`. That is what a drag-and-drop handler
587
+ * sees, so frameworks that read `input.files` or a drop event both work. The admission decision
588
+ * (which path may be read at all) belongs to the caller; this only carries the bytes.
589
+ * @param target - how to find the input: a CSS selector or visible text near it.
590
+ * @param file - name, MIME type and base64 of the bytes.
591
+ * @returns a script value: `{ ok: true, name, size }` or `{ ok: false, reason }`.
592
+ */
593
+ export function uploadScript(
594
+ target: { readonly by: 'css' | 'text' | 'xpath'; readonly value: string },
595
+ file: { readonly name: string; readonly mime: string; readonly base64: string },
596
+ ): string {
597
+ const spec = JSON.stringify({ target, file })
598
+ return `(() => {${DEEP_DOM_SOURCE}
599
+ const spec = ${spec}
600
+ const probe = globalThis[${JSON.stringify(PROBE_KEY)}]
601
+ const where = probe ? probe.find(spec.target) : null
602
+ let node = null
603
+ try {
604
+ if (spec.target.by === 'css') node = __dshQuery(spec.target.value)
605
+ else if (spec.target.by === 'xpath') node = document.evaluate(spec.target.value, document, null, 9, null).singleNodeValue
606
+ else if (where) node = document.elementFromPoint(where.x, where.y)
607
+ } catch (error) { node = null }
608
+ if (node && node.tagName !== 'INPUT' && node.querySelector) {
609
+ const nested = node.querySelector('input[type=file]')
610
+ if (nested) node = nested
611
+ }
612
+ if (!node || node.tagName !== 'INPUT' || String(node.type).toLowerCase() !== 'file') {
613
+ return JSON.stringify({ ok: false, reason: 'no file input at that target (' + (where ? where.described : 'nothing matched') + ')' })
614
+ }
615
+ const binary = atob(spec.file.base64)
616
+ const bytes = new Uint8Array(binary.length)
617
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i)
618
+ const blob = new File([bytes], spec.file.name, { type: spec.file.mime || 'application/octet-stream' })
619
+ const transfer = new DataTransfer()
620
+ transfer.items.add(blob)
621
+ node.files = transfer.files
622
+ node.dispatchEvent(new Event('input', { bubbles: true }))
623
+ node.dispatchEvent(new Event('change', { bubbles: true }))
624
+ return JSON.stringify({ ok: true, name: blob.name, size: blob.size, files: node.files ? node.files.length : 0 })
625
+ })()`
626
+ }
627
+ /**
628
+ * What an action changed on the page that the URL does not show: the title, visible alert regions
629
+ * and the dialogs the probe answered. Read before and after each action for the post-action line.
630
+ * It never installs the probe, so observing an action leaves the page as it was.
631
+ */
632
+ const PULSE_SCRIPT = `(() => {
633
+ const probe = globalThis[${JSON.stringify(PROBE_KEY)}]
634
+ const alerts = []
635
+ try {
636
+ for (const node of Array.from(document.querySelectorAll('[role=alert], [role=alertdialog], [aria-live=assertive]')).slice(0, 20)) {
637
+ const text = String(node.innerText || '').replace(/\\s+/g, ' ').trim().slice(0, 160)
638
+ if (text !== '' && node.getClientRects().length > 0 && alerts.indexOf(text) === -1) alerts.push(text)
639
+ if (alerts.length >= 5) break
640
+ }
641
+ } catch (error) { /* a document without a body still has a title */ }
642
+ const dialogs = probe && Array.isArray(probe.dialogs)
643
+ ? probe.dialogs.slice(-5).map(entry => ({ at: entry.at, kind: entry.kind, message: String(entry.message).slice(0, 160), answered: entry.answered }))
644
+ : []
645
+ return JSON.stringify({ title: String(document.title || ''), alerts: alerts, dialogs: dialogs, probe: probe ? Number(probe.startedAt) || 0 : 0 })
646
+ })()`
647
+
648
+ /** A fetch from the page, so it carries the page's same-origin cookies. The body comes back as text. */
649
+ function fetchScript(url: string, init: { readonly method?: string; readonly headers?: Readonly<Record<string, string>>; readonly body?: string }): string {
650
+ return `(async () => {
651
+ const response = await fetch(new URL(${JSON.stringify(url)}, document.baseURI).href, Object.assign({ credentials: 'same-origin' }, ${JSON.stringify(init)}))
652
+ const body = await response.text()
653
+ return JSON.stringify({ ok: response.ok, status: response.status, statusText: response.statusText, url: response.url, type: response.headers.get('content-type') || '', body: body })
654
+ })()`
655
+ }
656
+
657
+ /** Build a fixed page operation, rejecting unknown operations before any code runs. */
658
+ export function pageOperationScript(request: BrowserPageOperationRequest): string {
659
+ switch (request.operation) {
660
+ case 'install': return PROBE_INSTALL_SCRIPT
661
+ case 'url': return 'JSON.stringify(location.href)'
662
+ case 'pulse': return PULSE_SCRIPT
663
+ case 'fetch': return fetchScript(request.url, request.init)
664
+ case 'text': return 'JSON.stringify((document.body ? document.body.innerText : "").indexOf(' + JSON.stringify(request.text) + ') !== -1)'
665
+ case 'drag': return dragScript(request.from, request.to, request.steps)
666
+ case 'upload': return uploadScript(request.target, request.file)
667
+ case 'probe': {
668
+ const methods: readonly BrowserProbeMethod[] = ['read', 'clear', 'settle', 'find', 'overlayAt', 'summary',
669
+ 'findText', 'hoverAt', 'setDialogPolicy', 'dialogStatus', 'networkCursor', 'dataSources']
670
+ if (!methods.includes(request.method)) throw new Error('browser: unsupported fixed page operation')
671
+ return probeCallScript(request.method, request.args)
672
+ }
673
+ default: throw new Error('browser: unsupported fixed page operation')
674
+ }
675
+ }