effect-browser 0.3.0-beta.23 → 0.3.0-beta.25

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 (348) hide show
  1. package/README.md +437 -142
  2. package/dist/Action.d.mts +1 -1
  3. package/dist/Action.mjs +61 -9
  4. package/dist/Action.mjs.map +1 -1
  5. package/dist/Browser.d.mts +2 -2
  6. package/dist/Browser.mjs +2 -2
  7. package/dist/BrowserError.d.mts +2 -2
  8. package/dist/BrowserError.mjs +194 -41
  9. package/dist/BrowserError.mjs.map +1 -1
  10. package/dist/BrowserEvent.d.mts +2 -2
  11. package/dist/BrowserEvent.mjs +185 -35
  12. package/dist/BrowserEvent.mjs.map +1 -1
  13. package/dist/Cdp.d.mts +15 -0
  14. package/dist/Cdp.mjs +22 -0
  15. package/dist/Cdp.mjs.map +1 -0
  16. package/dist/Change.d.mts +2 -2
  17. package/dist/Change.mjs +40 -7
  18. package/dist/Change.mjs.map +1 -1
  19. package/dist/Frame.d.mts +2 -2
  20. package/dist/Frame.mjs +132 -14
  21. package/dist/Frame.mjs.map +1 -1
  22. package/dist/InputStyle.d.mts +153 -0
  23. package/dist/InputStyle.mjs +2 -0
  24. package/dist/Layout.d.mts +2 -0
  25. package/dist/Layout.mjs +123 -0
  26. package/dist/Layout.mjs.map +1 -0
  27. package/dist/Overlay.d.mts +2 -0
  28. package/dist/Overlay.mjs +58 -0
  29. package/dist/Overlay.mjs.map +1 -0
  30. package/dist/Page.d.mts +2 -2
  31. package/dist/Page.mjs +2 -2
  32. package/dist/PageTime.d.mts +2 -0
  33. package/dist/PageTime.mjs +17 -0
  34. package/dist/PageTime.mjs.map +1 -0
  35. package/dist/Pose.d.mts +2 -0
  36. package/dist/Pose.mjs +65 -0
  37. package/dist/Pose.mjs.map +1 -0
  38. package/dist/Site.d.mts +984 -0
  39. package/dist/Site.mjs +110 -0
  40. package/dist/Site.mjs.map +1 -0
  41. package/dist/Snapshot.d.mts +2 -2
  42. package/dist/Snapshot.mjs +87 -6
  43. package/dist/Snapshot.mjs.map +1 -1
  44. package/dist/Text.d.mts +2 -0
  45. package/dist/Text.mjs +45 -0
  46. package/dist/Text.mjs.map +1 -0
  47. package/dist/Window.d.mts +2 -2
  48. package/dist/Window.mjs +31 -6
  49. package/dist/Window.mjs.map +1 -1
  50. package/dist/ai/BrowserTools.d.mts +4987 -0
  51. package/dist/ai/BrowserTools.mjs +3 -0
  52. package/dist/ai/PageControl.d.mts +286 -0
  53. package/dist/ai/PageControl.mjs +426 -0
  54. package/dist/ai/PageControl.mjs.map +1 -0
  55. package/dist/ai/PromptCache.d.mts +16 -0
  56. package/dist/ai/PromptCache.mjs +72 -0
  57. package/dist/ai/PromptCache.mjs.map +1 -0
  58. package/dist/ai/Tabs.d.mts +2 -0
  59. package/dist/ai/Tabs.mjs +72 -0
  60. package/dist/ai/Tabs.mjs.map +1 -0
  61. package/dist/ai/ToolError.d.mts +34 -0
  62. package/dist/ai/ToolError.mjs +2 -0
  63. package/dist/ai/index.d.mts +6 -0
  64. package/dist/ai/index.mjs +6 -0
  65. package/dist/index.d.mts +7 -15
  66. package/dist/index.mjs +9 -8
  67. package/dist/{Action-24sLOubi.d.mts → internal/Action-CkanNTUw.d.mts} +64 -4
  68. package/dist/{Browser-wZhwZSlG.d.mts → internal/Browser-DD9Vm1c-.d.mts} +80 -10
  69. package/dist/{Browser-BKPAbyys.mjs → internal/Browser-vzD7i2oj.mjs} +658 -495
  70. package/dist/internal/Browser-vzD7i2oj.mjs.map +1 -0
  71. package/dist/{BrowserError-BlcmLVzn.d.mts → internal/BrowserError-CsuRYcDX.d.mts} +187 -28
  72. package/dist/{BrowserEvent-lLqJ3GJS.d.mts → internal/BrowserEvent-tGPYYf6R.d.mts} +197 -18
  73. package/dist/internal/BrowserTools-Yi3lOX4h.mjs +497 -0
  74. package/dist/internal/BrowserTools-Yi3lOX4h.mjs.map +1 -0
  75. package/dist/{Style-AO4V7Czt.mjs → internal/InputStyle-CPzxoN4g.mjs} +94 -16
  76. package/dist/internal/InputStyle-CPzxoN4g.mjs.map +1 -0
  77. package/dist/{moment/Moment.mjs → internal/Moment-CstaX1mR.mjs} +49 -16
  78. package/dist/internal/Moment-CstaX1mR.mjs.map +1 -0
  79. package/dist/{moment/Moment.d.mts → internal/Moment-DOcldBdf.d.mts} +54 -21
  80. package/dist/internal/Page-BfGxn7oN.d.mts +1553 -0
  81. package/dist/{Page-BF5izr8R.mjs → internal/Page-DqF-tuTx.mjs} +62 -72
  82. package/dist/internal/Page-DqF-tuTx.mjs.map +1 -0
  83. package/dist/internal/Release-CFONkPDP.d.mts +39 -0
  84. package/dist/internal/Stage-D5ymSXDT.mjs +298 -0
  85. package/dist/internal/Stage-D5ymSXDT.mjs.map +1 -0
  86. package/dist/internal/Stillness-DCPeAN1a.mjs +1124 -0
  87. package/dist/internal/Stillness-DCPeAN1a.mjs.map +1 -0
  88. package/dist/internal/Supervisor-BcY_QNIY.d.mts +108 -0
  89. package/dist/internal/Supervisor-BcglY23c.mjs +531 -0
  90. package/dist/internal/Supervisor-BcglY23c.mjs.map +1 -0
  91. package/dist/internal/Tabs-dXMscIUQ.d.mts +52 -0
  92. package/dist/internal/TestPage-CYiYbh63.d.mts +159 -0
  93. package/dist/internal/ToolError-DArsRS2m.mjs +117 -0
  94. package/dist/internal/ToolError-DArsRS2m.mjs.map +1 -0
  95. package/dist/{plan/index.d.mts → internal/Walk-BNXcfZ2z.d.mts} +59 -35
  96. package/dist/{plan/index.mjs → internal/Walk-C5ky7uSf.mjs} +83 -51
  97. package/dist/internal/Walk-C5ky7uSf.mjs.map +1 -0
  98. package/dist/{ActionPort.mjs → internal/action-port-B5EkeGOR.mjs} +6 -12
  99. package/dist/internal/action-port-B5EkeGOR.mjs.map +1 -0
  100. package/dist/internal/cdp/workerd.d.mts +13 -0
  101. package/dist/internal/cdp/workerd.mjs +19 -0
  102. package/dist/internal/cdp/workerd.mjs.map +1 -0
  103. package/dist/{Clock.mjs → internal/clock-BKSAEf00.mjs} +13 -13
  104. package/dist/internal/clock-BKSAEf00.mjs.map +1 -0
  105. package/dist/{connection-2KHI4_KN.d.mts → internal/connection-BaB0vp1o.d.mts} +6 -6
  106. package/dist/{connection-CK83pvqP.mjs → internal/connection-C2X4GmXM.mjs} +19 -15
  107. package/dist/internal/connection-C2X4GmXM.mjs.map +1 -0
  108. package/dist/internal/events-DzCrww-y.mjs +72 -0
  109. package/dist/internal/events-DzCrww-y.mjs.map +1 -0
  110. package/dist/internal/fold.inpage-CyVZQHZL.d.mts +49 -0
  111. package/dist/internal/fold.inpage-uhrT-dOB.mjs +49 -0
  112. package/dist/internal/fold.inpage-uhrT-dOB.mjs.map +1 -0
  113. package/dist/internal/functions-jBOs6GKv.mjs +27 -0
  114. package/dist/internal/functions-jBOs6GKv.mjs.map +1 -0
  115. package/dist/{Geometry-DJx9qrYy.d.mts → internal/geometry-Dhj_ztJs.d.mts} +3 -3
  116. package/dist/{Geometry.mjs → internal/geometry-Lxyflb9J.mjs} +3 -12
  117. package/dist/internal/geometry-Lxyflb9J.mjs.map +1 -0
  118. package/dist/{Matching.mjs → internal/matching-Cs-UeOY0.mjs} +24 -19
  119. package/dist/internal/matching-Cs-UeOY0.mjs.map +1 -0
  120. package/dist/internal/page-DFQb-YOK.mjs +436 -0
  121. package/dist/internal/page-DFQb-YOK.mjs.map +1 -0
  122. package/dist/internal/pose.inpage-CBFeWcVa.mjs +1996 -0
  123. package/dist/internal/pose.inpage-CBFeWcVa.mjs.map +1 -0
  124. package/dist/{Url.mjs → internal/url-DB0pQYk6.mjs} +3 -12
  125. package/dist/internal/url-DB0pQYk6.mjs.map +1 -0
  126. package/dist/policy/Policy.d.mts +60 -6
  127. package/dist/policy/Policy.mjs +52 -9
  128. package/dist/policy/Policy.mjs.map +1 -1
  129. package/dist/policy/index.d.mts +2 -0
  130. package/dist/policy/index.mjs +2 -0
  131. package/dist/presentation/Film.d.mts +332 -0
  132. package/dist/presentation/Film.mjs +298 -0
  133. package/dist/presentation/Film.mjs.map +1 -0
  134. package/dist/presentation/Motion.d.mts +5 -1
  135. package/dist/presentation/Motion.mjs +16 -2
  136. package/dist/presentation/Motion.mjs.map +1 -1
  137. package/dist/presentation/Presentation.d.mts +48 -6
  138. package/dist/presentation/Presentation.mjs +28 -9
  139. package/dist/presentation/Presentation.mjs.map +1 -1
  140. package/dist/presentation/Stage.d.mts +40 -6
  141. package/dist/presentation/Stage.mjs +1 -262
  142. package/dist/presentation/index.d.mts +5 -0
  143. package/dist/presentation/index.mjs +5 -0
  144. package/dist/supervisor/Release.d.mts +2 -0
  145. package/dist/supervisor/Release.mjs +40 -0
  146. package/dist/supervisor/Release.mjs.map +1 -0
  147. package/dist/supervisor/Supervisor.d.mts +2 -104
  148. package/dist/supervisor/Supervisor.mjs +2 -515
  149. package/dist/supervisor/index.d.mts +3 -0
  150. package/dist/supervisor/index.mjs +3 -0
  151. package/dist/testing/HttpCassette.d.mts +98 -0
  152. package/dist/testing/HttpCassette.mjs +146 -0
  153. package/dist/testing/HttpCassette.mjs.map +1 -0
  154. package/dist/testing/Story.d.mts +31 -0
  155. package/dist/testing/Story.mjs +76 -0
  156. package/dist/testing/Story.mjs.map +1 -0
  157. package/dist/testing/TestBrowser.d.mts +191 -0
  158. package/dist/testing/TestBrowser.mjs +105 -0
  159. package/dist/testing/TestBrowser.mjs.map +1 -0
  160. package/dist/testing/TestModel.d.mts +133 -0
  161. package/dist/testing/TestModel.mjs +209 -0
  162. package/dist/testing/TestModel.mjs.map +1 -0
  163. package/dist/testing/TestPage.d.mts +2 -0
  164. package/dist/testing/TestPage.mjs +47 -0
  165. package/dist/testing/TestPage.mjs.map +1 -0
  166. package/dist/testing/index.d.mts +6 -337
  167. package/dist/testing/index.mjs +6 -515
  168. package/dist/timeline/Moment.d.mts +3 -0
  169. package/dist/timeline/Moment.mjs +3 -0
  170. package/dist/timeline/Stillness.d.mts +34 -0
  171. package/dist/timeline/Stillness.mjs +2 -0
  172. package/dist/timeline/index.d.mts +3 -0
  173. package/dist/timeline/index.mjs +3 -0
  174. package/dist/walk/Walk.d.mts +2 -0
  175. package/dist/walk/Walk.mjs +2 -0
  176. package/dist/walk/index.d.mts +2 -0
  177. package/dist/walk/index.mjs +2 -0
  178. package/package.json +54 -133
  179. package/src/Action.ts +73 -8
  180. package/src/Browser.ts +85 -14
  181. package/src/BrowserError.ts +258 -63
  182. package/src/BrowserEvent.ts +264 -48
  183. package/src/Cdp.ts +42 -0
  184. package/src/Change.ts +75 -4
  185. package/src/Frame.ts +247 -14
  186. package/src/{Style.ts → InputStyle.ts} +130 -18
  187. package/src/Layout.ts +187 -0
  188. package/src/Overlay.ts +76 -0
  189. package/src/Page.ts +144 -275
  190. package/src/PageTime.ts +72 -0
  191. package/src/Pose.ts +81 -0
  192. package/src/Site.ts +136 -0
  193. package/src/Snapshot.ts +179 -3
  194. package/src/Text.ts +60 -0
  195. package/src/Window.ts +53 -3
  196. package/src/ai/BrowserTools.ts +778 -0
  197. package/src/ai/PageControl.ts +702 -0
  198. package/src/ai/PromptCache.ts +87 -0
  199. package/src/ai/Tabs.ts +84 -0
  200. package/src/ai/ToolError.ts +50 -0
  201. package/src/ai/index.ts +36 -0
  202. package/src/ai/internal/crops.ts +38 -0
  203. package/src/ai/internal/points.ts +57 -0
  204. package/src/ai/internal/receipts.ts +107 -0
  205. package/src/index.ts +87 -6
  206. package/src/{ActionPort.ts → internal/action-port.ts} +3 -3
  207. package/src/{providers → internal/cdp}/connection.ts +19 -12
  208. package/src/internal/cdp/workerd.ts +36 -0
  209. package/src/{Clock.ts → internal/clock.ts} +20 -0
  210. package/src/internal/input/actions.ts +1 -1
  211. package/src/internal/input/dispatch.ts +2 -2
  212. package/src/internal/input/guard.inpage.ts +1 -1
  213. package/src/internal/input/guard.ts +1 -1
  214. package/src/internal/input/perform.ts +35 -7
  215. package/src/internal/input/pointer.ts +9 -6
  216. package/src/internal/input/targets.inpage.ts +3 -3
  217. package/src/internal/input/targets.ts +1 -1
  218. package/src/{Matching.ts → internal/matching.ts} +28 -19
  219. package/src/internal/page/bridge.ts +67 -35
  220. package/src/internal/page/clock.inpage.ts +306 -0
  221. package/src/internal/page/compose.inpage.ts +101 -0
  222. package/src/internal/page/context.ts +4 -2
  223. package/src/internal/page/functions.ts +84 -0
  224. package/src/internal/page/navigation.ts +1 -1
  225. package/src/internal/page/openings.ts +2 -2
  226. package/src/internal/page/overlay.inpage.ts +96 -0
  227. package/src/internal/page/overlay.ts +89 -0
  228. package/src/internal/page/page.ts +39 -29
  229. package/src/internal/page/port.ts +14 -8
  230. package/src/internal/page/pose.inpage.ts +200 -0
  231. package/src/internal/page/pose.ts +80 -0
  232. package/src/internal/page/replies.ts +1 -1
  233. package/src/internal/page/requests.ts +1 -1
  234. package/src/internal/page/scripts.ts +1 -1
  235. package/src/internal/page/time.inpage.ts +49 -0
  236. package/src/internal/page/time.ts +122 -0
  237. package/src/internal/page/viewport.ts +3 -2
  238. package/src/internal/pictures/capture.ts +1 -4
  239. package/src/internal/pictures/dimensions.ts +1 -1
  240. package/src/internal/pictures/frame.ts +1 -1
  241. package/src/internal/pictures/pictures.ts +144 -91
  242. package/src/internal/reading/context.inpage.ts +2 -2
  243. package/src/internal/reading/expect.inpage.ts +1 -1
  244. package/src/internal/reading/layout.inpage.ts +193 -0
  245. package/src/internal/reading/layout.ts +101 -0
  246. package/src/internal/reading/names.inpage.ts +15 -0
  247. package/src/internal/reading/outline.inpage.ts +5 -21
  248. package/src/internal/reading/reading.ts +33 -21
  249. package/src/internal/reading/ready.inpage.ts +21 -26
  250. package/src/internal/reading/ready.ts +26 -5
  251. package/src/internal/reading/subjects.inpage.ts +3 -3
  252. package/src/internal/reading/text.inpage.ts +3 -16
  253. package/src/internal/reading/walk.inpage.ts +1 -1
  254. package/src/internal/timeline/changes.inpage.ts +7 -15
  255. package/src/internal/timeline/changes.ts +17 -5
  256. package/src/internal/timeline/record.inpage.ts +15 -6
  257. package/src/internal/timeline/sight.inpage.ts +2 -2
  258. package/src/internal/timeline/window.ts +3 -4
  259. package/src/policy/Policy.ts +70 -16
  260. package/src/policy/index.ts +12 -0
  261. package/src/presentation/Film.ts +451 -0
  262. package/src/presentation/Motion.ts +45 -3
  263. package/src/presentation/Presentation.ts +60 -14
  264. package/src/presentation/Stage.ts +73 -35
  265. package/src/presentation/index.ts +30 -0
  266. package/src/presentation/{feed.ts → internal/feed.ts} +1 -1
  267. package/src/supervisor/Release.ts +45 -0
  268. package/src/supervisor/Supervisor.ts +80 -5
  269. package/src/supervisor/index.ts +18 -0
  270. package/src/supervisor/{contract.ts → internal/contract.ts} +14 -10
  271. package/src/supervisor/{lifecycle.ts → internal/lifecycle.ts} +7 -7
  272. package/src/supervisor/{runtime.ts → internal/runtime.ts} +7 -7
  273. package/src/testing/HttpCassette.ts +260 -0
  274. package/src/testing/Story.ts +103 -0
  275. package/src/testing/TestBrowser.ts +14 -4
  276. package/src/testing/TestModel.ts +297 -0
  277. package/src/testing/TestPage.ts +92 -4
  278. package/src/testing/index.ts +35 -1
  279. package/src/testing/{evidence.ts → internal/evidence.ts} +19 -11
  280. package/src/testing/{model.ts → internal/model.ts} +14 -8
  281. package/src/testing/{page.ts → internal/page.ts} +55 -51
  282. package/src/{moment → timeline}/Moment.ts +79 -29
  283. package/src/{stillness → timeline}/Stillness.ts +89 -46
  284. package/src/timeline/index.ts +18 -0
  285. package/src/{stillness/Pixels.ts → timeline/internal/pixels.ts} +27 -1
  286. package/src/{moment → timeline/internal}/words.ts +2 -2
  287. package/src/walk/Walk.ts +165 -0
  288. package/src/walk/index.ts +12 -0
  289. package/src/{plan → walk/internal}/choose.ts +23 -14
  290. package/src/{plan → walk/internal}/data.ts +37 -14
  291. package/src/{plan → walk/internal}/execute.ts +79 -36
  292. package/src/{plan → walk/internal}/record.ts +6 -6
  293. package/src/{plan → walk/internal}/targets.ts +35 -25
  294. package/dist/ActionPort.d.mts +0 -15
  295. package/dist/ActionPort.mjs.map +0 -1
  296. package/dist/Browser-BKPAbyys.mjs.map +0 -1
  297. package/dist/Change-Ba7INmay.d.mts +0 -69
  298. package/dist/Clock.d.mts +0 -57
  299. package/dist/Clock.mjs.map +0 -1
  300. package/dist/Frame-UEH2hO5T.d.mts +0 -124
  301. package/dist/Geometry.d.mts +0 -2
  302. package/dist/Geometry.mjs.map +0 -1
  303. package/dist/Matching.d.mts +0 -37
  304. package/dist/Matching.mjs.map +0 -1
  305. package/dist/Page-BF5izr8R.mjs.map +0 -1
  306. package/dist/Page-CvsOEorc.d.mts +0 -566
  307. package/dist/Released-tURbFmal.d.mts +0 -15
  308. package/dist/Snapshot-CtBVOtuu.d.mts +0 -73
  309. package/dist/Stillness-CNlvayIo.mjs +0 -136
  310. package/dist/Stillness-CNlvayIo.mjs.map +0 -1
  311. package/dist/Style-AO4V7Czt.mjs.map +0 -1
  312. package/dist/Style.d.mts +0 -72
  313. package/dist/Style.mjs +0 -2
  314. package/dist/Url.d.mts +0 -26
  315. package/dist/Url.mjs.map +0 -1
  316. package/dist/Window-CMddGMt1.d.mts +0 -34
  317. package/dist/connection-CK83pvqP.mjs.map +0 -1
  318. package/dist/moment/Moment.mjs.map +0 -1
  319. package/dist/plan/index.mjs.map +0 -1
  320. package/dist/presentation/Stage.mjs.map +0 -1
  321. package/dist/presentation/feed.d.mts +0 -20
  322. package/dist/presentation/feed.mjs +0 -18
  323. package/dist/presentation/feed.mjs.map +0 -1
  324. package/dist/providers/Cdp.d.mts +0 -9
  325. package/dist/providers/Cdp.mjs +0 -15
  326. package/dist/providers/Cdp.mjs.map +0 -1
  327. package/dist/providers/Chromium.d.mts +0 -32
  328. package/dist/providers/Chromium.mjs +0 -55
  329. package/dist/providers/Chromium.mjs.map +0 -1
  330. package/dist/providers/Released.d.mts +0 -2
  331. package/dist/providers/Released.mjs +0 -12
  332. package/dist/providers/Released.mjs.map +0 -1
  333. package/dist/stillness/Stillness.d.mts +0 -12
  334. package/dist/stillness/Stillness.mjs +0 -2
  335. package/dist/supervisor/Supervisor.mjs.map +0 -1
  336. package/dist/testing/index.mjs.map +0 -1
  337. package/dist/workerd/Cdp.d.mts +0 -8
  338. package/dist/workerd/Cdp.mjs +0 -13
  339. package/dist/workerd/Cdp.mjs.map +0 -1
  340. package/src/plan/index.ts +0 -36
  341. package/src/providers/Cdp.ts +0 -16
  342. package/src/providers/Chromium.ts +0 -99
  343. package/src/providers/Released.ts +0 -13
  344. package/src/workerd/Cdp.ts +0 -11
  345. /package/dist/{rolldown-runtime-D7D4PA-g.mjs → internal/rolldown-runtime-D7D4PA-g.mjs} +0 -0
  346. /package/src/{Geometry.ts → internal/geometry.ts} +0 -0
  347. /package/src/{Url.ts → internal/url.ts} +0 -0
  348. /package/src/{stillness → timeline/internal}/utilsBundle.d.ts +0 -0
