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,631 @@
1
+ /**
2
+ * Human page entries and same-origin frame identity (design §3.1, §10.3,
3
+ * §11.3; B02/B40/B46/B48/B32).
4
+ *
5
+ * Two different adapters must never own the same page's entry: only ONE
6
+ * overlay is installed per document, and an already-installed overlay is a
7
+ * no-op. The overlay is a *low-trust* entry: it reports an intent with
8
+ * `entry: 'page-overlay'` and never claims `activeTab`, screenshot or any
9
+ * other capability. `isTrusted` is recorded for diagnostics, never used as an
10
+ * authorisation credential.
11
+ *
12
+ * Frame identity is decided by the host from the selector it was asked to
13
+ * inspect; the page cannot invent a `frameRoute` that the service will trust.
14
+ * @module dsh-browser/browser-reference/entry
15
+ */
16
+
17
+ import { HIGHLIGHT_HOST_ID, OVERLAY_HOST_ID } from './visible.ts'
18
+ import { captureEntrySource } from './page-script.ts'
19
+ import { MAX_REFERENCE_TEXT } from '../reference-text.ts'
20
+ export { MAX_REFERENCE_TEXT } from '../reference-text.ts'
21
+
22
+ /**
23
+ * The bound the service and the page bar share. The bar trims an over-long
24
+ * paste before it crosses the intent channel; the service re-applies the same
25
+ * bound because a page is low-trust.
26
+ */
27
+ export const MAX_REFERENCE_COMMENT = 2000
28
+ export const REFERENCE_INTENT_CHANNEL = 'dsh-browser-ref:intent'
29
+ export const MAX_FRAME_SELECTOR = 200
30
+ export const MAX_FRAME_EVENTS = 24
31
+ export const MAX_FRAME_TEXT = MAX_REFERENCE_TEXT
32
+
33
+ /** One row of the single merged context menu. */
34
+ /** Which element a right-click action explicitly names. */
35
+ export type ReferenceTargetKind = 'text' | 'image' | 'table'
36
+
37
+ export interface ReferenceMenuItem {
38
+ readonly id: string
39
+ readonly label: string
40
+ readonly kind: 'reference' | 'role' | 'separator'
41
+ readonly role?: 'copy' | 'cut' | 'paste' | 'selectAll'
42
+ /** Explicit target of this action; absent on the ordinary edit roles. */
43
+ readonly target?: ReferenceTargetKind
44
+ }
45
+
46
+ /** What the browser's real context-menu event reported about the clicked node. */
47
+ export interface ReferenceMenuContext {
48
+ readonly hasSelection?: boolean
49
+ readonly mediaType?: string
50
+ }
51
+
52
+ /**
53
+ * The browser's ordinary edit items are kept, with the reference actions added
54
+ * by the SAME owner. One menu, one popup: two adapters each opening their own
55
+ * menu was the failure mode the design calls out (§3.1:59).
56
+ *
57
+ * A right-click on an image or a selection inside a table gets its OWN action,
58
+ * so "quote this image" never depends on the selection still covering the node
59
+ * (§3.2/§3.3). Copy/cut/paste/select-all roles always stay in this one menu.
60
+ */
61
+ export function referenceMenuTemplate(context: ReferenceMenuContext = {}): readonly ReferenceMenuItem[] {
62
+ const actions: ReferenceMenuItem[] = [
63
+ { id: 'dsh-browser-reference-text', label: '引用选中的文字', kind: 'reference', target: 'text' },
64
+ ]
65
+ if (context.mediaType === 'image') {
66
+ actions.push({ id: 'dsh-browser-reference-image', label: '引用这张图片', kind: 'reference', target: 'image' })
67
+ }
68
+ if (context.hasSelection === true) {
69
+ actions.push({ id: 'dsh-browser-reference-table', label: '引用选中的表格', kind: 'reference', target: 'table' })
70
+ }
71
+ return [
72
+ ...actions,
73
+ { id: 'dsh-browser-reference-separator', label: '', kind: 'separator' },
74
+ { id: 'dsh-browser-copy', label: '复制', kind: 'role', role: 'copy' },
75
+ { id: 'dsh-browser-cut', label: '剪切', kind: 'role', role: 'cut' },
76
+ { id: 'dsh-browser-paste', label: '粘贴', kind: 'role', role: 'paste' },
77
+ { id: 'dsh-browser-select-all', label: '全选', kind: 'role', role: 'selectAll' },
78
+ ]
79
+ }
80
+
81
+ /** A CSS selector is accepted only if it is short and free of injection syntax. */
82
+ export function validateFrameSelector(value: unknown): string | undefined {
83
+ if (typeof value !== 'string') return undefined
84
+ const selector = value.trim()
85
+ if (selector === '' || selector.length > MAX_FRAME_SELECTOR) return undefined
86
+ if (/[{}<>;`$\\]/.test(selector)) return undefined
87
+ if (selector.includes('/*') || selector.includes('*/')) return undefined
88
+ return selector
89
+ }
90
+
91
+ /** Wrap a one-shot or resident page expression in the same typed shell. */
92
+ function pageEval(body: string): string {
93
+ return '(function (spec) { try { ' + body + ' } catch (error) { '
94
+ + 'return JSON.stringify({ ok: false, reason: "script-error: " + String(error) }) '
95
+ + '} })(arguments[0] || {})'
96
+ }
97
+
98
+ /**
99
+ * Install the resident selection entry. Listeners survive the return value.
100
+ * The saved Range is what keeps a `mousedown` on the button from collapsing
101
+ * the selection before the capture runs (design §3.1:222).
102
+ */
103
+ export function overlayScript(): string {
104
+ const body = [
105
+ 'if (window.__dshRefOverlayInstalled) return JSON.stringify({ ok: true, already: true })',
106
+ // The bar freezes the COMPLETE capture (ordered text runs, assets, table
107
+ // ranges, anchors), not only its words. Installed once per document, in its
108
+ // own function scope so the page library cannot shadow our locals.
109
+ 'if (typeof window.__dshRefCapture !== "function") { window.__dshRefCapture = ' + captureEntrySource() + ' }',
110
+ 'var bridge = null',
111
+ 'var channel = "postMessage"',
112
+ 'if (window.__dshRef && typeof window.__dshRef.intent === "function") { bridge = window.__dshRef; channel = "preload" }',
113
+ 'else if (window.bridge && typeof window.bridge.referenceIntent === "function") { bridge = window.bridge; channel = "bridge" }',
114
+ // Three-state §3: a compact comment bar beside the selection, not a bare
115
+ // button. The comment is optional; confirming with an empty box quotes the
116
+ // selection unchanged.
117
+ // One overlay per document. A second injection (hot reload, retry, two carriers) used to leave the
118
+ // previous bar in the page with its old comment still typed in it — reported as "信息残留".
119
+ 'var stale = document.getElementById("' + OVERLAY_HOST_ID + '")',
120
+ 'if (stale && stale.parentNode) stale.parentNode.removeChild(stale)',
121
+ 'var host = document.createElement("div")',
122
+ 'host.id = "' + OVERLAY_HOST_ID + '"',
123
+ 'host.setAttribute("role", "group")',
124
+ 'host.setAttribute("aria-label", String(spec.label || "网页引用"))',
125
+ // No fixed width: the bar starts as a short field and grows with the
126
+ // comment, so it never covers a paragraph of the page it quotes.
127
+ 'host.style.cssText = "all:initial;position:fixed;z-index:2147483645;display:none;box-sizing:border-box;width:auto;min-width:0;max-width:min(360px,calc(100vw - 16px));background:#fff;color:#1a1a1a;border:0;border-radius:24px;corner-shape:round;padding:6px;font:400 13px/20px system-ui,sans-serif;box-shadow:0 0 0 .5px rgba(0,0,0,.14),0 6px 20px rgba(0,0,0,.18);pointer-events:auto"',
128
+ 'var preview = document.createElement("div")',
129
+ // Keep the frozen excerpt available to the controller; the selected page
130
+ // text itself remains the visible preview beside the compact comment bar.
131
+ 'preview.setAttribute("aria-hidden", "true")',
132
+ 'preview.style.cssText = "all:initial;display:none"',
133
+ 'var input = document.createElement("textarea")',
134
+ 'input.rows = 1',
135
+ 'input.maxLength = ' + MAX_REFERENCE_COMMENT,
136
+ 'input.setAttribute("aria-label", "添加评论(可选)")',
137
+ 'input.setAttribute("placeholder", "添加可选评论…")',
138
+ // `field-sizing: content` is what makes "grow while typing, then wrap"
139
+ // possible: the field follows its text until `max-width`, then the extra
140
+ // text wraps and the bar gets taller instead of wider.
141
+ 'input.cols = 8',
142
+ 'input.style.cssText = "all:initial;display:block;flex:0 1 auto;min-width:96px;max-width:236px;min-height:28px;max-height:88px;box-sizing:border-box;resize:none;overflow-y:auto;overflow-x:hidden;overflow-wrap:anywhere;word-break:break-word;white-space:pre-wrap;background:transparent;color:#1a1a1a;border:0;border-radius:8px;padding:4px 8px;font:400 13px/20px system-ui,sans-serif;field-sizing:content"',
143
+ 'var confirm = document.createElement("button")',
144
+ 'confirm.setAttribute("type", "button")',
145
+ 'confirm.id = "' + OVERLAY_HOST_ID + '-add"',
146
+ // The only thing that changed: the bare "✓" glyph became a stroked check in
147
+ // inline SVG, so it inherits CanvasText and stays crisp at any zoom. The
148
+ // button itself keeps the bar's own grey, DSH-style chrome.
149
+ // A font glyph, not an inline SVG. Measured on a real page: the stroked SVG inside this button
150
+ // painted nothing at all (a white disc with no mark), so the only visible state was "an empty
151
+ // circle". A text glyph renders in every case and inherits colour normally.
152
+ "confirm.textContent = '✓'",
153
+ 'confirm.setAttribute("aria-label", "引用所选内容")',
154
+ 'confirm.title = "引用所选内容"',
155
+ // White circle, dark check, both forced: a page stylesheet used to win the `background` while the
156
+ // mark stayed light, and the pair drifted apart. Inline `!important` outranks a page's own
157
+ // `!important`, so the circle and the glyph can no longer disagree.
158
+ 'confirm.style.cssText = "all:initial;display:inline-flex!important;align-items:center!important;justify-content:center!important;flex:none;box-sizing:border-box;width:28px;height:28px;border-radius:50%;corner-shape:round;border:0!important;font:600 18px/1 system-ui,sans-serif;cursor:pointer"',
159
+ // A compact status line: the failure reason (nothing selected), the note
160
+ // length near its bound, and the post-add confirmation all land here.
161
+ 'var status = document.createElement("span")',
162
+ 'status.setAttribute("role", "status")',
163
+ 'status.setAttribute("aria-live", "polite")',
164
+ 'status.style.cssText = "all:initial;position:absolute;left:6px;right:6px;top:calc(100% + 6px);box-sizing:border-box;color:#1a1a1a;background:#fff;border-radius:8px;padding:6px 10px;font:400 12px/18px system-ui,sans-serif;box-shadow:0 2px 8px rgba(0,0,0,.16);overflow-wrap:anywhere"',
165
+ 'var footer = document.createElement("div")',
166
+ 'footer.style.cssText = "all:initial;display:contents"',
167
+ 'var entryStyle = document.createElement("style")',
168
+ 'entryStyle.textContent = "#' + OVERLAY_HOST_ID + ' span:empty{display:none!important}'
169
+ + '#' + OVERLAY_HOST_ID + ' button:focus-visible{outline:2px solid Highlight;outline-offset:2px}'
170
+ + '#' + OVERLAY_HOST_ID + '-add:disabled{cursor:default}'
171
+ + '#' + OVERLAY_HOST_ID + ' textarea:focus-visible{outline:0}"',
172
+ 'host.appendChild(entryStyle)',
173
+ 'var row = document.createElement("div")',
174
+ 'row.style.cssText = "all:initial;display:flex;align-items:center;gap:6px"',
175
+ 'host.appendChild(preview)',
176
+ 'row.appendChild(input)',
177
+ 'footer.appendChild(confirm)',
178
+ 'footer.appendChild(status)',
179
+ 'row.appendChild(footer)',
180
+ 'host.appendChild(row)',
181
+ 'var savedRange = null',
182
+ // The page selection is destroyed the moment the comment field takes focus,
183
+ // so its text is frozen here and submitted with the intent; the host locates
184
+ // it again from the frozen quote instead of re-reading a dead selection.
185
+ 'var frozenText = ""',
186
+ // The COMPLETE capture frozen at the same moment: ordered text runs, image
187
+ // sources and table ranges with their anchors. A text-only freeze loses
188
+ // images/tables and lets a duplicate paragraph be re-located by wording.
189
+ 'var frozenCapture = null',
190
+ 'var dismissedText = ""',
191
+ 'function textField(node) {',
192
+ ' if (!node || node.nodeType !== 1) return false',
193
+ ' var tag = String(node.tagName || "").toUpperCase()',
194
+ ' return tag === "TEXTAREA" || tag === "INPUT" || node.isContentEditable === true',
195
+ '}',
196
+ 'function clip(text, max) {',
197
+ ' var value = String(text || "").replace(/[ \\t\\r\\n]+/g, " ").trim()',
198
+ ' return value.length > max ? value.slice(0, max) + "…" : value',
199
+ '}',
200
+ // One place decides what the bar says about the pending quote, so the
201
+ // preview, the disabled state and the hint can never disagree.
202
+ 'function setQuote(text) {',
203
+ ' var value = clip(text, 90)',
204
+ ' preview.textContent = value === "" ? "" : "「" + value + "」"',
205
+ ' preview.style.display = "none"',
206
+ ' confirm.disabled = value === ""',
207
+ ' confirm.style.opacity = value === "" ? "0.9" : "1"',
208
+ ' status.textContent = value === "" ? "请先在网页上选中内容" : ""',
209
+ ' status.style.color = value === "" ? "#b42318" : "GrayText"',
210
+ '}',
211
+ 'function freeze() {',
212
+ // Once focus is inside the bar, the page selection is already gone and the
213
+ // bar's own selection (a Ctrl+A of the human's note) is what getSelection()
214
+ // reports. The first freeze stays authoritative: rewriting it here is what
215
+ // turned a page quote into the comment.
216
+ ' if (document.activeElement && host.contains(document.activeElement)) return',
217
+ ' var selection = window.getSelection ? window.getSelection() : null',
218
+ ' var text = selection ? String(selection.toString()) : ""',
219
+ ' if (text) { frozenText = text; setQuote(text) }',
220
+ ' var range = currentRange()',
221
+ ' if (range) savedRange = range',
222
+ // Freeze once, before focus moves: clicking the comment field collapses the
223
+ // page selection, so this is the last moment the real range exists.
224
+ ' if (range && frozenCapture === null && typeof window.__dshRefCapture === "function") {',
225
+ ' try { frozenCapture = window.__dshRefCapture({ context: 32 }) } catch (error) { frozenCapture = null }',
226
+ ' if (frozenCapture && frozenCapture.ok !== true) frozenCapture = null',
227
+ ' }',
228
+ '}',
229
+ // Which way round the page is painted. System colour keywords (`Canvas`,
230
+ // `CanvasText`) read the OS preference, not the page, which is how a dark
231
+ // article ended up with an invisible black-on-black comment field. The bar
232
+ // now measures the page instead and paints explicitly.
233
+ 'function colorOf(value) {',
234
+ ' var text = String(value || "")',
235
+ ' var open = text.indexOf("(")',
236
+ ' if (open < 0) return null',
237
+ ' var parts = text.slice(open + 1, text.lastIndexOf(")")).split(/[ ,\\/]+/)',
238
+ ' var numbers = []',
239
+ ' for (var i = 0; i < parts.length; i += 1) { var n = parseFloat(parts[i]); if (!isNaN(n)) numbers.push(n) }',
240
+ ' if (numbers.length < 3) return null',
241
+ ' return { a: numbers.length > 3 ? numbers[3] : 1, r: numbers[0], g: numbers[1], b: numbers[2] }',
242
+ '}',
243
+ 'function brightness(value) {',
244
+ ' var color = colorOf(value)',
245
+ ' if (!color || color.a === 0) return -1',
246
+ ' return (0.299 * color.r + 0.587 * color.g + 0.114 * color.b) / 255',
247
+ '}',
248
+ 'function pageIsDark(range) {',
249
+ // A carrier without a full style engine must not lose the whole bar: an
250
+ // unknown page is treated as light, which is still readable.
251
+ ' try {',
252
+ ' var node = range ? range.startContainer : null',
253
+ ' var element = node && node.nodeType === 1 ? node : (node && node.parentElement ? node.parentElement : null)',
254
+ ' while (element) {',
255
+ ' var painted = brightness(getComputedStyle(element).backgroundColor)',
256
+ ' if (painted >= 0) return painted < 0.5',
257
+ ' element = element.parentElement',
258
+ ' }',
259
+ ' var bodyPainted = brightness(getComputedStyle(document.body).backgroundColor)',
260
+ ' if (bodyPainted >= 0) return bodyPainted < 0.5',
261
+ ' var rootPainted = brightness(getComputedStyle(document.documentElement).backgroundColor)',
262
+ ' if (rootPainted >= 0) return rootPainted < 0.5',
263
+ // A page that only sets `color` still says which way it thinks; read that.
264
+ ' return brightness(getComputedStyle(document.body).color) > 0.5',
265
+ ' } catch (error) { return false }',
266
+ '}',
267
+ 'function paint(dark) {',
268
+ ' var surface = dark ? "#1c1c1e" : "#ffffff"',
269
+ ' var ink = dark ? "#f5f5f7" : "#1a1a1a"',
270
+ ' host.style.background = surface',
271
+ ' host.style.color = ink',
272
+ ' host.style.boxShadow = dark',
273
+ ' ? "0 0 0 .5px rgba(255,255,255,.16),0 6px 20px rgba(0,0,0,.45)"',
274
+ ' : "0 0 0 .5px rgba(0,0,0,.14),0 6px 20px rgba(0,0,0,.18)"',
275
+ ' input.style.color = ink',
276
+ ' confirm.style.background = ink',
277
+ ' confirm.style.color = surface',
278
+ ' status.style.background = surface',
279
+ ' status.style.color = ink',
280
+ '}',
281
+ 'var painted = null',
282
+ 'function paintFor(range) {',
283
+ ' var dark = pageIsDark(range)',
284
+ ' if (painted === dark) return',
285
+ ' painted = dark',
286
+ ' paint(dark)',
287
+ '}',
288
+ 'var listeners = []',
289
+ 'function listen(target, name, fn) {',
290
+ // A carrier document without event support must not break installation: the
291
+ // bar is an enhancement on top of a page we do not own.
292
+ ' if (!target || typeof target.addEventListener !== "function") return',
293
+ ' target.addEventListener(name, fn, true); listeners.push({ target: target, name: name, fn: fn })',
294
+ '}',
295
+ 'function currentRange() {',
296
+ ' var selection = window.getSelection ? window.getSelection() : null',
297
+ ' if (!selection || selection.rangeCount === 0 || selection.isCollapsed) return null',
298
+ ' try { return selection.getRangeAt(0).cloneRange() } catch (error) { return null }',
299
+ '}',
300
+ // The bar belongs above the FIRST selected character, not above the bounding box of the whole
301
+ // selection: a selection spanning several lines has a box that starts at the left margin, so the
302
+ // bar used to hang over unrelated text. Measured in the sidebar and reported as "太丑了".
303
+ 'function firstCharBox(range) {',
304
+ // 首选选区**第一行**的矩形:它就是「划线第一个字所在的那一行」,高只有一行。
305
+ // 旧的实现先折叠再按一个单元扩一格,遇到跨块选区时 endContainer 是元素节点,
306
+ // 扩一格会得到整块的高度,`place()` 据此认为「上方放不下」并把它压到面板最底部。
307
+ ' var lines = range.getClientRects ? range.getClientRects() : null',
308
+ ' if (lines && lines.length) return lines[0]',
309
+ ' try {',
310
+ ' var head = range.cloneRange()',
311
+ ' head.collapse(true)',
312
+ ' var unit = head.cloneRange()',
313
+ ' if (unit.endContainer && unit.endContainer.nodeType === 3) {',
314
+ ' var length = unit.endContainer.data.length',
315
+ ' unit.setEnd(unit.endContainer, Math.min(unit.endOffset + 1, length))',
316
+ ' } else if (unit.endContainer) {',
317
+ ' unit.setEnd(unit.endContainer, Math.min(unit.endOffset + 1, unit.endContainer.childNodes.length || 1))',
318
+ ' }',
319
+ ' var box = unit.getBoundingClientRect()',
320
+ ' if (box.width || box.height) return box',
321
+ ' } catch (error) { /* fall back to the line rects below */ }',
322
+ ' var rects = range.getClientRects ? range.getClientRects() : null',
323
+ ' if (rects && rects.length) return rects[0]',
324
+ ' return range.getBoundingClientRect()',
325
+ '}',
326
+ 'function place(range) {',
327
+ ' var box = firstCharBox(range)',
328
+ ' var width = host.offsetWidth || 240',
329
+ ' var height = host.offsetHeight || 76',
330
+ ' var viewWidth = window.innerWidth || 1024',
331
+ ' var viewHeight = window.innerHeight || 768',
332
+ // A detached node or a zero-width anchor reports an empty box: placing the
333
+ // bar from it parked the bar in the corner, looking like a stuck popup.
334
+ ' if (!box.width && !box.height) { host.style.display = "none"; return }',
335
+ // 选区当前必须有一行在视口里。整段选区可能已经滚出屏幕(第一行在下方几百像素),
336
+ // 这时按它算出来的位置只会被夹到面板边缘,看起来就是「浮条卡在底部」——那种情况直接不显示。
337
+ ' if (box.bottom < 0 || box.top > viewHeight) { host.style.display = "none"; return }',
338
+ // Left-aligned with the first character, shifted back only when that would leave the viewport.
339
+ ' var left = Math.max(8, Math.min(box.left, viewWidth - width - 8))',
340
+ // Prefer above the selection so the quoted text stays readable, then below.
341
+ ' var above = box.top - height - 10',
342
+ ' var top = above >= 8 ? above : Math.min(box.bottom + 10, viewHeight - height - 8)',
343
+ ' top = Math.max(8, Math.min(top, viewHeight - height - 8))',
344
+ ' host.style.left = left + "px"; host.style.top = top + "px"',
345
+ '}',
346
+ // A settled selection is the right moment to take the complete snapshot:
347
+ // keyboard selection (Shift+arrows, then Tab into the note) never fires a
348
+ // mousedown, and without this its images and tables degraded to a wording
349
+ // search. Debounced, because `selectionchange` fires during the drag.
350
+ 'var captureTimer = null',
351
+ 'function captureSoon() {',
352
+ ' if (typeof window.__dshRefCapture !== "function") return',
353
+ ' if (captureTimer !== null && typeof clearTimeout === "function") clearTimeout(captureTimer)',
354
+ ' captureTimer = setTimeout(function () {',
355
+ ' captureTimer = null',
356
+ ' if (document.activeElement && host.contains(document.activeElement)) return',
357
+ ' var range = currentRange()',
358
+ ' if (!range) return',
359
+ ' var text = String(window.getSelection ? window.getSelection() : "")',
360
+ ' if (text === "" || text !== frozenText) return',
361
+ ' try {',
362
+ ' var snap = window.__dshRefCapture({ context: 32 })',
363
+ ' if (snap && snap.ok === true) frozenCapture = snap',
364
+ ' } catch (error) { /* the click path will try again */ }',
365
+ ' }, 180)',
366
+ '}',
367
+ 'function refresh() {',
368
+ ' var range = currentRange()',
369
+ // Hiding keeps the frozen capture: the same quote can be re-shown when the
370
+ // selection is re-established, and a click may still need it.
371
+ ' if (!range) { host.style.display = "none"; return }',
372
+ ' var selection = window.getSelection()',
373
+ ' if (dismissedText && String(selection.toString()) === dismissedText) { host.style.display = "none"; return }',
374
+ ' savedRange = range',
375
+ ' var live = String(selection || "")',
376
+ ' if (live !== frozenText) {',
377
+ // A different selection: the old snapshot no longer describes it.
378
+ ' frozenText = live',
379
+ ' frozenCapture = null',
380
+ ' setQuote(live)',
381
+ // The comment belongs to the selection it was written for. Carrying it into a new selection made the
382
+ // bar look like it had remembered a message the reader already sent.
383
+ ' input.value = ""',
384
+ ' status.textContent = ""',
385
+ ' confirm.style.opacity = "0.9"',
386
+ ' }',
387
+ ' if (frozenCapture === null) captureSoon()',
388
+ ' paintFor(range)',
389
+ // Re-attach when the page swapped its body out from under us; without this the bar was "shown" in
390
+ // a detached tree and the reader saw nothing.
391
+ ' if (!host.isConnected && !host.__dshAttached) { (document.documentElement || document.body).appendChild(host); host.__dshAttached = true }',
392
+ ' host.style.display = "block"; place(range)',
393
+ '}',
394
+ // The selection must survive clicking or typing in the bar (§3: 点击或输入
395
+ // 评论不会导致选区丢失).
396
+ 'listen(document, "mousedown", function (event) {',
397
+ ' if (host.contains(event.target)) {',
398
+ ' // Freeze BEFORE the focus move: clicking the textarea collapses the page',
399
+ ' // selection, and the captured content must survive that.',
400
+ ' freeze()',
401
+ ' // A text field must keep its native default, otherwise it can never be',
402
+ ' // focused or typed into (three-state §3).',
403
+ ' if (textField(event.target)) return',
404
+ ' event.preventDefault()',
405
+ ' return',
406
+ ' }',
407
+ ' dismissedText = ""',
408
+ ' freeze()',
409
+ '})',
410
+ 'listen(document, "mouseup", function (event) { if (!host.contains(event.target)) setTimeout(refresh, 0) })',
411
+ 'listen(document, "selectionchange", function () { if (!host.contains(document.activeElement)) refresh() })',
412
+ 'listen(host, "scroll", function (event) { event.stopPropagation() })',
413
+ // Scrolling is reading, not cancelling. Follow the quoted range while it is
414
+ // still on screen; hide only once it has scrolled out of view.
415
+ 'listen(document, "scroll", function (event) {',
416
+ ' if (host.contains(event.target)) return',
417
+ ' if (host.style.display !== "block" || !savedRange) { host.style.display = "none"; return }',
418
+ ' var box = savedRange.getBoundingClientRect()',
419
+ ' var viewHeight = window.innerHeight || 768',
420
+ ' if (box.bottom < 0 || box.top > viewHeight) { host.style.display = "none"; return }',
421
+ ' place(savedRange)',
422
+ '}, true)',
423
+ 'listen(window, "resize", function () { if (host.style.display === "block" && savedRange) place(savedRange) })',
424
+ 'listen(document, "keydown", function (event) {',
425
+ // A dismissed quote was blocked until the next mousedown, so re-selecting
426
+ // the same words with Shift+arrows (or Ctrl+A) never brought the bar back.
427
+ // Any key that is not typed INSIDE the bar starts a fresh selection.
428
+ ' if (event.key !== "Escape" && !host.contains(document.activeElement)) dismissedText = ""',
429
+ ' if (event.key === "Escape") {',
430
+ ' var selection = window.getSelection ? window.getSelection() : null',
431
+ ' dismissedText = selection ? String(selection.toString()) : ""',
432
+ ' input.value = ""',
433
+ ' host.style.display = "none"',
434
+ ' }',
435
+ '})',
436
+ // IME: a composition Enter must never confirm (§3 中文输入法组词过程不会误确认).
437
+ 'listen(input, "keydown", function (event) {',
438
+ ' if (event.key !== "Enter") return',
439
+ ' if (event.isComposing === true || event.keyCode === 229) return',
440
+ ' if (event.ctrlKey || event.metaKey) { event.preventDefault(); event.stopPropagation(); submit(event) }',
441
+ '})',
442
+ // Never read the live selection here: the comment field can hold a Ctrl+A
443
+ // selection of the human's own note, and that must never replace the page
444
+ // quote. `frozenText` was captured before the field took focus.
445
+ 'function submit(event) {',
446
+ ' var selectionText = frozenText',
447
+ // Keyboard submission (Tab into the note, then Ctrl+Enter) never passes
448
+ // through the bar's mousedown, so the rich capture was never taken and an
449
+ // image/table quote degraded to a wording search. Capture now if the page
450
+ // selection is still alive.
451
+ ' if (frozenCapture === null && typeof window.__dshRefCapture === "function") {',
452
+ // Only take it when the live selection is still the quoted text: capturing
453
+ // a different range here would attach content the bar never showed.
454
+ ' var live = window.getSelection ? String(window.getSelection()) : ""',
455
+ ' if (selectionText === "" || live === selectionText) {',
456
+ ' try { frozenCapture = window.__dshRefCapture({ context: 32 }) } catch (error) { frozenCapture = null }',
457
+ ' if (frozenCapture && frozenCapture.ok !== true) frozenCapture = null',
458
+ ' }',
459
+ ' }',
460
+ // Nothing frozen: the user clicked through a stale bar. Say why instead of
461
+ // closing, which used to look like the click did nothing at all.
462
+ ' if (selectionText === "" && frozenCapture === null) { setQuote(""); return }',
463
+ ' var comment = String(input.value || "").trim()',
464
+ ' if (comment.length > ' + MAX_REFERENCE_COMMENT + ') comment = comment.slice(0, ' + MAX_REFERENCE_COMMENT + ')',
465
+ ' dismissedText = selectionText',
466
+ ' var intent = {',
467
+ ' type: "' + REFERENCE_INTENT_CHANNEL + '",',
468
+ ' entry: "page-overlay", origin: "user-selection",',
469
+ ' hasSelection: savedRange !== null || selectionText !== "",',
470
+ ' selectionText: selectionText,',
471
+ // The complete ordered snapshot taken while the real range still existed;
472
+ // the host consumes it verbatim instead of searching the page by wording.
473
+ ' capture: frozenCapture,',
474
+ ' isTrusted: event ? event.isTrusted === true : false,',
475
+ ' comment: comment,',
476
+ ' frameSelector: null,',
477
+ ' capabilities: []',
478
+ ' }',
479
+ ' if (bridge) { if (typeof bridge.intent === "function") bridge.intent(intent); else bridge.referenceIntent(intent) }',
480
+ ' else {',
481
+ ' window.postMessage(intent, "*")',
482
+ // No preload bridge (the Desktop sidebar carrier): keep the intent where the',
483
+ // host can collect it. The host polls __dshRefTake every tick.',
484
+ ' var queue = window.__dshRefIntents || (window.__dshRefIntents = [])',
485
+ ' queue.push(intent)',
486
+ ' }',
487
+ ' frozenText = ""',
488
+ ' frozenCapture = null',
489
+ ' input.value = ""',
490
+ ' setQuote("")',
491
+ ' preview.textContent = ""',
492
+ ' preview.style.display = "none"',
493
+ ' confirm.style.opacity = "0.9"',
494
+ // Leave NOTHING behind: the bar closes the moment the intent is queued.
495
+ // It used to stay for 1.2 s saying "已提交,正在加入…", and a throttled
496
+ // timer in a background webContents could leave that strip pinned in a
497
+ // corner for minutes — stray UI the user could not dismiss, describing a
498
+ // selection that no longer existed.
499
+ ' status.style.color = "GrayText"',
500
+ ' status.textContent = ""',
501
+ ' host.style.display = "none"',
502
+ '}',
503
+ 'listen(confirm, "click", function (event) { event.preventDefault(); event.stopPropagation(); submit(event) })',
504
+ // Only speak up when the note gets near the bound the host enforces; a
505
+ // counter on every keystroke is noise.
506
+ 'listen(input, "input", function () {',
507
+ ' if (document.activeElement !== input) return',
508
+ ' var length = String(input.value || "").length',
509
+ ' if (length > ' + MAX_REFERENCE_COMMENT * 0.8 + ') {',
510
+ ' status.style.color = length > ' + MAX_REFERENCE_COMMENT + ' ? "#b42318" : "GrayText"',
511
+ ' status.textContent = "评论 " + length + "/" + ' + MAX_REFERENCE_COMMENT + ' + " 字"',
512
+ ' } else if (status.textContent && status.textContent.indexOf("评论 ") === 0) {',
513
+ ' status.textContent = ""',
514
+ ' }',
515
+ // The bar is only as wide as its text now, so it has to be re-placed as it
516
+ // grows: otherwise a comment typed at the right edge walks off screen.
517
+ ' if (savedRange) setTimeout(function () { place(savedRange) }, 0)',
518
+ '})',
519
+ // Attach to the ROOT element, not to body: pages that replace <body> after load (SPA shells, some CMS
520
+ // templates) silently detached the bar, so selecting real article text showed nothing at all —
521
+ // measured on a CCTV article reached from 百度新闻 ("shown: none" while the same code worked on other
522
+ // sites). A later re-attach guard in show() covers the remaining cases.
523
+ ';(document.documentElement || document.body).appendChild(host)',
524
+ // Collection point for the carrier without a preload bridge. Defined once,
525
+ // so a re-injection over a live overlay cannot double-collect intents.',
526
+ 'window.__dshRefTake = function () {',
527
+ ' var queue = window.__dshRefIntents',
528
+ ' if (!queue || !queue.length) return null',
529
+ ' return queue.shift()',
530
+ '}',
531
+ 'window.__dshRefOverlayInstalled = true',
532
+ 'window.__dshRefOverlayDispose = function () {',
533
+ ' if (captureTimer !== null && typeof clearTimeout === "function") clearTimeout(captureTimer)',
534
+ ' for (var i = 0; i < listeners.length; i += 1) {',
535
+ ' try { listeners[i].target.removeEventListener(listeners[i].name, listeners[i].fn, true) } catch (error) {}',
536
+ ' }',
537
+ ' if (host.parentNode) host.parentNode.removeChild(host)',
538
+ ' var notice = typeof document.getElementById === "function" ? document.getElementById("__dsh-ref-notice") : null',
539
+ ' if (notice && notice.parentNode) notice.parentNode.removeChild(notice)',
540
+ ' window.__dshRefOverlayInstalled = false',
541
+ ' window.__dshRefOverlayDispose = null',
542
+ ' return listeners.length',
543
+ '}',
544
+ 'return JSON.stringify({ ok: true, installed: true, channel: channel })',
545
+ ].join('\n')
546
+ return pageEval(body)
547
+ }
548
+
549
+ /**
550
+ * Turn an arguments[0]-based page expression into a standalone expression that
551
+ * Electron's executeJavaScript can run in the top-level main world, where
552
+ * `arguments` does not exist. The CDP execute path keeps the original form.
553
+ */
554
+ export function standaloneScript(script: string, spec: Record<string, unknown> = {}): string {
555
+ return script.replace('(arguments[0] || {})', `(${JSON.stringify(spec)})`)
556
+ }
557
+
558
+ /** Remove the resident entry and all its listeners (idempotent, §11.3). */
559
+ export function overlayDisposeScript(): string {
560
+ const body = [
561
+ 'if (typeof window.__dshRefOverlayDispose !== "function") return JSON.stringify({ ok: true, removed: 0 })',
562
+ 'var count = window.__dshRefOverlayDispose()',
563
+ 'return JSON.stringify({ ok: true, removed: count })',
564
+ ].join('\n')
565
+ return pageEval(body)
566
+ }
567
+
568
+ /** The untrusted shape a frame capture returns. */
569
+ export interface FrameCaptureResult {
570
+ readonly ok: boolean
571
+ readonly reason?: string
572
+ readonly url?: string
573
+ readonly frameUrl?: string
574
+ readonly title?: string
575
+ readonly frameSelector?: string
576
+ readonly events?: readonly unknown[]
577
+ }
578
+
579
+ /**
580
+ * Collect a same-origin iframe's selection, images and tables. The frame's URL
581
+ * is read from the iframe element in the TOP document, never from a payload
582
+ * field the frame could forge; cross-origin frames answer with an explicit
583
+ * `frame-inaccessible` reason rather than a fabricated identity.
584
+ */
585
+ export function frameCaptureScript(): string {
586
+ const body = [
587
+ 'var selector = String(spec.frameSelector || "")',
588
+ 'var element = null',
589
+ 'try { element = document.querySelector(selector) } catch (error) { element = null }',
590
+ 'if (!element || String(element.tagName || "").toUpperCase() !== "IFRAME") {',
591
+ ' return JSON.stringify({ ok: false, reason: "frame-not-found" })',
592
+ '}',
593
+ 'var frameDoc = null',
594
+ 'try { frameDoc = element.contentDocument } catch (error) { frameDoc = null }',
595
+ 'if (!frameDoc) return JSON.stringify({ ok: false, reason: "frame-inaccessible" })',
596
+ 'var frameUrl = ""',
597
+ 'try { frameUrl = String(element.contentWindow.location.href) } catch (error) {',
598
+ ' frameUrl = String(element.getAttribute("src") || "")',
599
+ '}',
600
+ 'if (!frameUrl) frameUrl = String(element.getAttribute("src") || "")',
601
+ 'var result = (function (document, window, location) {',
602
+ ' return (' + captureEntrySource() + ')(spec)',
603
+ '})(frameDoc, element.contentWindow, { href: frameUrl })',
604
+ 'result.url = String(location.href)',
605
+ 'result.frameUrl = frameUrl',
606
+ 'result.frameSelector = selector',
607
+ 'return JSON.stringify(result)',
608
+ ].join('\n')
609
+ return pageEval(body)
610
+ }
611
+
612
+ /** Validate a frame result field by field; the page cannot self-report identity. */
613
+ export function validateFrameCapture(value: unknown, requestedSelector: string): FrameCaptureResult | undefined {
614
+ if (typeof value !== 'object' || value === null) return undefined
615
+ const row = value as Record<string, unknown>
616
+ if (row.ok !== true) return { ok: false, reason: typeof row.reason === 'string' ? row.reason.slice(0, 100) : 'frame-unavailable' }
617
+ if (typeof row.url !== 'string' || typeof row.frameUrl !== 'string') return undefined
618
+ const events = Array.isArray(row.events) ? row.events.slice(0, MAX_FRAME_EVENTS) : []
619
+ return {
620
+ ok: true,
621
+ url: row.url.slice(0, 4_000),
622
+ frameUrl: row.frameUrl.slice(0, 4_000),
623
+ title: typeof row.title === 'string' ? row.title.slice(0, 500) : '',
624
+ // Identity always comes from the host's request, not the page payload.
625
+ frameSelector: requestedSelector,
626
+ events,
627
+ }
628
+ }
629
+
630
+ /** Hide any of our own UI before a screenshot; used by the overlay owner. */
631
+ export const OVERLAY_IDS = [OVERLAY_HOST_ID, HIGHLIGHT_HOST_ID] as const