@@ -1,136 +0,0 @@
1
- import { Failed, Timeout, refuse, undispatched } from "./BrowserError.mjs";
2
- import { monotonicMillis } from "./Clock.mjs";
3
- import { Clock, Duration, Effect, Option, Schedule, Stream } from "effect";
4
- import { jpegjs } from "playwright-core/lib/utilsBundle";
5
- //#region src/stillness/Pixels.ts
6
- /**
7
- * Where a page's screen moves, from its screencast frames: each frame decoded and cut into
8
- * 16-pixel blocks, a block moving where a few of its pixels, sampled every other one, changed by
9
- * more than JPEG's noise in any color channel.
10
- * What moved among the frames before an input is the page's background, such as an idle
11
- * animation; foreground stillness ignores it.
12
- *
13
- * Frames use Playwright's bundled JPEG decoder. The package build ships that exact decoder
14
- * alone, keeping its Node utility bundle out of Workers. Source runs use its native export,
15
- * whose untyped entry point is declared by `utilsBundle.d.ts`.
16
- */
17
- const picture = (frame) => jpegjs.decode(frame.data, { useTArray: true });
18
- /** A sample changed where any color channel moved more than this, beyond JPEG's noise. */
19
- const noise = 32;
20
- /** The blocks where two pictures differ, by `row * columns + column`; -1 for different sizes. */
21
- const moved = (from, to) => {
22
- if (from.width !== to.width || from.height !== to.height) return [-1];
23
- const columns = Math.ceil(from.width / 16);
24
- const counts = /* @__PURE__ */ new Map();
25
- const differs = (at) => Math.abs((from.data[at] ?? 0) - (to.data[at] ?? 0)) > noise;
26
- for (let y = 0; y < from.height; y += 2) for (let x = 0; x < from.width; x += 2) {
27
- const at = (y * from.width + x) * 4;
28
- const block = Math.floor(y / 16) * columns + Math.floor(x / 16);
29
- if (differs(at) || differs(at + 1) || differs(at + 2)) counts.set(block, (counts.get(block) ?? 0) + 1);
30
- }
31
- return [...counts].flatMap(([block, count]) => count >= 3 ? [block] : []);
32
- };
33
- /** The blocks that moved from one picture to the next and their neighbours; none past a resize. */
34
- const background = (pictures) => {
35
- const columns = Math.ceil((pictures[0]?.width ?? 0) / 16);
36
- const around = (block) => [
37
- -1,
38
- 0,
39
- 1
40
- ].flatMap((row) => [
41
- -1,
42
- 0,
43
- 1
44
- ].filter((step) => block >= 0 && block % columns + step >= 0).filter((step) => block % columns + step < columns).map((step) => block + row * columns + step));
45
- return new Set(pictures.flatMap((to, index) => moved(pictures[index - 1] ?? to, to).flatMap(around)));
46
- };
47
- /** Whether anything moved from one picture to another outside the background. */
48
- const stirs = (from, to, mask) => moved(from, to).some((block) => !mask.has(block));
49
- //#endregion
50
- //#region src/stillness/Stillness.ts
51
- /** Screen and foreground stillness over the public page capture and owning clock. */
52
- const observe = (page, options, timeout) => Effect.gen(function* () {
53
- const now = () => monotonicMillis(page.clock);
54
- const deadline = now() + Duration.toMillis(timeout);
55
- const settled = () => page.ready({
56
- quietMillis: options.quietMillis,
57
- timeout: Duration.millis(Math.max(0, deadline - now()))
58
- });
59
- const quiet = (millis) => Effect.gen(function* () {
60
- const capture = yield* page.capture();
61
- const foreground = options.still === "foreground";
62
- let counts = yield* capture.stats();
63
- let stirred = now();
64
- let reference;
65
- const decoded = (frame) => Effect.try({
66
- try: () => picture(frame),
67
- catch: (error) => undispatched("ready", new Failed({ detail: `no picture: ${String(error)}` }))
68
- });
69
- const inputAt = (yield* page.recentEvents).findLast((event) => event._tag === "Action")?.startedAt ?? Number.NEGATIVE_INFINITY;
70
- const document = (yield* page.state).document;
71
- const before = (foreground ? yield* page.recentFrames : []).filter((frame) => frame.hostTime < inputAt && frame.hostTime >= inputAt - 1500 && frame.document === document);
72
- const sampled = before.filter((_, index) => index % Math.ceil(before.length / 8) === 0);
73
- const mask = background(yield* Effect.forEach(sampled, decoded));
74
- const look = Effect.gen(function* () {
75
- const stats = yield* capture.stats();
76
- const latest = (yield* page.state).frame;
77
- const arrived = stats.received !== counts.received;
78
- const unseen = stats.accepted - counts.accepted;
79
- counts = stats;
80
- if (latest === void 0 || !capture.isCurrent(latest)) stirred = now();
81
- else if (!foreground ? arrived || stats.ackBacklog > 0 : !arrived && stats.ackBacklog > 0) stirred = now();
82
- else if (foreground && (unseen > 0 || reference === void 0)) {
83
- const frames = (yield* page.recentFrames).slice(-Math.max(1, Math.min(8, unseen)));
84
- if (unseen > frames.length) stirred = now();
85
- for (const frame of frames) {
86
- const seen = yield* decoded(frame);
87
- if (reference === void 0 || stirs(reference, seen, mask)) {
88
- reference = seen;
89
- stirred = now();
90
- }
91
- }
92
- }
93
- return now() - stirred;
94
- });
95
- const spell = Effect.repeat(look, {
96
- schedule: Schedule.fixed(Duration.millis(foreground ? 100 : 25)),
97
- until: (still) => still >= millis
98
- });
99
- const still = Effect.gen(function* () {
100
- for (;;) {
101
- yield* spell;
102
- const before = counts.received;
103
- yield* Effect.all([settled(), capture.sync], {
104
- concurrency: 2,
105
- discard: true
106
- });
107
- if ((yield* look) >= millis && (foreground || counts.received === before)) return;
108
- }
109
- });
110
- return yield* Effect.raceFirst(capture.stream.pipe(Stream.runDrain, Effect.andThen(Effect.never)), still);
111
- });
112
- yield* page.afterInput(Effect.void);
113
- if (options.still === "content") {
114
- yield* page.changes();
115
- yield* Effect.sleep(Duration.millis(options.quietMillis));
116
- return yield* settled();
117
- }
118
- yield* settled();
119
- yield* quiet(options.quietMillis);
120
- });
121
- const wait = (page, options) => Effect.gen(function* () {
122
- if (!Number.isFinite(options.quietMillis) || options.quietMillis < 0) return yield* refuse("stillness", "quietMillis must be finite and nonnegative");
123
- const input = options.timeout ?? Duration.seconds(15);
124
- const components = typeof input === "number" ? [input] : typeof input === "object" && !Duration.isDuration(input) ? Object.values(input) : [];
125
- const timeout = Duration.fromInput(input);
126
- if (components.some((value) => typeof value === "number" && !Number.isFinite(value)) || Option.isNone(timeout) || !Duration.isFinite(timeout.value) || Duration.isNegative(timeout.value)) return yield* refuse("stillness", "timeout must be a finite nonnegative duration");
127
- const duration = timeout.value;
128
- return yield* observe(page, options, duration).pipe(Effect.timeoutOrElse({
129
- duration,
130
- orElse: () => Effect.fail(undispatched("stillness", new Timeout({ millis: Duration.toMillis(duration) })))
131
- }));
132
- }).pipe(Effect.scoped, Effect.provideService(Clock.Clock, page.clock), Effect.withSpan("Stillness.wait"));
133
- //#endregion
134
- export { wait as t };
135
-
136
- //# sourceMappingURL=Stillness-CNlvayIo.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"Stillness-CNlvayIo.mjs","names":["Motion.picture","Motion.background","Motion.stirs"],"sources":["../src/stillness/Pixels.ts","../src/stillness/Stillness.ts"],"sourcesContent":["/**\n * Where a page's screen moves, from its screencast frames: each frame decoded and cut into\n * 16-pixel blocks, a block moving where a few of its pixels, sampled every other one, changed by\n * more than JPEG's noise in any color channel.\n * What moved among the frames before an input is the page's background, such as an idle\n * animation; foreground stillness ignores it.\n *\n * Frames use Playwright's bundled JPEG decoder. The package build ships that exact decoder\n * alone, keeping its Node utility bundle out of Workers. Source runs use its native export,\n * whose untyped entry point is declared by `utilsBundle.d.ts`.\n */\n// oxlint-disable-next-line typescript/triple-slash-reference -- a declaration of an untyped module cannot be imported, and every program that compiles this source needs it\n/// <reference path=\"./utilsBundle.d.ts\" />\nimport { jpegjs } from \"playwright-core/lib/utilsBundle\";\n\nimport type { Frame } from \"../Frame.ts\";\n\n/** A decoded frame: RGBA, `width` pixels a row. */\nexport type Picture = ReturnType<typeof jpegjs.decode>;\n\nexport const picture = (frame: Frame): Picture => jpegjs.decode(frame.data, { useTArray: true });\n\n/** A sample changed where any color channel moved more than this, beyond JPEG's noise. */\nconst noise = 32;\n\n/** The blocks where two pictures differ, by `row * columns + column`; -1 for different sizes. */\nconst moved = (from: Picture, to: Picture): ReadonlyArray<number> => {\n if (from.width !== to.width || from.height !== to.height) return [-1];\n const columns = Math.ceil(from.width / 16);\n const counts = new Map<number, number>();\n const differs = (at: number) => Math.abs((from.data[at] ?? 0) - (to.data[at] ?? 0)) > noise;\n\n for (let y = 0; y < from.height; y += 2)\n for (let x = 0; x < from.width; x += 2) {\n const at = (y * from.width + x) * 4;\n const block = Math.floor(y / 16) * columns + Math.floor(x / 16);\n\n if (differs(at) || differs(at + 1) || differs(at + 2))\n counts.set(block, (counts.get(block) ?? 0) + 1);\n }\n\n // At least three changed samples, so a stray one is no motion.\n return [...counts].flatMap(([block, count]) => (count >= 3 ? [block] : []));\n};\n\n/** The blocks that moved from one picture to the next and their neighbours; none past a resize. */\nexport const background = (pictures: ReadonlyArray<Picture>): ReadonlySet<number> => {\n const columns = Math.ceil((pictures[0]?.width ?? 0) / 16);\n\n const around = (block: number) =>\n [-1, 0, 1].flatMap((row) =>\n [-1, 0, 1]\n .filter((step) => block >= 0 && (block % columns) + step >= 0)\n .filter((step) => (block % columns) + step < columns)\n .map((step) => block + row * columns + step),\n );\n\n return new Set(\n pictures.flatMap((to, index) => moved(pictures[index - 1] ?? to, to).flatMap(around)),\n );\n};\n\n/** Whether anything moved from one picture to another outside the background. */\nexport const stirs = (from: Picture, to: Picture, mask: ReadonlySet<number>) =>\n moved(from, to).some((block) => !mask.has(block));\n","/** Screen and foreground stillness over the public page capture and owning clock. */\nimport { Clock, Duration, Effect, Option, Schedule, Stream } from \"effect\";\n\nimport { Failed, refuse, Timeout, undispatched } from \"../BrowserError.ts\";\nimport { monotonicMillis } from \"../Clock.ts\";\nimport type { Frame } from \"../Frame.ts\";\nimport type { Page } from \"../Page.ts\";\nimport * as Motion from \"./Pixels.ts\";\n\nexport interface Options {\n readonly still?: \"screen\" | \"content\" | \"foreground\" | undefined;\n readonly quietMillis: number;\n readonly timeout?: Duration.Input | undefined;\n}\n\nconst observe = (page: Page, options: Options, timeout: Duration.Duration) =>\n Effect.gen(function* () {\n const now = () => monotonicMillis(page.clock);\n const deadline = now() + Duration.toMillis(timeout);\n\n const settled = () =>\n page.ready({\n quietMillis: options.quietMillis,\n timeout: Duration.millis(Math.max(0, deadline - now())),\n });\n\n // A capture the wait starts sends its first frame late, over half a second from a hosted\n // browser, so the spell counts from that frame (#202); Chrome sends one as a capture starts,\n // even of a still page.\n const quiet = (millis: number) =>\n Effect.gen(function* () {\n const capture = yield* page.capture();\n\n const foreground = options.still === \"foreground\";\n let counts = yield* capture.stats();\n let stirred = now();\n let reference: Motion.Picture | undefined;\n\n const decoded = (frame: Frame) =>\n Effect.try({\n try: () => Motion.picture(frame),\n catch: (error) =>\n undispatched(\"ready\", new Failed({ detail: `no picture: ${String(error)}` })),\n });\n\n // The background: what moved in up to eight frames of the document's 1.5 s before its\n // latest input, as far back as the capture keeps them.\n const inputAt =\n (yield* page.recentEvents).findLast((event) => event._tag === \"Action\")?.startedAt ??\n Number.NEGATIVE_INFINITY;\n\n const document = (yield* page.state).document;\n\n const before = (foreground ? yield* page.recentFrames : []).filter(\n (frame) =>\n frame.hostTime < inputAt &&\n frame.hostTime >= inputAt - 1500 &&\n frame.document === document,\n );\n\n const sampled = before.filter((_, index) => index % Math.ceil(before.length / 8) === 0);\n const mask = Motion.background(yield* Effect.forEach(sampled, decoded));\n\n // How long the screen has been still: since a frame, or an unanswered acknowledgement. In\n // the foreground, since a frame moved outside the background, or acknowledgements went\n // unanswered with no frame coming.\n const look = Effect.gen(function* () {\n const stats = yield* capture.stats();\n const latest = (yield* page.state).frame;\n const arrived = stats.received !== counts.received;\n const unseen = stats.accepted - counts.accepted;\n\n counts = stats;\n if (latest === undefined || !capture.isCurrent(latest)) stirred = now();\n else if (!foreground ? arrived || stats.ackBacklog > 0 : !arrived && stats.ackBacklog > 0)\n stirred = now();\n else if (foreground && (unseen > 0 || reference === undefined)) {\n // A move and its return between looks both count. Bound decoding; any frames lost\n // from history, or beyond this batch, deny a quiet spell rather than hiding motion.\n const frames = (yield* page.recentFrames).slice(-Math.max(1, Math.min(8, unseen)));\n\n if (unseen > frames.length) stirred = now();\n for (const frame of frames) {\n const seen = yield* decoded(frame);\n\n if (reference === undefined || Motion.stirs(reference, seen, mask)) {\n reference = seen;\n stirred = now();\n }\n }\n }\n\n return now() - stirred;\n });\n\n // Decode at a fixed cadence: adding a delay after a full batch lets its backlog grow.\n const spell = Effect.repeat(look, {\n schedule: Schedule.fixed(Duration.millis(foreground ? 100 : 25)),\n until: (still) => still >= millis,\n });\n\n const still = Effect.gen(function* () {\n for (;;) {\n yield* spell;\n const before = counts.received;\n\n yield* Effect.all([settled(), capture.sync], { concurrency: 2, discard: true });\n if ((yield* look) >= millis && (foreground || counts.received === before)) return;\n }\n });\n\n return yield* Effect.raceFirst(\n capture.stream.pipe(Stream.runDrain, Effect.andThen(Effect.never)),\n still,\n );\n });\n\n yield* page.afterInput(Effect.void);\n if (options.still === \"content\") {\n yield* page.changes();\n yield* Effect.sleep(Duration.millis(options.quietMillis));\n\n return yield* settled();\n }\n yield* settled();\n yield* quiet(options.quietMillis);\n });\n\nexport const wait = (page: Page, options: Options) =>\n Effect.gen(function* () {\n if (!Number.isFinite(options.quietMillis) || options.quietMillis < 0)\n return yield* refuse(\"stillness\", \"quietMillis must be finite and nonnegative\");\n const input = options.timeout ?? Duration.seconds(15);\n\n const components =\n typeof input === \"number\"\n ? [input]\n : typeof input === \"object\" && !Duration.isDuration(input)\n ? Object.values(input)\n : [];\n\n const timeout = Duration.fromInput(input);\n\n if (\n components.some((value) => typeof value === \"number\" && !Number.isFinite(value)) ||\n Option.isNone(timeout) ||\n !Duration.isFinite(timeout.value) ||\n Duration.isNegative(timeout.value)\n )\n return yield* refuse(\"stillness\", \"timeout must be a finite nonnegative duration\");\n const duration = timeout.value;\n\n return yield* observe(page, options, duration).pipe(\n Effect.timeoutOrElse({\n duration,\n orElse: () =>\n Effect.fail(\n undispatched(\"stillness\", new Timeout({ millis: Duration.toMillis(duration) })),\n ),\n }),\n );\n }).pipe(\n Effect.scoped,\n Effect.provideService(Clock.Clock, page.clock),\n Effect.withSpan(\"Stillness.wait\"),\n );\n"],"mappings":";;;;;;;;;;;;;;;;AAoBA,MAAa,WAAW,UAA0B,OAAO,OAAO,MAAM,MAAM,EAAE,WAAW,KAAK,CAAC;;AAG/F,MAAM,QAAQ;;AAGd,MAAM,SAAS,MAAe,OAAuC;CACnE,IAAI,KAAK,UAAU,GAAG,SAAS,KAAK,WAAW,GAAG,QAAQ,OAAO,CAAC,EAAE;CACpE,MAAM,UAAU,KAAK,KAAK,KAAK,QAAQ,EAAE;CACzC,MAAM,yBAAS,IAAI,IAAoB;CACvC,MAAM,WAAW,OAAe,KAAK,KAAK,KAAK,KAAK,OAAO,MAAM,GAAG,KAAK,OAAO,EAAE,IAAI;CAEtF,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK,GACpC,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,OAAO,KAAK,GAAG;EACtC,MAAM,MAAM,IAAI,KAAK,QAAQ,KAAK;EAClC,MAAM,QAAQ,KAAK,MAAM,IAAI,EAAE,IAAI,UAAU,KAAK,MAAM,IAAI,EAAE;EAE9D,IAAI,QAAQ,EAAE,KAAK,QAAQ,KAAK,CAAC,KAAK,QAAQ,KAAK,CAAC,GAClD,OAAO,IAAI,QAAQ,OAAO,IAAI,KAAK,KAAK,KAAK,CAAC;CAClD;CAGF,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC,SAAS,CAAC,OAAO,WAAY,SAAS,IAAI,CAAC,KAAK,IAAI,CAAC,CAAE;AAC5E;;AAGA,MAAa,cAAc,aAA0D;CACnF,MAAM,UAAU,KAAK,MAAM,SAAS,EAAE,EAAE,SAAS,KAAK,EAAE;CAExD,MAAM,UAAU,UACd;EAAC;EAAI;EAAG;CAAC,CAAC,CAAC,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AAO,cAAc;EACnB;EACA,cACE,OAAO,KACL,aAAa,aAAa,IAAI,QAAQ,EAAE,QAAQ,SAAS,SAAS,QAAQ,EAAE,CAAC,CAAC,CAChF;CACJ,CAAC,CACH;AACF,CAAC,CAAC,CAAC,KACD,OAAO,QACP,OAAO,eAAe,MAAM,OAAO,KAAK,KAAK,GAC7C,OAAO,SAAS,gBAAgB,CAClC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"Style-AO4V7Czt.mjs","names":["Keys.description","description"],"sources":["../src/internal/input/keys.ts","../src/Style.ts"],"sourcesContent":["/**\n * Key aliases for Playwright and printable US key descriptions for pipelined Chromium typing.\n */\n\nconst aliases: Record<string, string> = {\n ctrl: \"Control\",\n control: \"Control\",\n cmd: \"Meta\",\n command: \"Meta\",\n meta: \"Meta\",\n win: \"Meta\",\n super: \"Meta\",\n mod: \"ControlOrMeta\",\n alt: \"Alt\",\n option: \"Alt\",\n shift: \"Shift\",\n enter: \"Enter\",\n return: \"Enter\",\n esc: \"Escape\",\n escape: \"Escape\",\n tab: \"Tab\",\n space: \"Space\",\n spacebar: \"Space\",\n \" \": \"Space\",\n backspace: \"Backspace\",\n delete: \"Delete\",\n del: \"Delete\",\n insert: \"Insert\",\n home: \"Home\",\n end: \"End\",\n pageup: \"PageUp\",\n pagedown: \"PageDown\",\n up: \"ArrowUp\",\n down: \"ArrowDown\",\n left: \"ArrowLeft\",\n right: \"ArrowRight\",\n arrowup: \"ArrowUp\",\n arrowdown: \"ArrowDown\",\n arrowleft: \"ArrowLeft\",\n arrowright: \"ArrowRight\",\n};\n\nconst named = new Set(Object.values(aliases));\n\n/** Parse and validate the whole chord before sending any down events. */\nexport const parts = (keys: string): ReadonlyArray<string> | undefined => {\n const tokens: Array<string> = [];\n let building = \"\";\n\n // Like Playwright, a plus without a preceding token is the literal plus key: Control++.\n for (const character of keys) {\n if (character === \"+\" && building.trim() !== \"\") {\n tokens.push(building);\n building = \"\";\n } else building += character;\n }\n tokens.push(building);\n if (tokens.length > 4) return undefined;\n const out: Array<string> = [];\n\n for (const token of tokens) {\n const part = token === \" \" ? \"Space\" : token.trim();\n const lower = part.toLowerCase();\n const alias = Object.hasOwn(aliases, lower) ? aliases[lower] : undefined;\n\n if (alias !== undefined) out.push(alias);\n else if (\n named.has(part) ||\n /^F([1-9]|1[0-2])$/.test(part) ||\n /^(Key[A-Z]|Digit[0-9]|Numpad[0-9])$/.test(part) ||\n description(part) !== undefined\n )\n out.push(part);\n else return undefined;\n }\n\n return out;\n};\n\ninterface Description {\n readonly code: string;\n readonly keyCode: number;\n readonly key: string;\n readonly text: string;\n}\n\nconst punctuation: ReadonlyArray<readonly [string, string, number]> = [\n [\"`~\", \"Backquote\", 192],\n [\"-_\", \"Minus\", 189],\n [\"=+\", \"Equal\", 187],\n [\"\\\\|\", \"Backslash\", 220],\n [\"[{\", \"BracketLeft\", 219],\n [\"]}\", \"BracketRight\", 221],\n [\";:\", \"Semicolon\", 186],\n [\"'\\\"\", \"Quote\", 222],\n [\",<\", \"Comma\", 188],\n [\".>\", \"Period\", 190],\n [\"/?\", \"Slash\", 191],\n [\" \", \"Space\", 32],\n];\n\n/**\n * Match Playwright's pinned US layout for literal typing. Uppercase and shifted punctuation\n * carry their literal text without synthesizing Shift. Newlines also use insertText so a text\n * payload cannot submit a form; only an explicit Enter or submit option may do that.\n */\nexport const description = (character: string): Description | undefined => {\n // Prose correction uses the same raw key path so its deletion has a matched release.\n if (character === \"Backspace\")\n return { code: \"Backspace\", keyCode: 8, key: \"Backspace\", text: \"\" };\n if (character.length !== 1) return undefined;\n if (/^[A-Za-z]$/.test(character)) {\n const upper = character.toUpperCase();\n\n return { code: `Key${upper}`, keyCode: upper.charCodeAt(0), key: character, text: character };\n }\n const digit = \"0123456789\".indexOf(character);\n const number = digit === -1 ? \")!@#$%^&*(\".indexOf(character) : digit;\n\n if (number !== -1)\n return { code: `Digit${number}`, keyCode: 48 + number, key: character, text: character };\n const symbol = punctuation.find(([characters]) => characters.includes(character));\n\n return symbol === undefined\n ? undefined\n : { code: symbol[1], keyCode: symbol[2], key: character, text: character };\n};\n","/**\n * How input is sent: plainly, as fast as the page takes it, or performed for viewers, with a\n * pointer that glides, keys typed at a person's pace, held buttons and wheels in bursts. A page's\n * actions take one, and the input reaches the same controls either way; only its timing, and\n * what viewers see of it, differ. A presenter builds the performed one.\n */\nimport {\n Context,\n type Duration,\n Effect,\n type MutableRef,\n type Option,\n Random,\n Schema,\n} from \"effect\";\n\nimport { undispatched, type BrowserError, InvalidRequest, refuse } from \"./BrowserError.ts\";\nimport type * as Motion from \"./Geometry.ts\";\nimport { normal } from \"./Geometry.ts\";\nimport * as Keys from \"./internal/input/keys.ts\";\nimport type { Point } from \"./Page.ts\";\n\nexport interface TypingEvent {\n /** From the start of the typing. */\n readonly afterMillis: number;\n readonly phase: \"down\" | \"up\" | \"insert\";\n readonly key: string;\n}\n\nexport interface WheelStep {\n readonly dx: number;\n readonly dy: number;\n /** From the first step. */\n readonly afterMillis: number;\n}\n\nexport interface Style {\n /** Own presentation only after policy allows input; wait options belong to the page. */\n readonly withInput?:\n | ((options: {\n readonly operation: string;\n readonly wait: Duration.Duration;\n readonly failFast: boolean;\n }) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E | BrowserError, R>)\n | undefined;\n /**\n * Whether viewers watch the input: then the pointer clicks into a field before typing, finds\n * what lies under it as it scrolls, and scrolls to a target out of view with the wheel.\n */\n readonly shown: boolean;\n /** Where viewers last saw the pointer, which the next glide starts from; else the page's own. */\n readonly pointer: MutableRef.MutableRef<Option.Option<Point>> | undefined;\n /** The pointer's path to `to`, ending exactly there. */\n readonly glide: (\n from: Point,\n to: Point,\n dragging: boolean,\n ) => Effect.Effect<ReadonlyArray<Motion.Sample>>;\n /** How long a button stays down when a click does not say. */\n readonly hold: Effect.Effect<number, BrowserError>;\n /** The key events that type `text`, or one insertion of it under a guard, timed from the start. */\n readonly typing: (\n text: string,\n guarded: boolean,\n ) => Effect.Effect<ReadonlyArray<TypingEvent>, BrowserError>;\n /** The pause between repeated presses of the same keys. */\n readonly keyGap: Effect.Effect<number, BrowserError>;\n /** A wheel scroll as the wheel turns: in one step, or in notches and bursts. */\n readonly wheel: (dx: number, dy: number) => Effect.Effect<ReadonlyArray<WheelStep>, BrowserError>;\n}\n\n/** Each key as it comes, with no pause; a drag moves in eight short steps so its target sees it. */\nexport const plain: Style = {\n shown: false,\n pointer: undefined,\n glide: (from, to, dragging) =>\n Effect.succeed(\n dragging\n ? Array.from({ length: 8 }, (_, index) => ({\n x: index === 7 ? to.x : from.x + ((to.x - from.x) * (index + 1)) / 8,\n y: index === 7 ? to.y : from.y + ((to.y - from.y) * (index + 1)) / 8,\n afterMillis: (index + 1) * 8,\n }))\n : [{ ...to, afterMillis: 0 }],\n ),\n hold: Effect.succeed(0),\n typing: (text, guarded) =>\n Effect.succeed(\n guarded && text !== \"\"\n ? [{ afterMillis: 0, phase: \"insert\", key: text }]\n : [...text].flatMap((key): ReadonlyArray<TypingEvent> =>\n Keys.description(key) === undefined\n ? [{ afterMillis: 0, phase: \"insert\", key }]\n : [\n { afterMillis: 0, phase: \"down\", key },\n { afterMillis: 0, phase: \"up\", key },\n ],\n ),\n ),\n keyGap: Effect.succeed(0),\n wheel: (dx, dy) => Effect.succeed([{ dx, dy, afterMillis: 0 }]),\n};\n\n// A right-skewed draw, clamped so that cleanup and deadlines stay predictable; 1 - U keeps the\n// logarithm defined when Random returns zero.\nconst lognormal = Effect.fnUntraced(function* (\n median: number,\n sigma: number,\n minimum: number,\n maximum: number,\n) {\n return Math.max(minimum, Math.min(maximum, median * Math.exp(sigma * (yield* normal))));\n});\n\n/** A pause around `median`, as the research measured reactions: at most four times it. */\nexport const pause = (median: number, sigma: number) =>\n median <= 0 ? Effect.succeed(0) : lognormal(median, sigma, 0, median * 4);\n\n// A mouse press about 80 ms long on average, a key about 110 ms, each now and then longer: their\n// medians are the means times exp(-sigma^2 / 2).\nconst pressHold = lognormal(75.2, 0.35, 35, 200);\nconst keyHold = lognormal(107.8, 0.2, 60, 220);\nconst eventOrder = { up: 0, insert: 1, down: 2 };\n\n/**\n * Plan the whole text before any key goes, so holds overlap without waiting on the network. A\n * physical key is never held twice, as with A and a, or ! and 1. The first key waits for the hand\n * to reach the keys, each later one follows the last by a gap drawn around `gap`, and a word's\n * first key comes 60 ms later.\n */\nexport const maximumDurationMillis = 10_000;\n\nconst Delay = Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: maximumDurationMillis }));\n\nconst ordered = <A extends { readonly afterMillis: number }>(sample: Schema.Codec<A>) =>\n Schema.Array(sample).check(\n Schema.makeFilter(\n (samples) =>\n samples.every(\n (event, index) => event.afterMillis >= (samples[index - 1]?.afterMillis ?? 0),\n ),\n { expected: \"nondecreasing input offsets\" },\n ),\n );\n\nconst Typing = ordered(\n Schema.Struct({\n afterMillis: Delay,\n phase: Schema.Literals([\"down\", \"up\", \"insert\"]),\n key: Schema.String,\n }),\n).check(\n Schema.makeFilter(\n (events) => {\n const held = new Set<string>();\n\n for (const event of events) {\n if (event.phase === \"insert\") continue;\n const code = Keys.description(event.key)?.code;\n\n if (code === undefined || (event.phase === \"down\") === held.has(code)) return false;\n if (event.phase === \"down\") held.add(code);\n else held.delete(code);\n }\n\n return held.size === 0;\n },\n { expected: \"matched key holds\" },\n ),\n);\n\nconst Wheel = ordered(Schema.Struct({ afterMillis: Delay, dx: Schema.Finite, dy: Schema.Finite }));\n\nconst decode =\n <A>(schema: Schema.Codec<A>, operation: string) =>\n (value: unknown) =>\n Schema.decodeUnknownEffect(schema)(value).pipe(\n Effect.catch(() =>\n refuse(operation, \"style must provide a finite bounded ordered input schedule\"),\n ),\n );\n\n/** Copy and validate custom schedules before their first input; planning uses the action bound. */\nexport const validated = (style: Style): Style => ({\n ...style,\n hold: style.hold.pipe(Effect.flatMap(decode(Delay, \"click\"))),\n keyGap: style.keyGap.pipe(Effect.flatMap(decode(Delay, \"press\"))),\n typing: (text, guarded) =>\n style.typing(text, guarded).pipe(Effect.flatMap(decode(Typing, \"type\"))),\n wheel: (dx, dy) => style.wheel(dx, dy).pipe(Effect.flatMap(decode(Wheel, \"scroll\"))),\n});\n\nconst overBudget = (operation: string) =>\n undispatched(\n operation,\n new InvalidRequest({\n detail: `presentation must take at most ${maximumDurationMillis} milliseconds`,\n }),\n );\n\nconst typing = Effect.fnUntraced(function* (\n text: string,\n gap: number,\n): Effect.fn.Return<ReadonlyArray<TypingEvent>, BrowserError> {\n const events: Array<TypingEvent> = [];\n const releases = new Map<string, number>();\n let due = text === \"\" ? 0 : yield* Random.nextBetween(150, 400);\n let previous = \"\";\n\n for (const character of text) {\n if (due > maximumDurationMillis) return yield* overBudget(\"type\");\n if (/\\s/u.test(previous) && /[\\p{L}\\p{N}]/u.test(character)) due += 60;\n const description = Keys.description(character);\n\n if (description === undefined)\n events.push({ afterMillis: due, phase: \"insert\", key: character });\n else {\n due = Math.max(due, (releases.get(description.code) ?? -1) + 1);\n const released = due + (yield* keyHold);\n\n events.push(\n { afterMillis: due, phase: \"down\", key: character },\n { afterMillis: released, phase: \"up\", key: character },\n );\n releases.set(description.code, released);\n }\n due += yield* Random.nextBetween(gap / 2, (gap * 3) / 2);\n previous = character;\n }\n\n if (events.some((event) => event.afterMillis > maximumDurationMillis))\n return yield* overBudget(\"type\");\n\n return events.toSorted(\n (left, right) =>\n left.afterMillis - right.afterMillis || eventOrder[left.phase] - eventOrder[right.phase],\n );\n});\n\n/** A word is five characters; the gap leaves room for each word's later start. */\nexport const keyGap = (wordsPerMinute: number) => 12_000 / wordsPerMinute - 10;\n\n/**\n * The wheel in 100 px notches, 30 to 140 ms apart, in bursts of at most nine, with 0.6 to 2.6 s\n * between bursts, as people scroll.\n */\nconst bursts = Effect.fnUntraced(function* (dx: number, dy: number) {\n const notches = Math.max(1, Math.ceil(Math.hypot(dx, dy) / 100));\n\n // Even the shortest possible schedule exceeds the cap; refuse before allocating it.\n if (notches > 1 + maximumDurationMillis / 30) return yield* overBudget(\"scroll\");\n const steps: Array<WheelStep> = [];\n let due = 0;\n\n for (let index = 0; index < notches; index++) {\n if (index > 0)\n due += yield* index % 9 === 0 ? Random.nextBetween(600, 2600) : Random.nextBetween(30, 140);\n if (due > maximumDurationMillis) return yield* overBudget(\"scroll\");\n steps.push({ dx: dx / notches, dy: dy / notches, afterMillis: due });\n }\n\n return steps;\n});\n\n/** Input performed for viewers, with this pointer and pace. */\nexport const performed = (options: {\n readonly pointer: MutableRef.MutableRef<Option.Option<Point>>;\n readonly motion: Motion.Planner;\n readonly wordsPerMinute: number;\n}): Style => {\n const gap = keyGap(options.wordsPerMinute);\n\n return {\n shown: true,\n pointer: options.pointer,\n glide: (from, to) => options.motion.plan(from, to),\n hold: pressHold,\n typing: (text) => typing(text, gap),\n keyGap: Random.nextBetween(gap / 2, (gap * 3) / 2),\n wheel: bursts,\n };\n};\n\n/** Input style in this fiber; plain input is the default. */\nexport const Current = Context.Reference<Style>(\"effect-browser/Style\", {\n defaultValue: () => plain,\n});\n\n/** Apply a style through page input, including pages selected later by a browser adapter. */\nexport const provide =\n (style: Style) =>\n <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n Effect.provideService(effect, Current, style);\n"],"mappings":";;;;;;;;AAIA,MAAM,UAAkC;CACtC,MAAM;CACN,SAAS;CACT,KAAK;CACL,SAAS;CACT,MAAM;CACN,KAAK;CACL,OAAO;CACP,KAAK;CACL,KAAK;CACL,QAAQ;CACR,OAAO;CACP,OAAO;CACP,QAAQ;CACR,KAAK;CACL,QAAQ;CACR,KAAK;CACL,OAAO;CACP,UAAU;CACV,KAAK;CACL,WAAW;CACX,QAAQ;CACR,KAAK;CACL,QAAQ;CACR,MAAM;CACN,KAAK;CACL,QAAQ;CACR,UAAU;CACV,IAAI;CACJ,MAAM;CACN,MAAM;CACN,OAAO;CACP,SAAS;CACT,WAAW;CACX,WAAW;CACX,YAAY;AACd;AAEA,MAAM,QAAQ,IAAI,IAAI,OAAO,OAAO,OAAO,CAAC;;AAG5C,MAAa,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I,IAAI,OAAO,YAAY,IAAI,GAAG;EAC5F,IAAI,MAAA,KAA6B,OAAO,OAAO,WAAW,QAAQ;EAClE,MAAM,KAAK;GAAE,IAAI,KAAK;GAAS,IAAI,KAAK;GAAS,aAAa;EAAI,CAAC;CACrE;CAEA,OAAO;AACT,CAAC;;AAGD,MAAa,aAAa,YAIb;CACX,MAAM,MAAM,OAAO,QAAQ,cAAc;CAEzC,OAAO;EACL,OAAO;EACP,SAAS,QAAQ;EACjB,QAAQ,MAAM,OAAO,QAAQ,OAAO,KAAK,MAAM,EAAE;EACjD,MAAM;EACN,SAAS,SAAS,OAAO,MAAM,GAAG;EAClC,QAAQ,OAAO,YAAY,MAAM,GAAI,MAAM,IAAK,CAAC;EACjD,OAAO;CACT;AACF;;AAGA,MAAa,UAAU,QAAQ,UAAiB,wBAAwB,EACtE,oBAAoB,MACtB,CAAC;;AAGD,MAAa,WACV,WACS,WACR,OAAO,eAAe,QAAQ,SAAS,KAAK"}
package/dist/Style.d.mts DELETED
@@ -1,72 +0,0 @@
1
- import { t as BrowserError } from "./BrowserError-BlcmLVzn.mjs";
2
- import { a as Sample, r as Planner, t as Geometry_d_exports } from "./Geometry-DJx9qrYy.mjs";
3
- import { m as Point } from "./Page-CvsOEorc.mjs";
4
- import { Context, Duration, Effect, MutableRef, Option } from "effect";
5
- declare namespace Style_d_exports {
6
- export { Current, Style, TypingEvent, WheelStep, keyGap, maximumDurationMillis, pause, performed, plain, provide, validated };
7
- }
8
- export interface TypingEvent {
9
- /** From the start of the typing. */
10
- readonly afterMillis: number;
11
- readonly phase: "down" | "up" | "insert";
12
- readonly key: string;
13
- }
14
- export interface WheelStep {
15
- readonly dx: number;
16
- readonly dy: number;
17
- /** From the first step. */
18
- readonly afterMillis: number;
19
- }
20
- export interface Style {
21
- /** Own presentation only after policy allows input; wait options belong to the page. */
22
- readonly withInput?: ((options: {
23
- readonly operation: string;
24
- readonly wait: Duration.Duration;
25
- readonly failFast: boolean;
26
- }) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E | BrowserError, R>) | undefined;
27
- /**
28
- * Whether viewers watch the input: then the pointer clicks into a field before typing, finds
29
- * what lies under it as it scrolls, and scrolls to a target out of view with the wheel.
30
- */
31
- readonly shown: boolean;
32
- /** Where viewers last saw the pointer, which the next glide starts from; else the page's own. */
33
- readonly pointer: MutableRef.MutableRef<Option.Option<Point>> | undefined;
34
- /** The pointer's path to `to`, ending exactly there. */
35
- readonly glide: (from: Point, to: Point, dragging: boolean) => Effect.Effect<ReadonlyArray<Sample>>;
36
- /** How long a button stays down when a click does not say. */
37
- readonly hold: Effect.Effect<number, BrowserError>;
38
- /** The key events that type `text`, or one insertion of it under a guard, timed from the start. */
39
- readonly typing: (text: string, guarded: boolean) => Effect.Effect<ReadonlyArray<TypingEvent>, BrowserError>;
40
- /** The pause between repeated presses of the same keys. */
41
- readonly keyGap: Effect.Effect<number, BrowserError>;
42
- /** A wheel scroll as the wheel turns: in one step, or in notches and bursts. */
43
- readonly wheel: (dx: number, dy: number) => Effect.Effect<ReadonlyArray<WheelStep>, BrowserError>;
44
- }
45
- /** Each key as it comes, with no pause; a drag moves in eight short steps so its target sees it. */
46
- export declare const plain: Style;
47
- /** A pause around `median`, as the research measured reactions: at most four times it. */
48
- export declare const pause: (median: number, sigma: number) => Effect.Effect<number, never, never>;
49
- /**
50
- * Plan the whole text before any key goes, so holds overlap without waiting on the network. A
51
- * physical key is never held twice, as with A and a, or ! and 1. The first key waits for the hand
52
- * to reach the keys, each later one follows the last by a gap drawn around `gap`, and a word's
53
- * first key comes 60 ms later.
54
- */
55
- export declare const maximumDurationMillis = 10000;
56
- /** Copy and validate custom schedules before their first input; planning uses the action bound. */
57
- export declare const validated: (style: Style) => Style;
58
- /** A word is five characters; the gap leaves room for each word's later start. */
59
- export declare const keyGap: (wordsPerMinute: number) => number;
60
- /** Input performed for viewers, with this pointer and pace. */
61
- export declare const performed: (options: {
62
- readonly pointer: MutableRef.MutableRef<Option.Option<Point>>;
63
- readonly motion: Planner;
64
- readonly wordsPerMinute: number;
65
- }) => Style;
66
- /** Input style in this fiber; plain input is the default. */
67
- export declare const Current: Context.Reference<Style>;
68
- /** Apply a style through page input, including pages selected later by a browser adapter. */
69
- export declare const provide: (style: Style) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, never>>;
70
- //#endregion
71
- export { Style_d_exports as t };
72
- //# sourceMappingURL=Style.d.mts.map
package/dist/Style.mjs DELETED
@@ -1,2 +0,0 @@
1
- import { a as pause, c as provide, i as maximumDurationMillis, l as validated, o as performed, r as keyGap, s as plain, t as Current } from "./Style-AO4V7Czt.mjs";
2
- export { Current, keyGap, maximumDurationMillis, pause, performed, plain, provide, validated };
package/dist/Url.d.mts DELETED
@@ -1,26 +0,0 @@
1
- declare namespace Url_d_exports {
2
- export { addresses, parse, quoted, redact, redactWithin, withheld };
3
- }
4
- /**
5
- * Addresses: reading one the way a person types it, for `Page.goto` and the browser tools alike,
6
- * and reporting one without the values that are credentials, by one rule that the page script runs
7
- * too, for the outline's links.
8
- */
9
- /** The URL `input` names. Without a scheme it is a web address: HTTPS, or HTTP on loopback. */
10
- export declare const parse: (input: string) => URL | null;
11
- /**
12
- * The rule that reports an address without its credentials. The page script runs it too, so it
13
- * stays self-contained, as `names.inpage.ts` says a page-side part must.
14
- */
15
- export declare const addresses: () => {
16
- withheld: "••••••••";
17
- redact: (url: string) => string;
18
- };
19
- export declare const withheld: "••••••••", redact: (url: string) => string;
20
- /** An address inside text, as a failure's message quotes one. */
21
- export declare const quoted: RegExp;
22
- /** `text` with each address in it redacted. */
23
- export declare const redactWithin: (text: string) => string;
24
- //#endregion
25
- export { Url_d_exports as t };
26
- //# sourceMappingURL=Url.d.mts.map
package/dist/Url.mjs.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"Url.mjs","names":[],"sources":["../src/Url.ts"],"sourcesContent":["/**\n * Addresses: reading one the way a person types it, for `Page.goto` and the browser tools alike,\n * and reporting one without the values that are credentials, by one rule that the page script runs\n * too, for the outline's links.\n */\n\nconst scheme = /^[a-z][a-z0-9+.-]*:/i;\n\n// `localhost:3000` and `example.com:8080/a` look like a scheme to the URL parser; a port decides.\nconst hostAndPort = /^[^\\s/?#@:]+:\\d+(?:[/?#]|$)/;\n\nconst loopback = /^(?:localhost|127(?:\\.\\d+){3}|\\[::1\\])(?:[:/?#]|$)/i;\n\n/** The URL `input` names. Without a scheme it is a web address: HTTPS, or HTTP on loopback. */\nexport const parse = (input: string): URL | null => {\n const text = input.trim();\n\n if (scheme.test(text) && !hostAndPort.test(text)) return URL.parse(text);\n\n return URL.parse(`${loopback.test(text) ? \"http\" : \"https\"}://${text}`);\n};\n\n/**\n * The rule that reports an address without its credentials. The page script runs it too, so it\n * stays self-contained, as `names.inpage.ts` says a page-side part must.\n */\nexport const addresses = () => {\n // What a credential's value reads as, as a secret field's text does (`Page.redacted`).\n const withheld = \"••••••••\" as const;\n\n // A parameter's name, compared in lowercase without separators, says it is a credential: a token,\n // secret, password, signature, assertion, session id or one-time code, or a code or key of a kind\n // that signs someone in or signs a request, such as `verification_code` or `api_key`.\n const credential =\n /token|secret|passw|passcode|passphrase|signature|credential|assertion|verifier|bearer|jwt|hmac|apikey|accesskey|privatekey|sess(?:ion)?id|saml(?:response|art)|(?:sig|otp)$|(?:auth|api|access|private|secret|signing|client|encryption|licen[cs]e|session|master|app|device|verification|verify|confirmation|confirm|activation|activate|reset|recovery|login|security|magic|onetime|mfa|2fa|sms|email|otp|oob)(?:code|key)$|^(?:auth|authorization|pwd|pass)$/;\n\n // These names as often say what an address is about, such as a stock code, a support ticket or a\n // conference session. Under them a value is a credential when it looks generated, at least 16\n // characters with letters and digits, as tokens, session ids and authorization codes do.\n const ambiguous = /^(?:code|key|session|sid|ticket)$/;\n\n const secret = (name: string, value: string) => {\n const bare = name.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n\n return (\n value !== \"\" &&\n (credential.test(bare) ||\n (ambiguous.test(bare) && value.length >= 16 && /\\d/.test(value) && /[a-z]/i.test(value)))\n );\n };\n\n // Parameters as written, each credential's value withheld: a query's, a fragment's written as a\n // query, or a path's segments', as a Java session id is.\n const masked = (parameters: string, separator: string) =>\n parameters\n .split(separator)\n .map((parameter) => {\n const [name = \"\", value = \"\"] = [...new URLSearchParams(parameter)][0] ?? [];\n\n return secret(name, value)\n ? `${parameter.slice(0, parameter.indexOf(\"=\") + 1)}${withheld}`\n : parameter;\n })\n .join(separator);\n\n /**\n * `url` as the library reports it: without userinfo, and with each credential's value withheld,\n * so the rest keeps its identity, such as a chart's `?ticker=ETH`. An address without a host,\n * such as `data:` or `about:blank`, is content or a fixed name, and stays as it is.\n */\n const redact = (url: string): string => {\n const parsed = URL.parse(url);\n\n if (parsed === null || parsed.host === \"\") return url;\n parsed.username = \"\";\n parsed.password = \"\";\n parsed.pathname = masked(parsed.pathname, \";\");\n parsed.search = masked(parsed.search.slice(1), \"&\");\n if (parsed.hash.includes(\"=\")) {\n const fragment = parsed.hash.slice(1);\n const question = fragment.indexOf(\"?\");\n // A route before the parameters, as in `#/inbox?token=…`, stays.\n const start = question >= 0 && question < fragment.indexOf(\"=\") ? question + 1 : 0;\n\n parsed.hash = fragment.slice(0, start) + masked(fragment.slice(start), \"&\");\n }\n\n return parsed.href.replaceAll(encodeURIComponent(withheld), withheld);\n };\n\n return { withheld, redact };\n};\n\nexport const { withheld, redact } = addresses();\n\n/** An address inside text, as a failure's message quotes one. */\nexport const quoted = /[a-z][a-z\\d+.-]*:\\/\\/[^\\s\"'<>]+/gi;\n\n/** `text` with each address in it redacted. */\nexport const redactWithin = (text: string) => text.replace(quoted, (url) => redact(url));\n"],"mappings":";;;;;;;;;;;;;;;AAMA,MAAM,SAAS;AAGf,MAAM,cAAc;AAEpB,MAAM,WAAW;;AAGjB,MAAa,SAAS,UAA8B;CAClD,MAAM,OAAO,MAAM,KAAK;CAExB,IAAI,OAAO,KAAK,IAAI,KAAK,CAAC,YAAY,KAAK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S,MAAM,GAAG,KAAK,IAAI,OAAO,SAAS,MAAM,KAAK,GAAG,GAAG;EAC5E;EAEA,OAAO,OAAO,KAAK,WAAW,mBAAmB,QAAQ,GAAG,QAAQ;CACtE;CAEA,OAAO;EAAE;EAAU;CAAO;AAC5B;AAEA,MAAa,EAAE,UAAU,WAAW,UAAU;;AAG9C,MAAa,SAAS;;AAGtB,MAAa,gBAAgB,SAAiB,KAAK,QAAQ,SAAS,QAAQ,OAAO,GAAG,CAAC"}
@@ -1,34 +0,0 @@
1
- import { t as BrowserError } from "./BrowserError-BlcmLVzn.mjs";
2
- import { E as WheelScrolled, S as TextInserted, T as TrackPlanned, a as CursorChanged, c as Disconnected, d as PageClosed, f as PageLoaded, g as PointerReleased, h as PointerPressed, l as KeyChanged, m as PageUntracked, o as DialogShown, p as PageOpened, t as Action, u as Navigated, v as RequestRefused, w as TrackPerformed, y as SessionEnding } from "./BrowserEvent-lLqJ3GJS.mjs";
3
- import { r as Changes } from "./Change-Ba7INmay.mjs";
4
- import { r as Frame } from "./Frame-UEH2hO5T.mjs";
5
- import { Schema } from "effect";
6
- declare namespace Window_d_exports {
7
- export { Window };
8
- }
9
- declare const Window_base: Schema.Class<Window, Schema.Struct<{
10
- readonly page: Schema.String;
11
- /** Where the window starts, in host monotonic milliseconds on the owning browser’s clock. */
12
- readonly since: Schema.Finite;
13
- /** Where it ends, never after it was taken. */
14
- readonly until: Schema.Finite;
15
- /** The page's events after `since`, up to `until`, oldest first, without the input presentation track. */
16
- readonly events: Schema.$Array<Schema.Union<readonly [typeof RequestRefused, typeof PageOpened, typeof PageClosed, typeof PageUntracked, typeof Navigated, typeof PageLoaded, typeof Action, typeof TrackPlanned, typeof TrackPerformed, typeof PointerPressed, typeof PointerReleased, typeof WheelScrolled, typeof KeyChanged, typeof TextInserted, typeof CursorChanged, typeof DialogShown, typeof Disconnected, typeof SessionEnding]>>;
17
- /**
18
- * What visibly changed after `since`, up to `until`; absent where `missing` says why. A page's
19
- * first window starts its record, so the record sees none of it.
20
- */
21
- readonly changes: Schema.optional<typeof Changes>;
22
- /** Screencast frames painted from `since` to `until`, oldest first, as far back as kept. */
23
- readonly frames: Schema.$Array<typeof Frame>;
24
- /**
25
- * Why each part that could not be read is missing: the read of its changes, by whatever
26
- * operation failed there, or a moment's picture (`frame`) or outline (`snapshot`).
27
- */
28
- readonly missing: Schema.$Array<typeof BrowserError>;
29
- }>, {}>;
30
- /** A page's events, changes and frames over one window of its browser's host clock. */
31
- declare class Window extends Window_base {}
32
- //#endregion
33
- export { Window_d_exports as n, Window as t };
34
- //# sourceMappingURL=Window-CMddGMt1.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"connection-CK83pvqP.mjs","names":["Errors.InvalidRequest","Url.quoted","Errors.Timeout","Browser.make","Browser.Browser"],"sources":["../src/providers/connection.ts"],"sourcesContent":["/**\n * A browser reached over the Chrome DevTools Protocol: a Chrome started with\n * `--remote-debugging-port`, or any provider that hands out a CDP WebSocket URL.\n *\n * Closing the scope disconnects. It does not close the remote browser; its owner does that.\n *\n * @since 0.3.0\n */\nimport { type DateTime, Effect, Layer, Redacted } from \"effect\";\nimport type { Browser as PlaywrightBrowser } from \"playwright-core\";\n\nimport * as Browser from \"../Browser.ts\";\nimport * as Errors from \"../BrowserError.ts\";\nimport { reasonOf, undispatched } from \"../BrowserError.ts\";\nimport * as Url from \"../Url.ts\";\n\n/** The runtime connector receives the bound and cancellation signal owned by the opening scope. */\nexport interface ConnectOptions {\n readonly timeout: number;\n readonly headers?: Readonly<Record<string, string>> | undefined;\n readonly signal: AbortSignal;\n}\n\n/**\n * Return a real Playwright CDP browser whose `close()` disconnects without ending the remote\n * browser. Honor `signal` to cancel work; a browser returned after cancellation is disconnected.\n * The endpoint and headers may contain credentials and must not be logged.\n */\nexport type Connector = (endpoint: string, options: ConnectOptions) => Promise<PlaywrightBrowser>;\n\nexport interface Options extends Browser.Options, Pick<ConnectOptions, \"headers\"> {\n /**\n * `ws://`, `wss://` or `http://` DevTools endpoint. Often a credential, so it may be redacted;\n * connect failures never include its userinfo, path or query.\n */\n readonly endpoint: string | Redacted.Redacted<string>;\n /** Runtime-supplied Playwright connection. Required by the `workerd` entry. */\n readonly connect?: Connector | undefined;\n /** Identifies the session in `Browser.id`. Defaults to `\"cdp\"`. */\n readonly id?: string | undefined;\n readonly provider?: string | undefined;\n /** Bound on connecting. Defaults to 30 seconds. */\n readonly connectTimeoutMillis?: number | undefined;\n /** When the provider ends the session on its own, as a hosted session's timeout does. */\n readonly expiresAt?: DateTime.Utc | undefined;\n /**\n * A connection apart from this one for the pages' screencasts, as a hosted provider supplies.\n * Without one, each page's capture runs on its own session.\n */\n readonly capture?: Browser.CaptureSource | undefined;\n}\n\n/** Runtime facades supply the default transport; the shared lifetime imports no Node transport. */\nexport const make = (defaultConnect?: Connector) => {\n const open = Effect.fn(\"Cdp.open\")(function* (options: Options) {\n const endpoint = Redacted.isRedacted(options.endpoint)\n ? Redacted.value(options.endpoint)\n : options.endpoint;\n\n const timeout = options.connectTimeoutMillis ?? 30_000;\n const connector = options.connect ?? defaultConnect;\n const headers = options.headers === undefined ? undefined : { ...options.headers };\n\n const invalid = (detail: string) =>\n undispatched(\"connect\", new Errors.InvalidRequest({ detail }));\n\n if (!Number.isFinite(timeout) || timeout <= 0)\n return yield* invalid(\"connectTimeoutMillis must be finite and greater than zero\");\n if (connector === undefined)\n return yield* invalid(\"This runtime requires a CDP connect callback\");\n\n // Inspect before URL normalization or truncation. Withhold an echoed diagnostic entirely so\n // overlapping header values cannot leave fragments; other URLs keep only their scheme and host.\n const redact = (message: string) => {\n if (Object.values(headers ?? {}).some((value) => value !== \"\" && message.includes(value)))\n return \"CDP diagnostic withheld\";\n\n const origins = message.replace(Url.quoted, (url) => {\n const parsed = URL.parse(url);\n\n return parsed?.host ? `${parsed.protocol}//${parsed.host}` : \"<url>\";\n });\n\n return endpoint === \"\" ? origins : origins.replaceAll(endpoint, \"<endpoint>\");\n };\n\n const failed = (cause: unknown, timeoutMillis?: number) =>\n undispatched(\"connect\", reasonOf(cause, timeoutMillis, \"connection\", redact));\n\n // The endpoint is often a credential, so the connect span names no part of it.\n const connected = yield* Effect.acquireRelease(\n Effect.tryPromise({\n try: (signal) =>\n connector(endpoint, {\n timeout,\n signal,\n ...(headers === undefined ? {} : { headers: { ...headers } }),\n }).then(async (browser) => {\n // Cancellation can precede a connector that ignores its signal. Its late browser still\n // belongs to this acquisition, so disconnect it before dropping the promise result.\n if (signal.aborted) await browser.close().catch(() => undefined);\n\n return browser;\n }),\n catch: (cause) => failed(cause, timeout),\n }).pipe(\n Effect.timeoutOrElse({\n duration: timeout,\n orElse: () =>\n Effect.fail(undispatched(\"connect\", new Errors.Timeout({ millis: timeout }))),\n }),\n Effect.withSpan(\"Cdp.connect\", {}, { captureStackTrace: false }),\n ),\n (browser) => Effect.tryPromise(() => browser.close()).pipe(Effect.ignore),\n { interruptible: true },\n );\n\n const context =\n connected.contexts()[0] ??\n (yield* Effect.tryPromise({\n try: () => connected.newContext(),\n catch: (cause) => failed(cause),\n }));\n\n const { id = \"cdp\", provider = \"cdp\", expiresAt, capture } = options;\n\n return yield* Browser.make(context, { id, provider, expiresAt, capture }, options);\n });\n\n const layer = (options: Options): Layer.Layer<Browser.Browser, Errors.BrowserError> =>\n Layer.effect(Browser.Browser, open(options));\n\n return { open, layer };\n};\n"],"mappings":";;;;;;;;;;;;;;AAqDA,MAAa,QAAQ,mBAA+B;CAClD,MAAM,OAAO,OAAO,GAAG,UAAU,CAAC,CAAC,WAAW,SAAkB;EAC9D,MAAM,WAAW,SAAS,WAAW,QAAQ,QAAQ,IACjD,SAAS,MAAM,QAAQ,QAAQ,IAC/B,QAAQ;EAEZ,MAAM,UAAU,QAAQ,wBAAwB;EAChD,MAAM,YAAY,QAAQ,WAAW;EACrC,MAAM,UAAU,QAAQ,YAAY,KAAA,IAAY,KAAA,IAAY,EAAE,GAAG,QAAQ,QAAQ;EAEjF,MAAM,WAAW,WACf,aAAa,WAAW,IA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C,CAAC,KAAK,OAAO,MAAM,GACxE,EAAE,eAAe,KAAK,CACxB;EAEA,MAAM,UACJ,UAAU,SAAS,CAAC,CAAC,OACpB,OAAO,OAAO,WAAW;GACxB,WAAW,UAAU,WAAW;GAChC,QAAQ,UAAU,OAAO,KAAK;EAChC,CAAC;EAEH,MAAM,EAAE,KAAK,OAAO,WAAW,OAAO,WAAW,YAAY;EAE7D,OAAO,OAAOC,OAAa,SAAS;GAAE;GAAI;GAAU;GAAW;EAAQ,GAAG,OAAO;CACnF,CAAC;CAED,MAAM,SAAS,YACb,MAAM,OAAOC,SAAiB,KAAK,OAAO,CAAC;CAE7C,OAAO;EAAE;EAAM;CAAM;AACvB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"Moment.mjs","names":[],"sources":["../../src/moment/words.ts","../../src/moment/Moment.ts"],"sourcesContent":["/**\n * What changed on a page, in words for a model: a change with where it is, and what it is. A moment\n * tells its changes this way, and a tool's receipt the changes its action caused.\n */\nimport type { Subject, SubjectContext } from \"../BrowserEvent.ts\";\nimport type { Change } from \"../Change.ts\";\n\nexport const quoted = (value: string | undefined) => JSON.stringify(value ?? \"\");\n\n/** A subject in words, such as `button \"Play\"`; one without a name says where it was. */\nexport const named = (subject: Subject, point: string | undefined) => {\n const kind = subject.role ?? subject.tag;\n\n if (subject.name !== \"\") return `${kind} ${JSON.stringify(subject.name)}`;\n\n return point === undefined ? kind : `${kind} at ${point}`;\n};\n\n/** A change's context in words: `row \"Ether\", column \"1h\"` or `beside \"Price\", under \"Bitcoin\"`. */\nexport const where = ({ row, column, label, heading }: SubjectContext, grouped = false) => {\n const parts = [\n row === undefined ? \"\" : `row ${quoted(row)}`,\n column === undefined || grouped ? \"\" : `column ${quoted(column)}`,\n label === undefined ? \"\" : `beside ${quoted(label)}`,\n heading === undefined || grouped ? \"\" : `under ${quoted(heading)}`,\n ].filter((part) => part !== \"\");\n\n return parts.length === 0 ? \"\" : ` (${parts.join(\", \")})`;\n};\n\n/** A change in words, such as `\"$61,240\" became \"$62,010\" (row \"Bitcoin\", column \"Price\")`. */\nexport const describe = (change: Change, grouped = false): string => {\n const { subject, before, after, count, lowest, highest } = change;\n const context = where(subject.context, grouped);\n\n const range =\n lowest === undefined || highest === undefined ? \"\" : `, from ${lowest} to ${highest}`;\n\n const times = count > 1 ? ` (it changed ${count} times${range})` : \"\";\n\n switch (change.kind) {\n case \"title\":\n return `the title ${before === undefined ? \"now reads\" : `${quoted(before)} became`} ${quoted(after)}`;\n case \"value\": {\n const field = named(subject, undefined);\n\n if (after === \"checked\" || after === \"not checked\") return `${field} is now ${after}`;\n if (after === undefined || after === \"\") return `${field} was cleared`;\n\n return after === \"••••\" || before === undefined || before === \"\"\n ? `${field} was ${after === \"••••\" ? \"edited\" : `set to ${quoted(after)}`}`\n : `${field} changed from ${quoted(before)} to ${quoted(after)}`;\n }\n case \"appeared\":\n return `${quoted(after)} appeared${context}`;\n case \"disappeared\":\n return `${quoted(before)} disappeared${context}`;\n case \"brief\":\n return `${quoted(after)} appeared and went away again${context}`;\n case \"text\":\n return before === undefined\n ? `now reads ${quoted(after)}${context}${times}`\n : `${quoted(before)} became ${quoted(after)}${context}${times}`;\n }\n};\n","/**\n * What a page showed, and what changed on it, over a window of time.\n *\n * A page's timeline has three tracks on its browser's host clock: its events, what visibly changed\n * on it (`Change`), and its screencast frames. A `Window` holds the three from `since` to `until`,\n * and says why a part it could not read is missing rather than fail. `Page.window` takes one, which\n * can end in the past, at a frame a delayed consumer airs late, so that a line written now tells\n * what its viewers will see. Its `account` says what was so at its end: how long the page had been\n * still, which of its changes were still under way, and which had settled.\n *\n * A `Moment` is a window that ends at a picture of the page now: `capture` takes the picture, then\n * the window up to it, and on request the page's outline. `toPrompt` turns a moment into one user\n * message for any `effect/ai` call: a structured answer from `LanguageModel.generateObject`, a\n * caption from `generateText`, or one turn of a `Chat` that follows moment after moment. It leads\n * with what changed, news and what settled before what was still changing, as its account tells\n * them apart, and names an action as what a change followed; as a step where changes followed it\n * but none names it, or where its effect is drawn rather than written, as on a canvas, which only\n * the screenshots show; and claims nothing of what changed where the record did not see, or of a\n * part it could not read, which it names with why.\n *\n * Frames come from a running screencast, as far back as the browser's `frameHistory` keeps them.\n * A moment's picture is the newest frame if it was painted after the page's latest input and\n * completed action, at most 250 ms ago, else a new screenshot timed by its capture.\n *\n * @since 0.3.0\n */\nimport { Duration, Effect, Option, Result, Schema } from \"effect\";\nimport { Prompt } from \"effect/ai\";\n\nimport { refuse } from \"../BrowserError.ts\";\nimport { type Action } from \"../BrowserEvent.ts\";\nimport { type Change, type Changes } from \"../Change.ts\";\nimport { type Frame } from \"../Frame.ts\";\nimport type * as Page from \"../Page.ts\";\nimport { Snapshot, type SnapshotOptions } from \"../Snapshot.ts\";\nimport { describe, named, quoted, where } from \"./words.ts\";\n\nexport { Window } from \"../Window.ts\";\nimport { Window } from \"../Window.ts\";\n\n/**\n * A window that ends at a picture of the page, its last frame, unless `missing` says why it has\n * none. Its frames are a few, spread over the window, so that it still begins where it starts.\n */\nexport class Moment extends Window.extend<Moment>(\"effect-browser/Moment\")({\n /** The page's outline at the end of the window, when the capture asked for it. */\n snapshot: Schema.optional(Snapshot),\n}) {}\n\nexport interface CaptureOptions {\n /**\n * Where the window starts, as for `Page.window`: a previous window or moment, so that consecutive\n * ones neither repeat nor miss an event or a change, or a `Duration` back from the picture.\n * Defaults to 5 seconds.\n */\n readonly since?: Page.WindowOptions[\"since\"] | undefined;\n /** Frames to keep, at least 1, spread over the window and ending with the picture. Defaults to 2. */\n readonly frames?: number | undefined;\n /**\n * Whether to take the page's outline at the end, or its options; `true` means 4,000 characters.\n * Defaults to `false`: the frames and the timeline carry most moments, while an outline costs a\n * round trip to the page and can double a moment's tokens.\n */\n readonly snapshot?: SnapshotOptions | boolean | undefined;\n /** Show what fields hold in the moment's changes; a secret field still reads `••••`. */\n readonly unmask?: boolean | undefined;\n}\n\n/** Pick `count` frames spread evenly over `frames`, always including the last. */\nconst spread = (frames: ReadonlyArray<Frame>, count: number): ReadonlyArray<Frame> => {\n if (frames.length <= count) return frames;\n if (count <= 1) return frames.slice(-1);\n const step = (frames.length - 1) / (count - 1);\n\n return Array.from({ length: count }, (_, index) => frames[Math.round(index * step)]).filter(\n (frame): frame is Frame => frame !== undefined,\n );\n};\n\n// An action ends after its navigation settles, which can follow the last paint. A fresh picture\n// keeps that completed action inside the moment without moving events between adjacent windows.\nconst pictureOf = Effect.fnUntraced(function* (page: Page.Page) {\n const frame = yield* page.frame({ after: \"input\" });\n const events = yield* page.recentEvents;\n\n return events.some((event) => event._tag === \"Action\" && event.at > frame.hostTime)\n ? yield* page.frame({ maxAge: 0 })\n : frame;\n});\n\nexport const capture = Effect.fn(\"Moment.capture\")(function* (\n page: Page.Page,\n options: CaptureOptions = {},\n) {\n const count = options.frames ?? 2;\n\n if (!Number.isSafeInteger(count) || count < 1)\n return yield* refuse(\"moment\", \"frames must be a positive safe integer\");\n const outline = options.snapshot ?? false;\n\n // The picture comes first, at no call with a running screencast, and the window ends at its\n // paint, so its changes hold nothing it does not show; without one, the window ends now. The\n // outline is taken alongside. What cannot be read is missing from the moment, not its end.\n const { pictured, outlined } = yield* Effect.all(\n {\n pictured: Effect.result(pictureOf(page)).pipe(\n Effect.flatMap((picture) =>\n Effect.map(\n page.window({\n since: options.since ?? Duration.seconds(5),\n until: Result.getOrUndefined(picture),\n unmask: options.unmask,\n }),\n (window) => ({ window, picture }),\n ),\n ),\n ),\n outlined: Effect.result(\n outline === false\n ? Effect.void\n : page.snapshot({ maxChars: 4000, ...(outline === true ? {} : outline) }),\n ),\n },\n { concurrency: 2 },\n );\n\n const { window, picture } = pictured;\n const shown = Result.getOrUndefined(picture);\n\n return new Moment({\n ...window,\n frames: spread(\n shown === undefined\n ? window.frames\n : [...window.frames.filter((frame) => frame !== shown), shown],\n count,\n ),\n snapshot: Result.getOrUndefined(outlined) ?? undefined,\n missing: [\n ...window.missing,\n ...Option.toArray(Result.getFailure(picture)),\n ...Option.toArray(Result.getFailure(outlined)),\n ],\n });\n});\n\n/** A window's record of changes, if it saw any of the window: a page's first has none. */\nconst recordOf = ({ changes }: Window) =>\n changes !== undefined && changes.from < changes.until ? changes : undefined;\n\n/** What a window says of its page at its end: what was still in flux, and what had settled. */\nexport interface Account {\n /**\n * How long, in milliseconds, the page had been still at the end: since the last change in view\n * its record shows, or the last paint its screencast frames show, or else since the window, or\n * its record, began. Undefined where neither could tell, with no record of the window and no\n * painted frame: a screenshot shows the page, not when it last changed. Frames show paint only\n * while a capture runs, and the record does not see a canvas, so a canvas that keeps drawing\n * with no capture running reads as still.\n */\n readonly stillFor: number | undefined;\n /**\n * The changes still under way at the end: what kept changing, more than once in the window or\n * already before it, and changed again within twice its own pace before the end.\n */\n readonly changing: ReadonlyArray<Change>;\n /** Every other change, which shows what it settled at. */\n readonly settled: ReadonlyArray<Change>;\n}\n\n/** Whether a change was still under way at `until`, by its own pace. */\nconst underWay = (change: Change, until: number) => {\n const pace =\n change.count > 1\n ? (change.at - change.startedAt) / (change.count - 1)\n : change.earlier === undefined\n ? undefined\n : change.startedAt - change.earlier;\n\n return pace !== undefined && until - change.at < 2 * pace;\n};\n\n/**\n * An account of the window's page at its end: how long it had been still, and which of its\n * changes were still under way and which had settled. A window whose record saw none of it has\n * neither.\n */\nexport const account = (window: Window): Account => {\n const record = recordOf(window);\n const changes = record?.changes ?? [];\n\n const stirred = [\n ...changes.flatMap((change) => (change.kind === \"title\" ? [] : [change.at])),\n ...window.frames.flatMap((frame) =>\n frame.timing._tag === \"BrowserPaint\" ? [frame.hostTime] : [],\n ),\n ];\n\n return {\n stillFor:\n record === undefined && stirred.length === 0\n ? undefined\n : window.until - Math.max(window.since, record?.from ?? window.since, ...stirred),\n changing: changes.filter((change) => underWay(change, window.until)),\n settled: changes.filter((change) => !underWay(change, window.until)),\n };\n};\n\nconst seconds = (moment: Moment, at: number) => `${((at - moment.until) / 1000).toFixed(1)}s`;\n\nconst pointOf = (x: number | undefined, y: number | undefined) =>\n x === undefined || y === undefined ? undefined : `(${Math.round(x)}, ${Math.round(y)})`;\n\n/**\n * What an action acted on. Without a subject the action failed before finding it, and a ref it was\n * given is left out: refs are reused, so the page's outline may give it to something else by now.\n */\nconst acted = (event: Action): string => {\n const point = pointOf(event.x, event.y);\n\n if (event.subject === undefined)\n return event.target === undefined || /^e\\d+$|\"e\\d+\"/.test(event.target)\n ? (point ?? \"\")\n : event.target;\n // A drag's point is where it ended.\n if (event.to !== undefined)\n return `${named(event.subject, undefined)} to ${named(event.to, point)}`;\n\n return named(event.subject, point);\n};\n\n/**\n * An action as a step: `click button \"Pay\"`. A failed one says only that: its error is advice for\n * the caller that acted, which may name a ref, not a fact about the page.\n */\nconst step = (event: Action): string => {\n const target = acted(event);\n const text = event.text === undefined ? \"\" : JSON.stringify(event.text);\n\n const what =\n event.name === \"type\" && target !== \"\"\n ? `${text} into ${target}`\n : event.name === \"select\" && target !== \"\"\n ? `${text} in ${target}`\n : `${target} ${text}`;\n\n return `${event.name} ${what}${event.ok ? \"\" : \" (failed)\"}`.replace(/\\s+/g, \" \").trim();\n};\n\n/** What is drawn rather than written, whose changes only the screenshots show. */\nconst drawn = new Set([\"canvas\", \"iframe\", \"video\", \"embed\", \"object\", \"svg\"]);\n\nconst onDrawn = (event: Action) =>\n event.ok && event.subject !== undefined && drawn.has(event.subject.role ?? event.subject.tag);\n\ninterface Line {\n readonly at: number;\n readonly rank: number;\n readonly text: string;\n}\n\n/** At most this many lines of what happened; the least notable are counted, not listed. */\nconst maxLines = 24;\n\n/**\n * The changes as lines, news first, and the actions they name; cells of one column that changed\n * together as one line. What kept changing says whether it still was at the moment, by its account.\n */\nconst changed = (moment: Moment, record: Changes) => {\n const actions = moment.events.filter((event): event is Action => event._tag === \"Action\");\n const named = new Set<Action>();\n const changing = new Set(account(moment).changing);\n\n const state = (change: Change) =>\n changing.has(change)\n ? \", still changing at the moment\"\n : change.count > 1 || change.earlier !== undefined\n ? `, settled since ${seconds(moment, change.at)}`\n : \"\";\n\n // The action whose input a change followed: one that ran while the input arrived, give or take\n // the clock's mapping, so input the library did not send names no action.\n const cause = (change: Change) => {\n const input = change.cause;\n\n const action =\n input === undefined\n ? undefined\n : actions.findLast((event) => event.startedAt <= input + 100 && event.at >= input - 100);\n\n if (action === undefined) return \"\";\n named.add(action);\n\n return `, after ${step(action)}`;\n };\n\n const columns = Map.groupBy(\n record.changes.filter(\n (change) => change.kind === \"text\" && change.subject.context.column !== undefined,\n ),\n ({ subject: { context } }) => JSON.stringify([context.heading, context.column]),\n );\n\n const lines: Array<Line> = [];\n const collapsed = new Set<Change>();\n\n for (const [first, ...cells] of columns.values())\n if (first !== undefined && cells.length >= 2) {\n const still = [first, ...cells].filter((cell) => changing.has(cell)).length;\n\n for (const cell of [first, ...cells]) collapsed.add(cell);\n lines.push({\n at: first.startedAt,\n rank: still > 0 ? 3 : 2,\n text: `${cells.length + 1} cells in column ${quoted(first.subject.context.column)}${where({ heading: first.subject.context.heading })} changed, such as ${describe(first, true)}${still > 0 ? `, ${still} still changing at the moment` : \"\"}`,\n });\n }\n for (const change of record.changes)\n if (!collapsed.has(change))\n lines.push({\n at: change.startedAt,\n rank: changing.has(change) ? 3 : 2,\n text: describe(change) + cause(change) + state(change),\n });\n\n return { lines, named };\n};\n\n/** What a part a moment could not read was, by the operation that failed: a window's one read is its changes. */\nconst parts = new Map([\n [\"frame\", \"A picture of the moment\"],\n [\"snapshot\", \"The page's outline\"],\n]);\n\n/** The moment's changes and events as lines, most notable first when its changes are recorded. */\nconst happened = (moment: Moment): ReadonlyArray<string> => {\n const record = recordOf(moment);\n\n const { lines, named } =\n record === undefined\n ? { lines: new Array<Line>(), named: new Set<Action>() }\n : changed(moment, record);\n\n // Whether anything but a field's own edit changed after an action began.\n const followed = (event: Action) =>\n record?.changes.some((change) => change.kind !== \"value\" && change.at > event.startedAt) ===\n true;\n\n // With a record, an action is told as a step where changes followed it and none names it, so a\n // click whose effect a busy page leaves uncredited is not lost; where its effect is drawn; or\n // where it started before the record began, as on the document a click opened. An attempt that\n // nothing followed, a failed one, a hover and a scroll are left out.\n const told = (event: Action) =>\n !(event.ok && [\"navigate\", \"back\", \"reload\"].includes(event.name)) &&\n (record === undefined ||\n event.startedAt <= record.from ||\n (event.ok &&\n event.name !== \"scroll\" &&\n (onDrawn(event) || (event.name !== \"hover\" && !named.has(event) && followed(event)))));\n\n for (const event of moment.events)\n if (event._tag === \"Action\" && event.page === moment.page && told(event))\n lines.push({ at: event.at, rank: 4, text: step(event) });\n else if (event._tag === \"Navigated\")\n lines.push({\n at: event.at,\n rank: 0,\n text: `${event.sameDocument ? \"moved within the page\" : \"navigated\"} to ${event.url}`,\n });\n else if (event._tag === \"PageOpened\")\n lines.push({ at: event.at, rank: 0, text: `a tab opened at ${event.url}` });\n else if (event._tag === \"PageClosed\")\n lines.push({\n at: event.at,\n rank: 0,\n text: `the tab ${event.cause === \"crashed\" ? \"crashed\" : \"closed\"}`,\n });\n else if (event._tag === \"DialogShown\")\n lines.push({\n at: event.at,\n rank: 1,\n text: `a dialog (${event.kind}) said ${JSON.stringify(event.message)}`,\n });\n\n const ordered = lines.toSorted((left, right) =>\n record === undefined ? left.at - right.at : left.rank - right.rank || left.at - right.at,\n );\n\n const kept = ordered.slice(0, maxLines);\n const drawing = moment.events.some((event) => event._tag === \"Action\" && onDrawn(event));\n const begins = record === undefined ? moment.since : Math.max(moment.since, record.from);\n const unread = moment.missing.some((error) => !parts.has(error.operation));\n\n return [\n ...kept.map((line) => `${seconds(moment, line.at)} ${line.text}`),\n ...(ordered.length > maxLines ? [`…and ${ordered.length - maxLines} less notable`] : []),\n ...(record === undefined\n ? unread\n ? []\n : [\"What changed on the page was not recorded.\"]\n : record.changes.length > 0\n ? []\n : [\n `No text in view changed${begins > moment.since ? ` after ${seconds(moment, begins)}` : \"\"}${drawing ? \"; what is drawn, such as a canvas, shows only in the screenshots\" : \"\"}.`,\n ]),\n ...(record !== undefined && record.dropped > 0\n ? [\n `The page changed too much to tell it all: at least ${record.dropped} changes are not told.`,\n ]\n : []),\n ...(begins > moment.since\n ? [`Changes before ${seconds(moment, begins)} are not all known.`]\n : []),\n ...moment.missing.map(\n (error) =>\n `${parts.get(error.operation) ?? \"What changed on the page\"} could not be read: ${error.reason.message}.`,\n ),\n ];\n};\n\n/**\n * The moment as one user message: the page's outline when the moment has one, what changed, most\n * notable first, what kept changing told as still changing at the moment or settled since when, by\n * its account, with the actions that the changes followed, that changes followed though none\n * names them, or that drew what only the screenshots show, what could not be read and why, and its\n * frames captioned with their times, the last one \"the moment\" where it is the picture at its end.\n * Give a model its task with `Prompt.setSystem`, and add what the caller knows about the page as\n * more text.\n */\nexport const toPrompt = (moment: Moment): Prompt.Prompt => {\n const count = moment.frames.length;\n const last = count - 1;\n const pictured = moment.frames.at(-1)?.hostTime === moment.until;\n\n const following =\n count === 1 ? \"One screenshot follows\" : `${count} screenshots follow, oldest first`;\n\n return Prompt.fromMessages([\n Prompt.makeMessage(\"user\", {\n content: [\n Prompt.makePart(\"text\", {\n text: [\n \"One moment of a browser session. Rely only on what this material shows, and prefer concrete details: numbers, names, colours, positions and motion.\",\n \"\",\n ...(moment.snapshot === undefined ? [] : [moment.snapshot.rendered, \"\"]),\n `${recordOf(moment) === undefined ? \"What happened\" : \"What changed, most notable first\"} (seconds before the moment, over ${((moment.until - moment.since) / 1000).toFixed(1)}s):`,\n ...happened(moment),\n ...(count === 0\n ? []\n : [\n \"\",\n `${following}${pictured ? (count === 1 ? \": the moment itself.\" : \"; the last one is the moment itself.\") : \".\"}`,\n ]),\n ].join(\"\\n\"),\n }),\n ...moment.frames.flatMap((frame, index) => [\n Prompt.makePart(\"text\", {\n text:\n index === last && pictured ? \"The moment:\" : `${seconds(moment, frame.hostTime)}:`,\n }),\n Prompt.makePart(\"file\", { mediaType: \"image/jpeg\", data: frame.data }),\n ]),\n ],\n }),\n ]);\n};\n\n/** Describe one change using the same prose as moment prompts. */\nexport { describe as describeChange } from \"./words.ts\";\n"],"mappings":";;;;;;AAOA,MAAa,UA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,YAAY,WAAkC;CACzD,MAAM,QAAQ,OAAO,OAAO;CAC5B,MAAM,OAAO,QAAQ;CACrB,MAAM,WAAW,OAAO,OAAO,GAAG,EAAE,CAAC,EAAE,aAAa,OAAO;CAE3D,MAAM,YACJ,UAAU,IAAI,2BAA2B,GAAG,MAAM;CAEpD,OAAO,OAAO,aAAa,CACzB,OAAO,YAAY,QAAQ,EACzB,SAAS,CACP,OAAO,SAAS,QAAQ,EACtB,MAAM;EACJ;EACA;EACA,GAAI,OAAO,aAAa,KAAA,IAAY,CAAC,IAAI,CAAC,OAAO,SAAS,UAAU,EAAE;EACtE,GAAG,SAAS,MAAM,MAAM,KAAA,IAAY,kBAAkB,mCAAmC,sCAAsC,OAAO,QAAQ,OAAO,SAAS,IAAA,CAAM,QAAQ,CAAC,EAAE;EAC/K,GAAG,SAAS,MAAM;EAClB,GAAI,UAAU,IACV,CAAC,IACD,CACE,IACA,GAAG,YAAY,WAAY,UAAU,IAAI,yBAAyB,yCAA0C,KAC9G;CACN,CAAC,CAAC,KAAK,IAAI,EACb,CAAC,GACD,GAAG,OAAO,OAAO,SAAS,OAAO,UAAU,CACzC,OAAO,SAAS,QAAQ,EACtB,MACE,UAAU,QAAQ,WAAW,gBAAgB,GAAG,QAAQ,QAAQ,MAAM,QAAQ,EAAE,GACpF,CAAC,GACD,OAAO,SAAS,QAAQ;EAAE,WAAW;EAAc,MAAM,MAAM;CAAK,CAAC,CACvE,CAAC,CACH,EACF,CAAC,CACH,CAAC;AACH"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.mjs","names":["invalid","Stillness.wait"],"sources":["../../src/plan/choose.ts","../../src/plan/data.ts","../../src/plan/record.ts","../../src/plan/targets.ts","../../src/plan/execute.ts"],"sourcesContent":["/**\n * Choosing the one element a recorded subject names, among those `find` gives for its role and\n * name. Context tells them apart, and an element that does not repeat every part of the recorded\n * context is another subject, so a sole element left once its own has gone, such as Alice's\n * \"Remove\" after Bob has left, drifts rather than stands in:\n *\n * - a row is read whole: a row named \"Wrapped BTC\" is not the row \"BTC\". Laid out again without\n * rows, as cards, one of the element's fields must start with the row's words;\n * - a column counts where the element is under one;\n * - a label or heading must read the same, or its words appear, whole and in order, in one of the\n * element's fields, as `near` reads them.\n *\n * The rest are ranked by how much of the recorded context they read the same. There is no\n * ordinal, so a tie stays a tie.\n */\nimport { Effect, Schema } from \"effect\";\n\nimport type { Subject, SubjectContext } from \"../BrowserEvent.ts\";\nimport { match } from \"../Matching.ts\";\nimport type { Found } from \"../Page.ts\";\n\n/** Nothing on the page has the step's role and name. */\nexport class Missing extends Schema.TaggedError<Missing>()(\"Missing\", {}) {\n override get message() {\n return \"nothing on the page has the recorded role and name\";\n }\n}\n\n/** Several elements match the step's subject equally well, and nothing tells them apart. */\nexport class Ambiguous extends Schema.TaggedError<Ambiguous>()(\"Ambiguous\", {\n count: Schema.Int,\n}) {\n override get message() {\n return `${this.count} elements match the recorded subject equally well`;\n }\n}\n\n/** The page is not where the recording was: another site, or no element with its context. */\nexport class Drifted extends Schema.TaggedError<Drifted>()(\"Drifted\", {\n detail: Schema.String,\n}) {\n override get message() {\n return this.detail;\n }\n}\n\nconst { holds, normalize } = match();\nconst fields = [\"row\", \"column\", \"label\", \"heading\"] as const;\n\nconst said = (context: SubjectContext) =>\n Object.values(context).filter((value) => typeof value === \"string\");\n\n/** How an element repeats one recorded field: 2 read the same, 1 found as words, 0 not at all. */\nconst repeats = (field: (typeof fields)[number], value: string, context: SubjectContext) => {\n const own = context[field];\n\n if (own !== undefined && normalize(own) === normalize(value)) return 2;\n if (field === \"column\") return own === undefined ? 1 : 0;\n if (field === \"row\")\n return own === undefined &&\n said(context).some((other) => `${normalize(other)} `.startsWith(`${normalize(value)} `))\n ? 1\n : 0;\n\n return said(context).some((other) => holds(other, value)) ? 1 : 0;\n};\n\nexport const choose = (\n subject: Subject,\n found: ReadonlyArray<Found>,\n): Effect.Effect<Found, Missing | Ambiguous | Drifted> => {\n // `find` matched the role; a subject without one only matches elements without one.\n const named = found.filter((one) => subject.role !== null || one.subject.role === null);\n\n const kept = named.flatMap((one) => {\n let score = 0;\n\n for (const field of fields) {\n const value = subject.context[field];\n const repeated = value === undefined ? 0 : repeats(field, value, one.subject.context);\n\n if (value !== undefined && repeated === 0) return [];\n score += repeated;\n }\n\n return [{ one, score }];\n });\n\n const best = Math.max(...kept.map(({ score }) => score));\n const top = kept.filter(({ score }) => score === best);\n const [only] = top;\n\n if (named.length === 0) return Effect.fail(new Missing());\n if (kept.length === 0)\n return Effect.fail(new Drifted({ detail: \"no element named so repeats the recorded context\" }));\n\n return top.length === 1 && only !== undefined\n ? Effect.succeed(only.one)\n : Effect.fail(new Ambiguous({ count: top.length }));\n};\n","/** Serializable plan steps, expected effects, receipts and durable stopping evidence. */\nimport { Schema } from \"effect\";\n\nimport { Action } from \"../Action.ts\";\nimport { BrowserError } from \"../BrowserError.ts\";\nimport { Box, Subject } from \"../BrowserEvent.ts\";\nimport { Ambiguous, Drifted, Missing } from \"./choose.ts\";\n\n/** Reuse the execution variants; recorded code has no serializable replay capability. */\nconst ReplayAction = Action.pipe(\n Schema.refine(\n (value): value is Exclude<Action, { readonly _tag: \"Act\" }> => value._tag !== \"Act\",\n ),\n);\n\nconst Query = Schema.Struct({\n role: Schema.optional(Schema.String),\n name: Schema.optional(Schema.String),\n text: Schema.optional(Schema.String),\n});\n\n/**\n * What a step leaves. `durable` asserts an author-chosen, lasting read-back of this operation,\n * such as its uniquely named saved receipt or exact operation URL. Only Appeared and an exact\n * Navigated URL allow it; a toast, absence or relative navigation cannot establish recovery.\n * Relative navigation measures observed change from dispatch, without asserting causality.\n */\nexport const Expected = Schema.Union([\n Schema.TaggedStruct(\"Checked\", { checked: Schema.Boolean }),\n Schema.TaggedStruct(\"Appeared\", {\n query: Query,\n durable: Schema.optional(Schema.Literal(true)),\n }),\n Schema.TaggedStruct(\"Gone\", {\n query: Query,\n durable: Schema.optional(Schema.Never),\n }),\n Schema.TaggedStruct(\"Navigated\", {\n url: Schema.String,\n durable: Schema.optional(Schema.Literal(true)),\n }),\n Schema.TaggedStruct(\"Navigated\", {\n url: Schema.optional(Schema.Never),\n durable: Schema.optional(Schema.Never),\n }),\n]);\n\nexport type Expected = typeof Expected.Type;\n\n/** One recorded step: the action, what it acted on, and what else it was asked. */\nexport class Step extends Schema.Class<Step>(\"effect-browser/Plan/Step\")({\n action: ReplayAction,\n /** The address reached, including a delayed navigation before the next action began. */\n url: Schema.String,\n subject: Schema.optional(Subject),\n /** Where a drag ended. */\n to: Schema.optional(Subject),\n /** The recorded box keeps a point at the same relative position within its subject. */\n box: Schema.optional(Box),\n /** A slot replaces recorded typing text or a navigation address with withheld credentials. */\n input: Schema.optional(Schema.String),\n expect: Schema.optional(Expected),\n}) {}\n\nexport class Plan extends Schema.Class<Plan>(\"effect-browser/Plan\")({\n version: Schema.Literal(3),\n steps: Schema.Array(Step),\n}) {\n /** Version 3 carries canonical typed Actions; prior string-action encodings are rejected. */\n static new(steps: ReadonlyArray<Step>): Plan {\n return new Plan({ version: 3, steps });\n }\n\n /** The input slots its steps type, in order; replay needs text for each. */\n get inputs(): ReadonlyArray<string> {\n return this.steps.flatMap((step) => (step.input === undefined ? [] : [step.input]));\n }\n}\n\n/** One completed step, on the page's host clock. `verified` means its expected effect was seen. */\nexport class Receipt extends Schema.Class<Receipt>(\"effect-browser/Plan/Receipt\")({\n step: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n outcome: Schema.Literals([\"taken\", \"verified\", \"skipped\"]),\n startedAt: Schema.Finite,\n at: Schema.Finite,\n}) {}\n\n/** Durable stopping data. A begun step without a receipt must be restored as `unknown`. */\nexport class Stopped extends Schema.Class<Stopped>(\"effect-browser/Plan/Stopped\")({\n step: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n input: Schema.Literals([\"unsent\", \"unknown\"]),\n}) {}\n\n/** Repeating this step could repeat an unresolved effect; the consumer must reconcile it. */\nexport class Uncertain extends Schema.TaggedError<Uncertain>()(\"Uncertain\", {\n detail: Schema.String,\n}) {\n override get message() {\n return this.detail;\n }\n}\n\n/** Where replay stopped, counting steps from 0, why, and the steps that completed before it. */\nexport class ReplayError extends Schema.TaggedError<ReplayError>()(\"ReplayError\", {\n step: Schema.Int,\n reason: Schema.Union([Missing, Ambiguous, Drifted, BrowserError, Uncertain]),\n input: Schema.Literals([\"unsent\", \"unknown\"]),\n receipts: Schema.Array(Receipt),\n}) {\n get stopped(): Stopped {\n return new Stopped({ step: this.step, input: this.input });\n }\n\n override get message() {\n return `step ${this.step} failed: ${this.reason.message}`;\n }\n}\n","/** Derive replay steps from typed action events without parsing rendered descriptions. */\nimport { targetOf } from \"../Action.ts\";\nimport { type Action, type BrowserEvent, type Navigated } from \"../BrowserEvent.ts\";\nimport { redacted } from \"../Page.ts\";\nimport { Plan, Step } from \"./data.ts\";\n\nconst isStep = (\n event: BrowserEvent,\n): event is Action & {\n readonly value: Exclude<Action[\"value\"], { readonly _tag: \"Act\" }>;\n} => event._tag === \"Action\" && event.ok && event.value._tag !== \"Act\";\n\n/** A slot named for the field it fills, such as `email`, unique within the plan. */\nconst slotFor = (taken: Set<string>, field: string | undefined) => {\n const base =\n field\n ?.toLowerCase()\n .match(/[\\p{L}\\p{N}]+/gu)\n ?.join(\"-\") ?? \"input\";\n\n let slot = base;\n\n for (let count = 2; taken.has(slot); count++) slot = `${base}-${count}`;\n taken.add(slot);\n\n return slot;\n};\n\n/**\n * The walk one page's events record: the completed actions of the page that acted first, in\n * order. `page.recentEvents` gives them, or `browser.events()` read until the walk ends.\n */\nexport const fromEvents = (events: Iterable<BrowserEvent>): Plan => {\n const all = Array.from(events);\n const page = all.find((event) => event._tag === \"Action\")?.page;\n const mine = all.filter((event) => \"page\" in event && event.page === page);\n const steps = mine.filter(isStep);\n const opened = mine.find((event) => event._tag === \"PageOpened\")?.url ?? \"\";\n const moves = mine.filter((event): event is Navigated => event._tag === \"Navigated\");\n const taken = new Set<string>();\n\n // Where the page was just before a time: the last address it reached by then.\n const before = (time: number) => moves.findLast((move) => move.at <= time)?.url ?? opened;\n\n return new Plan({\n version: 3,\n steps: steps.map((action, index) => {\n const value = action.value;\n\n const target = targetOf(value);\n const point = typeof target === \"object\" ? target : undefined;\n const until = steps[index + 1]?.startedAt ?? Number.POSITIVE_INFINITY;\n const arrival = moves.findLast((move) => move.at > action.at && move.at <= until);\n\n // Refs are rebound from subjects at replay; typed text is replaced by a caller input slot.\n return new Step({\n action: value._tag === \"Type\" ? { ...value, text: \"\" } : value,\n url: arrival?.url ?? action.url ?? before(until),\n subject: action.subject,\n to: action.to,\n box: point === undefined ? undefined : action.box,\n input:\n value._tag === \"Type\"\n ? slotFor(taken, action.subject?.name)\n : value._tag === \"Goto\" && value.url.includes(redacted)\n ? slotFor(taken, \"address\")\n : undefined,\n });\n }),\n });\n};\n","/** Find a recorded subject and verify where its point still lands before replay input. */\nimport { Clock, Duration, Effect, Schedule } from \"effect\";\n\nimport { InvalidRequest, undispatched } from \"../BrowserError.ts\";\nimport { type Box, type Subject } from \"../BrowserEvent.ts\";\nimport type { Page, Found, Point, Target } from \"../Page.ts\";\nimport { choose, Drifted } from \"./choose.ts\";\n\nconst invalid = (detail: string) => undispatched(\"replay\", new InvalidRequest({ detail }));\n\n/**\n * The one element on the page that a subject names, by role, name and context (see `Plan`),\n * looking again for two seconds while the page may still be drawing it.\n */\nexport const locate = (page: Page, subject: Subject) =>\n page\n .find({\n name: subject.name,\n scope: \"document\",\n ...(subject.role === null ? {} : { role: subject.role }),\n })\n .pipe(\n Effect.flatMap((found) => choose(subject, found)),\n Effect.retry({\n schedule: Schedule.spaced(Duration.millis(250)),\n times: 8,\n while: (error) => error._tag !== \"BrowserError\",\n }),\n Effect.provideService(Clock.Clock, page.clock),\n Effect.withSpan(\"Plan.locate\", { attributes: { role: subject.role ?? \"\" } }),\n );\n\n/**\n * Where the step acts: the element its subject names, or, for a step recorded at a point, the same\n * place within that element, as long as a press there reaches that element and not one over it.\n * An element out of view is first brought into it, by hovering it, as a press by ref would be.\n */\nexport const aim = (page: Page, subject: Subject | undefined, point?: Point, recorded?: Box) => {\n if (subject === undefined) return Effect.fail(invalid(\"the step names no element\"));\n if (point === undefined) return Effect.map(locate(page, subject), ({ ref }): Target => ref);\n\n const reach = ({ ref, box }: Found) => {\n const at =\n recorded === undefined || recorded.width <= 0 || recorded.height <= 0\n ? point\n : {\n x: box.x + ((point.x - recorded.x) / recorded.width) * box.width,\n y: box.y + ((point.y - recorded.y) / recorded.height) * box.height,\n };\n\n return Effect.map(page.find({ at }), ([reached]) => (reached?.ref === ref ? at : undefined));\n };\n\n const missed = new Drifted({ detail: \"a press at the subject's point reaches another element\" });\n\n return locate(page, subject).pipe(\n Effect.flatMap((found) =>\n Effect.flatMap(reach(found), (at) =>\n at !== undefined\n ? Effect.succeed<Target>(at)\n : page.hover(found.ref).pipe(\n Effect.andThen(locate(page, subject)),\n Effect.flatMap(reach),\n Effect.flatMap((again) =>\n again === undefined ? Effect.fail(missed) : Effect.succeed<Target>(again),\n ),\n ),\n ),\n ),\n );\n};\n","/** Replay and restore with durable read-back before repeating uncertain consequential input. */\nimport { Clock, Duration, Effect, Exit, Option, Schedule, Schema } from \"effect\";\n\nimport { type Action } from \"../Action.ts\";\nimport { type BrowserError, InvalidRequest, undispatched } from \"../BrowserError.ts\";\nimport type { Page, ReadyOptions, Target } from \"../Page.ts\";\nimport * as Stillness from \"../stillness/Stillness.ts\";\nimport { type Ambiguous, Drifted, type Missing } from \"./choose.ts\";\nimport { type Plan, Step, Receipt, Stopped, Uncertain, ReplayError } from \"./data.ts\";\nimport { aim, locate } from \"./targets.ts\";\n\nconst invalid = (detail: string) => undispatched(\"replay\", new InvalidRequest({ detail }));\n\nconst dispatch = (\n page: Page,\n step: Step,\n text: string,\n before: Effect.Effect<void, BrowserError>,\n): Effect.Effect<void, Missing | Ambiguous | Drifted | BrowserError> => {\n const action = step.action;\n const point = (target: Target) => (typeof target === \"object\" ? target : undefined);\n\n const resolved: Effect.Effect<Action, Missing | Ambiguous | Drifted | BrowserError> = Effect.gen(\n function* () {\n switch (action._tag) {\n case \"Goto\":\n return { ...action, url: step.input === undefined ? action.url : text };\n case \"Back\":\n case \"Reload\":\n return action;\n case \"Press\":\n return {\n ...action,\n options: {\n ...action.options,\n on: step.subject === undefined ? undefined : (yield* locate(page, step.subject)).ref,\n },\n };\n case \"Click\":\n case \"Hover\":\n return {\n ...action,\n target: yield* aim(page, step.subject, point(action.target), step.box),\n };\n case \"Drag\":\n return {\n ...action,\n from: yield* aim(page, step.subject, point(action.from)),\n to: yield* aim(page, step.to, point(action.to)),\n };\n case \"Select\":\n return {\n ...action,\n ref: (yield* locate(\n page,\n step.subject ?? (yield* invalid(\"a selection needs a subject\")),\n )).ref,\n };\n case \"Scroll\":\n return step.subject === undefined\n ? action\n : {\n ...action,\n options: {\n ...action.options,\n at: yield* aim(\n page,\n step.subject,\n action.options?.at === undefined ? undefined : point(action.options.at),\n step.box,\n ),\n },\n };\n case \"Type\":\n return {\n ...action,\n text: step.input === undefined ? action.text : text,\n options: {\n ...action.options,\n into:\n step.subject === undefined ? undefined : (yield* locate(page, step.subject)).ref,\n },\n };\n }\n },\n );\n\n return resolved.pipe(\n Effect.tap(() => before),\n Effect.flatMap(page.perform),\n Effect.asVoid,\n );\n};\n\nexport interface TakeOptions {\n /** How each step waits first, except an opening navigation, or false. No final-step wait. */\n readonly settle?: ReadyOptions | false | undefined;\n readonly inputs?: Readonly<Record<string, string>> | undefined;\n /**\n * Bound for recorded arrival and expected effect, each. Defaults to 5 seconds. Zero makes one\n * read without polling; that read retains the page operation's timeout.\n */\n readonly arrival?: Duration.Input | undefined;\n}\n\nexport interface ReplayOptions extends TakeOptions {\n readonly from?: number | Stopped | undefined;\n}\n\n/**\n * Input that can be repeated without repeating a commitment. `take` also validates a Checked\n * target's boolean state before input. Back/reload can resubmit a form.\n */\nexport const repeatable = (step: Step): boolean =>\n [\"Goto\", \"Hover\", \"Scroll\", \"Select\"].includes(step.action._tag) ||\n (step.action._tag === \"Type\" &&\n step.subject !== undefined &&\n step.action.options?.replace !== false &&\n step.action.options?.submit !== true) ||\n (step.action._tag === \"Click\" && step.expect?._tag === \"Checked\");\n\ntype StepError = Missing | Ambiguous | Drifted | BrowserError | Uncertain;\n\n// Zero waits make one read; positive waits bound all reads and never repeat input.\nconst within = (check: Effect.Effect<boolean, StepError>, millis: number) =>\n millis === 0\n ? check\n : check.pipe(\n Effect.repeat({ until: (held) => held, schedule: Schedule.spaced(Duration.millis(25)) }),\n Effect.timeoutOrElse({\n duration: Duration.millis(millis),\n orElse: () => Effect.succeed(false),\n }),\n );\n\nconst sameSite = (url: string, recorded: string) => {\n const origin = URL.parse(recorded)?.origin;\n\n return (\n recorded === \"\" ||\n (origin === undefined || origin === \"null\"\n ? url === recorded\n : URL.parse(url)?.origin === origin)\n );\n};\n\nconst arrived = (page: Page, urls: ReadonlyArray<string>, millis: number) =>\n within(\n Effect.map(page.url, (url) => urls.some((recorded) => sameSite(url, recorded))),\n millis,\n ).pipe(\n Effect.filterOrFail(\n (held) => held,\n () =>\n new Drifted({ detail: \"the page did not reach the recorded site within the arrival wait\" }),\n ),\n Effect.asVoid,\n );\n\nconst checkEffect = (\n page: Page,\n step: Step,\n first?: { readonly url: string; readonly document: number; readonly connection: string },\n millis = 0,\n) => {\n const expected = step.expect;\n\n if (expected === undefined) return Effect.succeed(false);\n switch (expected._tag) {\n case \"Checked\":\n return step.subject === undefined\n ? Effect.fail(invalid(\"a checked effect needs a subject\"))\n : Effect.flatMap(locate(page, step.subject), (found) =>\n found.state.checked === undefined\n ? Effect.fail(invalid(\"a checked effect needs a checkable subject\"))\n : Effect.succeed(found.state.checked === expected.checked),\n );\n case \"Navigated\":\n if (expected.url === undefined && first === undefined) return Effect.succeed(false);\n\n return Effect.map(page.state, (now) =>\n expected.url === undefined\n ? now.url !== first?.url ||\n (now.connection === first?.connection && now.document !== first?.document)\n : now.url === expected.url,\n );\n case \"Appeared\":\n case \"Gone\":\n return Effect.map(\n page.until(\n { ...expected.query, scope: \"document\" },\n expected._tag === \"Appeared\" ? \"some\" : \"none\",\n millis,\n ),\n ({ met }) => met,\n );\n }\n};\n\n/**\n * Take one step. Unknown non-repeatable input is never resent: only positive durable read-back\n * can skip it. An interrupted call remains interrupted; persist begun-before-call in the consumer\n * and treat a missing receipt as Stopped{input: \"unknown\"}, including after process restart.\n */\nexport const take = Effect.fn(\"Plan.take\")(function* (\n page: Page,\n plan: Plan,\n at: number | Stopped,\n options: TakeOptions = {},\n): Effect.fn.Return<Receipt, ReplayError> {\n const index = typeof at === \"number\" ? at : at.step;\n let input: Stopped[\"input\"] = typeof at === \"number\" ? \"unsent\" : at.input;\n\n const work = Effect.gen(function* (): Effect.fn.Return<Receipt, StepError> {\n const step = plan.steps[index];\n\n if (!Number.isInteger(index) || index < 0 || step === undefined)\n return yield* invalid(\"the step index is outside the plan\");\n if (!Schema.is(Step.fields.action)(step.action))\n return yield* invalid(\"the step action cannot be replayed\");\n const duration = Duration.fromInput(options.arrival ?? Duration.seconds(5));\n\n if (\n Option.isNone(duration) ||\n Duration.isNegative(duration.value) ||\n !Duration.isFinite(duration.value)\n )\n return yield* invalid(\"arrival must be a finite nonnegative duration\");\n const millis = Duration.toMillis(duration.value);\n const first = yield* page.state;\n\n const uncertain = new Uncertain({\n detail: \"the step may have been sent; reconcile its durable effect before continuing\",\n });\n\n const unresolved = input === \"unknown\" && !repeatable(step);\n const expected = step.expect;\n\n const durable =\n expected !== undefined &&\n (expected._tag === \"Appeared\" ||\n (expected._tag === \"Navigated\" && typeof expected.url === \"string\")) &&\n expected.durable === true;\n\n if (\n !durable &&\n (unresolved || (expected !== undefined && \"durable\" in expected && expected.durable === true))\n )\n return yield* uncertain;\n if (\n options.settle !== false &&\n (index > 0 || ![\"Goto\", \"Back\", \"Reload\"].includes(step.action._tag))\n )\n yield* options.settle?.quietMillis === undefined\n ? page.ready(options.settle)\n : Stillness.wait(page, {\n ...options.settle,\n still: \"content\",\n quietMillis: options.settle.quietMillis,\n });\n const before = plan.steps[index - 1]?.url;\n\n if (before !== undefined)\n yield* arrived(page, unresolved ? [before, step.url] : [before], millis);\n const check = checkEffect(page, step);\n\n const read =\n millis === 0\n ? check\n : check.pipe(\n Effect.timeoutOrElse({\n duration: Duration.millis(millis),\n orElse: () =>\n Effect.fail(new Drifted({ detail: \"the expected-effect read timed out\" })),\n }),\n );\n\n const held = yield* read.pipe(Effect.mapError((error) => (unresolved ? uncertain : error)));\n\n const receipt = (outcome: Receipt[\"outcome\"]) =>\n Effect.gen(function* () {\n yield* arrived(page, [step.url], millis);\n const now = yield* page.state;\n\n return new Receipt({ step: index, outcome, startedAt: first.at, at: now.at });\n });\n\n if (held) return yield* receipt(\"skipped\");\n if (unresolved) return yield* uncertain;\n const text = step.input === undefined ? \"\" : options.inputs?.[step.input];\n\n if (text === undefined) return yield* invalid(`no text for the input \"${step.input ?? \"\"}\"`);\n let baseline: Effect.Success<Page[\"state\"]> | undefined;\n\n const beforeDispatch = Effect.tap(page.state, (state) =>\n Effect.sync(() => {\n baseline = state;\n }),\n ).pipe(Effect.asVoid);\n\n const verify = Effect.suspend(() => within(checkEffect(page, step, baseline, millis), millis));\n\n const acted = yield* Effect.exit(dispatch(page, step, text, beforeDispatch));\n\n if (Exit.isFailure(acted)) {\n const error = Exit.findErrorOption(acted);\n\n if (Option.isSome(error) && error.value._tag === \"BrowserError\" && error.value.dispatched) {\n input = \"unknown\";\n if (expected !== undefined && (repeatable(step) || durable)) {\n const observed = yield* Effect.exit(verify);\n\n if (Exit.isSuccess(observed) && observed.value) return yield* receipt(\"verified\");\n }\n }\n\n return yield* Effect.failCause(acted.cause);\n }\n input = \"unknown\";\n if (expected !== undefined && !(yield* verify))\n return yield* new Drifted({ detail: \"the step's expected effect did not arrive\" });\n\n return yield* receipt(expected === undefined ? \"taken\" : \"verified\");\n });\n\n return yield* work.pipe(\n Effect.provideService(Clock.Clock, page.clock),\n Effect.mapError(\n (reason) =>\n new ReplayError({\n step: index,\n reason,\n input,\n receipts: [],\n }),\n ),\n );\n});\n\nconst run = Effect.fnUntraced(function* (\n page: Page,\n plan: Plan,\n options: TakeOptions,\n from: number | Stopped,\n until: number,\n restoring: boolean,\n) {\n const receipts: Array<Receipt> = [];\n const start = typeof from === \"number\" ? from : from.step;\n\n if (\n !Number.isInteger(start) ||\n start < 0 ||\n start > plan.steps.length ||\n !Number.isInteger(until) ||\n until < start ||\n until > plan.steps.length\n )\n return yield* new ReplayError({\n step: start,\n input: \"unsent\",\n receipts,\n reason: invalid(\"the run bounds are outside the plan\"),\n });\n // Fresh runs still ask for all input slots before changing the page. Restoration checks first.\n if (!restoring && typeof from === \"number\") {\n const unfilled = plan.steps.findIndex(\n (step, index) =>\n index >= start && step.input !== undefined && options.inputs?.[step.input] === undefined,\n );\n\n if (unfilled !== -1)\n return yield* new ReplayError({\n step: start,\n input: \"unsent\",\n receipts,\n reason: invalid(`no text for the input \"${plan.steps[unfilled]?.input ?? \"\"}\"`),\n });\n }\n for (let index = start; index < until; index++) {\n const at = restoring\n ? new Stopped({ step: index, input: \"unknown\" })\n : index === start\n ? from\n : index;\n\n const receipt = yield* take(page, plan, at, options).pipe(\n Effect.mapError((error) => new ReplayError({ ...error, receipts: [...receipts] })),\n );\n\n receipts.push(receipt);\n }\n\n return receipts;\n});\n\n/** Take a plan's steps from a fresh index or durable stopping point, returning completed receipts. */\nexport const replay = (page: Page, plan: Plan, options: ReplayOptions = {}) =>\n run(page, plan, options, options.from ?? 0, plan.steps.length, false).pipe(\n Effect.withSpan(\"Plan.replay\"),\n );\n\n/** Restore prior steps on a fresh page; unresolved commitments require positive durable evidence. */\nexport const restore = (\n page: Page,\n plan: Plan,\n options: TakeOptions & { readonly upTo?: number | undefined } = {},\n) =>\n run(page, plan, options, 0, options.upTo ?? plan.steps.length, true).pipe(\n Effect.withSpan(\"Plan.restore\"),\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAsBA,IAAa,UAAb,cAA6B,OAAO,YAAqB,C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