effect-browser 0.3.0-beta.20 → 0.3.0-beta.22

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 (243) hide show
  1. package/README.md +221 -158
  2. package/dist/Action-24sLOubi.d.mts +110 -0
  3. package/dist/Action.d.mts +2 -0
  4. package/dist/Action.mjs +141 -0
  5. package/dist/Action.mjs.map +1 -0
  6. package/dist/ActionPort.d.mts +15 -0
  7. package/dist/ActionPort.mjs +101 -0
  8. package/dist/ActionPort.mjs.map +1 -0
  9. package/dist/Browser-Cq2K1FEA.mjs +4075 -0
  10. package/dist/Browser-Cq2K1FEA.mjs.map +1 -0
  11. package/dist/Browser-wZhwZSlG.d.mts +167 -0
  12. package/dist/Browser.d.mts +2 -129
  13. package/dist/Browser.mjs +1 -1
  14. package/dist/{BrowserError-Coy7EW1N.d.mts → BrowserError-BlcmLVzn.d.mts} +22 -7
  15. package/dist/BrowserError.d.mts +2 -2
  16. package/dist/BrowserError.mjs +46 -9
  17. package/dist/BrowserError.mjs.map +1 -1
  18. package/dist/{BrowserEvent-dq6FRT8w.d.mts → BrowserEvent-lLqJ3GJS.d.mts} +93 -37
  19. package/dist/BrowserEvent.d.mts +2 -2
  20. package/dist/BrowserEvent.mjs +29 -24
  21. package/dist/BrowserEvent.mjs.map +1 -1
  22. package/dist/{Change-DqING3tr.d.mts → Change-Ba7INmay.d.mts} +4 -6
  23. package/dist/Change.d.mts +2 -2
  24. package/dist/Change.mjs +97 -2
  25. package/dist/Change.mjs.map +1 -0
  26. package/dist/Clock.d.mts +57 -0
  27. package/dist/Clock.mjs +80 -0
  28. package/dist/Clock.mjs.map +1 -0
  29. package/dist/{Frame-DkNdjjjr.d.mts → Frame-UEH2hO5T.d.mts} +10 -3
  30. package/dist/Frame.d.mts +2 -2
  31. package/dist/Frame.mjs +10 -2
  32. package/dist/Frame.mjs.map +1 -1
  33. package/dist/{Motion-DND6I-64.d.mts → Geometry-DJx9qrYy.d.mts} +7 -10
  34. package/dist/Geometry.d.mts +2 -0
  35. package/dist/Geometry.mjs +32 -0
  36. package/dist/Geometry.mjs.map +1 -0
  37. package/dist/LICENSE-jpeg-js +28 -0
  38. package/dist/Matching.d.mts +37 -0
  39. package/dist/{match.inpage-xOe9LNO0.mjs → Matching.mjs} +28 -4
  40. package/dist/Matching.mjs.map +1 -0
  41. package/dist/{Page-CfB6Zn1p.mjs → Page-BF5izr8R.mjs} +216 -31
  42. package/dist/Page-BF5izr8R.mjs.map +1 -0
  43. package/dist/{Page-ku6j5t-v.d.mts → Page-CvsOEorc.d.mts} +158 -185
  44. package/dist/Page.d.mts +2 -2
  45. package/dist/Page.mjs +1 -1
  46. package/dist/Released-tURbFmal.d.mts +15 -0
  47. package/dist/{Snapshot-B34hZ4Jl.d.mts → Snapshot-CtBVOtuu.d.mts} +6 -1
  48. package/dist/Snapshot.d.mts +1 -1
  49. package/dist/Snapshot.mjs.map +1 -1
  50. package/dist/Stillness-CNlvayIo.mjs +136 -0
  51. package/dist/Stillness-CNlvayIo.mjs.map +1 -0
  52. package/dist/Style-AO4V7Czt.mjs +357 -0
  53. package/dist/Style-AO4V7Czt.mjs.map +1 -0
  54. package/dist/Style.d.mts +72 -0
  55. package/dist/Style.mjs +2 -0
  56. package/dist/Url.d.mts +26 -0
  57. package/dist/Url.mjs +74 -0
  58. package/dist/Url.mjs.map +1 -0
  59. package/dist/Window-CMddGMt1.d.mts +34 -0
  60. package/dist/Window.d.mts +2 -0
  61. package/dist/Window.mjs +35 -0
  62. package/dist/Window.mjs.map +1 -0
  63. package/dist/connection-2KHI4_KN.d.mts +41 -0
  64. package/dist/connection-BTeO0Hiz.mjs +68 -0
  65. package/dist/connection-BTeO0Hiz.mjs.map +1 -0
  66. package/dist/index.d.mts +15 -17
  67. package/dist/index.mjs +11 -14
  68. package/dist/moment/Moment.d.mts +86 -0
  69. package/dist/{Moment.mjs → moment/Moment.mjs} +44 -38
  70. package/dist/moment/Moment.mjs.map +1 -0
  71. package/dist/{Plan-DJ4hEEna.d.mts → plan/index.d.mts} +169 -64
  72. package/dist/{Plan-C-d5QYS8.mjs → plan/index.mjs} +122 -155
  73. package/dist/plan/index.mjs.map +1 -0
  74. package/dist/{Policy.d.mts → policy/Policy.d.mts} +5 -9
  75. package/dist/{Policy.mjs → policy/Policy.mjs} +11 -21
  76. package/dist/policy/Policy.mjs.map +1 -0
  77. package/dist/presentation/Motion.d.mts +12 -0
  78. package/dist/{Motion.mjs → presentation/Motion.mjs} +4 -27
  79. package/dist/presentation/Motion.mjs.map +1 -0
  80. package/dist/presentation/Presentation.d.mts +30 -0
  81. package/dist/presentation/Presentation.mjs +105 -0
  82. package/dist/presentation/Presentation.mjs.map +1 -0
  83. package/dist/{Stage.d.mts → presentation/Stage.d.mts} +5 -8
  84. package/dist/{Stage.mjs → presentation/Stage.mjs} +68 -76
  85. package/dist/presentation/Stage.mjs.map +1 -0
  86. package/dist/presentation/feed.d.mts +20 -0
  87. package/dist/presentation/feed.mjs +18 -0
  88. package/dist/presentation/feed.mjs.map +1 -0
  89. package/dist/providers/Cdp.d.mts +9 -0
  90. package/dist/providers/Cdp.mjs +15 -0
  91. package/dist/providers/Cdp.mjs.map +1 -0
  92. package/dist/{Chromium.d.mts → providers/Chromium.d.mts} +6 -7
  93. package/dist/{Chromium.mjs → providers/Chromium.mjs} +7 -16
  94. package/dist/providers/Chromium.mjs.map +1 -0
  95. package/dist/providers/Released.d.mts +2 -0
  96. package/dist/providers/Released.mjs +12 -0
  97. package/dist/providers/Released.mjs.map +1 -0
  98. package/dist/stillness/Stillness.d.mts +12 -0
  99. package/dist/stillness/Stillness.mjs +2 -0
  100. package/dist/supervisor/Supervisor.d.mts +104 -0
  101. package/dist/supervisor/Supervisor.mjs +513 -0
  102. package/dist/supervisor/Supervisor.mjs.map +1 -0
  103. package/dist/testing/index.d.mts +337 -0
  104. package/dist/testing/index.mjs +515 -0
  105. package/dist/testing/index.mjs.map +1 -0
  106. package/dist/workerd/Cdp.d.mts +8 -0
  107. package/dist/workerd/Cdp.mjs +13 -0
  108. package/dist/workerd/Cdp.mjs.map +1 -0
  109. package/package.json +94 -33
  110. package/src/Action.ts +127 -0
  111. package/src/ActionPort.ts +128 -0
  112. package/src/Browser.ts +366 -225
  113. package/src/BrowserError.ts +63 -6
  114. package/src/BrowserEvent.ts +26 -25
  115. package/src/Change.ts +0 -2
  116. package/src/{internal/pictures/clock.ts → Clock.ts} +17 -6
  117. package/src/Frame.ts +14 -0
  118. package/src/Geometry.ts +48 -0
  119. package/src/{internal/reading/match.inpage.ts → Matching.ts} +34 -4
  120. package/src/Page.ts +111 -92
  121. package/src/Snapshot.ts +5 -0
  122. package/src/{internal/input/style.ts → Style.ts} +121 -14
  123. package/src/Window.ts +30 -0
  124. package/src/index.ts +8 -13
  125. package/src/internal/input/actions.ts +61 -119
  126. package/src/internal/input/dispatch.ts +3 -3
  127. package/src/internal/input/gate.ts +21 -18
  128. package/src/internal/input/guard.inpage.ts +25 -58
  129. package/src/internal/input/guard.ts +11 -20
  130. package/src/internal/input/keyboard.ts +12 -3
  131. package/src/internal/input/perform.ts +78 -60
  132. package/src/internal/input/pointer.ts +4 -2
  133. package/src/internal/input/settle.ts +7 -5
  134. package/src/internal/input/targets.inpage.ts +1 -1
  135. package/src/internal/input/targets.ts +4 -9
  136. package/src/internal/page/bridge.ts +210 -114
  137. package/src/internal/page/context.ts +23 -73
  138. package/src/internal/page/dialogs.ts +58 -0
  139. package/src/internal/page/identity.ts +6 -23
  140. package/src/internal/page/lane.ts +14 -15
  141. package/src/internal/page/navigation.ts +50 -42
  142. package/src/internal/page/openings.ts +11 -5
  143. package/src/internal/page/page.ts +44 -81
  144. package/src/internal/page/port.ts +125 -0
  145. package/src/internal/{input → page}/replies.ts +1 -1
  146. package/src/internal/page/request-owner.ts +269 -0
  147. package/src/internal/page/requests.ts +357 -0
  148. package/src/internal/page/scripts.ts +124 -0
  149. package/src/internal/pictures/capture.ts +255 -332
  150. package/src/internal/pictures/dimensions.ts +162 -0
  151. package/src/internal/pictures/frame.ts +68 -0
  152. package/src/internal/pictures/pictures.ts +57 -23
  153. package/src/internal/pictures/quiescence.ts +1 -1
  154. package/src/internal/pictures/state.ts +26 -0
  155. package/src/internal/pictures/transport.ts +21 -4
  156. package/src/internal/reading/controls.inpage.ts +5 -70
  157. package/src/internal/reading/expect.inpage.ts +13 -17
  158. package/src/internal/reading/names.inpage.ts +89 -45
  159. package/src/internal/reading/outline.inpage.ts +6 -7
  160. package/src/internal/reading/reading.ts +144 -176
  161. package/src/internal/reading/ready.inpage.ts +6 -17
  162. package/src/internal/reading/ready.ts +13 -135
  163. package/src/internal/reading/subjects.inpage.ts +83 -43
  164. package/src/internal/reading/walk.inpage.ts +33 -13
  165. package/src/internal/timeline/changes.ts +55 -6
  166. package/src/internal/timeline/events.ts +15 -5
  167. package/src/internal/timeline/history.inpage.ts +1 -1
  168. package/src/internal/timeline/record.inpage.ts +4 -1
  169. package/src/internal/timeline/window.ts +2 -1
  170. package/src/{Moment.ts → moment/Moment.ts} +13 -31
  171. package/src/{internal/timeline → moment}/words.ts +2 -2
  172. package/src/{internal/reading → plan}/choose.ts +3 -3
  173. package/src/plan/data.ts +117 -0
  174. package/src/plan/execute.ts +411 -0
  175. package/src/plan/index.ts +36 -0
  176. package/src/plan/record.ts +71 -0
  177. package/src/plan/targets.ts +71 -0
  178. package/src/{Policy.ts → policy/Policy.ts} +13 -10
  179. package/src/{Motion.ts → presentation/Motion.ts} +12 -46
  180. package/src/presentation/Presentation.ts +176 -0
  181. package/src/{Stage.ts → presentation/Stage.ts} +147 -112
  182. package/src/presentation/feed.ts +21 -0
  183. package/src/providers/Cdp.ts +16 -0
  184. package/src/{Chromium.ts → providers/Chromium.ts} +7 -10
  185. package/src/providers/Released.ts +13 -0
  186. package/src/providers/connection.ts +134 -0
  187. package/src/{internal/pictures/motion.ts → stillness/Pixels.ts} +4 -4
  188. package/src/stillness/Stillness.ts +166 -0
  189. package/src/supervisor/Supervisor.ts +170 -0
  190. package/src/supervisor/contract.ts +105 -0
  191. package/src/supervisor/lifecycle.ts +272 -0
  192. package/src/supervisor/runtime.ts +234 -0
  193. package/src/testing/TestBrowser.ts +115 -0
  194. package/src/testing/TestPage.ts +10 -0
  195. package/src/testing/evidence.ts +154 -0
  196. package/src/testing/index.ts +3 -0
  197. package/src/testing/model.ts +222 -0
  198. package/src/testing/page.ts +360 -0
  199. package/src/workerd/Cdp.ts +11 -0
  200. package/dist/Browser-BwCldIff.mjs +0 -629
  201. package/dist/Browser-BwCldIff.mjs.map +0 -1
  202. package/dist/Cdp.d.mts +0 -32
  203. package/dist/Cdp.mjs +0 -61
  204. package/dist/Cdp.mjs.map +0 -1
  205. package/dist/Change-DNvztNLu.mjs +0 -138
  206. package/dist/Change-DNvztNLu.mjs.map +0 -1
  207. package/dist/Chromium.mjs.map +0 -1
  208. package/dist/Expect.d.mts +0 -62
  209. package/dist/Expect.mjs +0 -114
  210. package/dist/Expect.mjs.map +0 -1
  211. package/dist/Moment.d.mts +0 -2
  212. package/dist/Moment.mjs.map +0 -1
  213. package/dist/Motion.d.mts +0 -2
  214. package/dist/Motion.mjs.map +0 -1
  215. package/dist/Page-CfB6Zn1p.mjs.map +0 -1
  216. package/dist/Plan-C-d5QYS8.mjs.map +0 -1
  217. package/dist/Plan.d.mts +0 -2
  218. package/dist/Plan.mjs +0 -2
  219. package/dist/Policy.mjs.map +0 -1
  220. package/dist/Presentation.d.mts +0 -48
  221. package/dist/Presentation.mjs +0 -118
  222. package/dist/Presentation.mjs.map +0 -1
  223. package/dist/Stage.mjs.map +0 -1
  224. package/dist/Supervisor-2mPjIYYs.mjs +0 -676
  225. package/dist/Supervisor-2mPjIYYs.mjs.map +0 -1
  226. package/dist/Supervisor-mVPeEUp8.d.mts +0 -317
  227. package/dist/Supervisor.d.mts +0 -2
  228. package/dist/Supervisor.mjs +0 -2
  229. package/dist/context-w3NJPRLo.mjs +0 -335
  230. package/dist/context-w3NJPRLo.mjs.map +0 -1
  231. package/dist/match.inpage-xOe9LNO0.mjs.map +0 -1
  232. package/dist/page-BKwfF6z-.mjs +0 -5099
  233. package/dist/page-BKwfF6z-.mjs.map +0 -1
  234. package/dist/url-Cd04Okid.mjs +0 -264
  235. package/dist/url-Cd04Okid.mjs.map +0 -1
  236. package/src/Cdp.ts +0 -101
  237. package/src/Expect.ts +0 -180
  238. package/src/Plan.ts +0 -674
  239. package/src/Presentation.ts +0 -196
  240. package/src/Supervisor.ts +0 -632
  241. package/src/internal/supervisor/lifecycle.ts +0 -484
  242. /package/src/{internal/page/url.ts → Url.ts} +0 -0
  243. /package/src/{internal/pictures → stillness}/utilsBundle.d.ts +0 -0
package/src/Plan.ts DELETED
@@ -1,674 +0,0 @@
1
- /**
2
- * A walk recorded once from a page's events and replayed later, on a fresh page, with no model
3
- * call.
4
- *
5
- * `fromEvents` keeps one page's completed actions with their subjects and the options they were
6
- * given, its navigations with both the address asked for and the one reached, and what was typed
7
- * as a named input slot, never the text itself. A navigation to an address whose credentials the
8
- * events withheld is an input slot too, so replay goes where the caller says, or nowhere, and
9
- * never to the address without them. `replay` takes the steps in turn. Before a step
10
- * except an opening navigate, back or reload, it waits for `Page.ready`; then it finds the element its
11
- * subject names, by role and name among those that repeat all its recorded context, and acts on
12
- * it. Text typed into focus was typed into the focused field, which replay finds the same way, and
13
- * text typed into a secret field goes into nothing else. An element step never falls back to
14
- * coordinates, and a step recorded at a point acts there only while the element found for it still
15
- * covers that point. `take` and `replay` return receipts; failure preserves a stopping point and
16
- * earlier receipts. Unknown consequential input is never resent. Only a positive durable read-back
17
- * can reconcile it; restoration follows the same rule. The consumer journals begun steps before
18
- * calling, treating interruption or a missing receipt as unknown. Plain recordings use version 1;
19
- * authored expected effects use version 2. Old 0.2 plans and unknown versions do not decode.
20
- *
21
- * @since 0.3.0
22
- */
23
- import { Duration, Effect, Exit, Option, Schedule, Schema } from "effect";
24
-
25
- import { BrowserError, InvalidRequest } from "./BrowserError.ts";
26
- import {
27
- type Action,
28
- ActionOptions,
29
- Box,
30
- type BrowserEvent,
31
- type Navigated,
32
- Subject,
33
- } from "./BrowserEvent.ts";
34
- import { undispatched } from "./internal/page/context.ts";
35
- import { Ambiguous, choose, Drifted, Missing } from "./internal/reading/choose.ts";
36
- import { Point as ViewportPoint } from "./Motion.ts";
37
- import {
38
- type Found,
39
- type Page,
40
- type Point,
41
- type ReadyOptions,
42
- redacted,
43
- type Target,
44
- } from "./Page.ts";
45
-
46
- export { Ambiguous, Drifted, Missing } from "./internal/reading/choose.ts";
47
-
48
- export const StepAction = Schema.Literals([
49
- "navigate",
50
- "back",
51
- "reload",
52
- "click",
53
- "hover",
54
- "drag",
55
- "type",
56
- "press",
57
- "scroll",
58
- "select",
59
- ]);
60
-
61
- export type StepAction = typeof StepAction.Type;
62
-
63
- const Query = Schema.Struct({
64
- role: Schema.optional(Schema.String),
65
- name: Schema.optional(Schema.String),
66
- text: Schema.optional(Schema.String),
67
- });
68
-
69
- /**
70
- * What a step leaves. `durable` asserts an author-chosen, lasting read-back of this operation,
71
- * such as its uniquely named saved receipt or exact operation URL. Only Appeared and an exact
72
- * Navigated URL allow it; a toast, absence or relative navigation cannot establish recovery.
73
- * Relative navigation measures observed change from dispatch, without asserting causality.
74
- */
75
- export const Expected = Schema.Union([
76
- Schema.TaggedStruct("Checked", { checked: Schema.Boolean }),
77
- Schema.TaggedStruct("Appeared", {
78
- query: Query,
79
- durable: Schema.optional(Schema.Literal(true)),
80
- }),
81
- Schema.TaggedStruct("Gone", {
82
- query: Query,
83
- durable: Schema.optional(Schema.Never),
84
- }),
85
- Schema.TaggedStruct("Navigated", {
86
- url: Schema.String,
87
- durable: Schema.optional(Schema.Literal(true)),
88
- }),
89
- Schema.TaggedStruct("Navigated", {
90
- url: Schema.optional(Schema.Never),
91
- durable: Schema.optional(Schema.Never),
92
- }),
93
- ]);
94
-
95
- export type Expected = typeof Expected.Type;
96
-
97
- /** One recorded step: the action, what it acted on, and what else it was asked. */
98
- export class Step extends Schema.Class<Step>("effect-browser/Plan/Step")({
99
- action: StepAction,
100
- /**
101
- * The ending address, or a later recorded navigation before the next action began. Empty when
102
- * unknown; a delayed navigation can be stronger arrival evidence than the action's ending URL.
103
- */
104
- url: Schema.String,
105
- /** A navigation's requested address, or the keys a press pressed. */
106
- target: Schema.optional(Schema.String),
107
- subject: Schema.optional(Subject),
108
- /** Where a drag ended. */
109
- to: Schema.optional(Subject),
110
- /** The viewport point a step aimed at, when it aimed at a point, and a drag's end point. */
111
- point: Schema.optional(ViewportPoint),
112
- toPoint: Schema.optional(ViewportPoint),
113
- /** The box of what a step aimed at by point found there, so replay aims at the same place in it. */
114
- box: Schema.optional(Box),
115
- /**
116
- * The input slot whose text a `type` step types, or whose address a `navigate` step goes to, as
117
- * its recorded address had a credential withheld.
118
- */
119
- input: Schema.optional(Schema.String),
120
- /** The slot's text went into a secret field, so replay types it into nothing else. */
121
- secret: Schema.optional(Schema.Literal(true)),
122
- options: Schema.optional(ActionOptions),
123
- expect: Schema.optional(Expected),
124
- }) {}
125
-
126
- const PlanData = Schema.Struct({
127
- version: Schema.Literals([1, 2]),
128
- steps: Schema.Array(Step),
129
- }).check(
130
- Schema.makeFilter((plan) =>
131
- plan.version === (plan.steps.some((step) => step.expect !== undefined) ? 2 : 1)
132
- ? undefined
133
- : "only plans with expected effects use version 2",
134
- ),
135
- );
136
-
137
- export class Plan extends Schema.Class<Plan>("effect-browser/Plan")(PlanData) {
138
- /** Choose the encoding version from the steps; simple recordings remain version 1. */
139
- static new(steps: ReadonlyArray<Step>): Plan {
140
- return new Plan({ version: steps.some((step) => step.expect !== undefined) ? 2 : 1, steps });
141
- }
142
-
143
- /** The input slots its steps type, in order; replay needs text for each. */
144
- get inputs(): ReadonlyArray<string> {
145
- return this.steps.flatMap((step) => (step.input === undefined ? [] : [step.input]));
146
- }
147
- }
148
-
149
- /** One completed step, on the page's host clock. `verified` means its expected effect was seen. */
150
- export class Receipt extends Schema.Class<Receipt>("effect-browser/Plan/Receipt")({
151
- step: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
152
- outcome: Schema.Literals(["taken", "verified", "skipped"]),
153
- startedAt: Schema.Finite,
154
- at: Schema.Finite,
155
- }) {}
156
-
157
- /** Durable stopping data. A begun step without a receipt must be restored as `unknown`. */
158
- export class Stopped extends Schema.Class<Stopped>("effect-browser/Plan/Stopped")({
159
- step: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
160
- input: Schema.Literals(["unsent", "unknown"]),
161
- }) {}
162
-
163
- /** Repeating this step could repeat an unresolved effect; the consumer must reconcile it. */
164
- export class Uncertain extends Schema.TaggedError<Uncertain>()("Uncertain", {
165
- detail: Schema.String,
166
- }) {
167
- override get message() {
168
- return this.detail;
169
- }
170
- }
171
-
172
- /** Where replay stopped, counting steps from 0, why, and the steps that completed before it. */
173
- export class ReplayError extends Schema.TaggedError<ReplayError>()("ReplayError", {
174
- step: Schema.Int,
175
- reason: Schema.Union([Missing, Ambiguous, Drifted, BrowserError, Uncertain]),
176
- input: Schema.Literals(["unsent", "unknown"]),
177
- receipts: Schema.Array(Receipt),
178
- }) {
179
- get stopped(): Stopped {
180
- return new Stopped({ step: this.step, input: this.input });
181
- }
182
-
183
- override get message() {
184
- return `step ${this.step} failed: ${this.reason.message}`;
185
- }
186
- }
187
-
188
- const isStep = (event: BrowserEvent): event is Action & { readonly name: StepAction } =>
189
- event._tag === "Action" &&
190
- event.ok &&
191
- (StepAction.literals as ReadonlyArray<string>).includes(event.name);
192
-
193
- // A point target reads `x,y`, as `{"x":…,"y":…}` inside a drag's; a ref reads like e12.
194
- const pointIn = (target: string | undefined): Point | undefined => {
195
- const parsed = /^\{?(?:"x":)?(-?[\d.]+),(?:"y":)?(-?[\d.]+)\}?$/.exec(target ?? "");
196
-
197
- return parsed === null ? undefined : { x: Number(parsed[1]), y: Number(parsed[2]) };
198
- };
199
-
200
- /** A slot named for the field it fills, such as `email`, unique within the plan. */
201
- const slotFor = (taken: Set<string>, field: string | undefined) => {
202
- const base =
203
- field
204
- ?.toLowerCase()
205
- .match(/[\p{L}\p{N}]+/gu)
206
- ?.join("-") ?? "input";
207
-
208
- let slot = base;
209
-
210
- for (let count = 2; taken.has(slot); count++) slot = `${base}-${count}`;
211
- taken.add(slot);
212
-
213
- return slot;
214
- };
215
-
216
- /**
217
- * The walk one page's events record: the completed actions of the page that acted first, in
218
- * order. `page.recentEvents` gives them, or `browser.events()` read until the walk ends.
219
- */
220
- export const fromEvents = (events: Iterable<BrowserEvent>): Plan => {
221
- const all = Array.from(events);
222
- const page = all.find((event) => event._tag === "Action")?.page;
223
- const mine = all.filter((event) => "page" in event && event.page === page);
224
- const steps = mine.filter(isStep);
225
- const opened = mine.find((event) => event._tag === "PageOpened")?.url ?? "";
226
- const moves = mine.filter((event): event is Navigated => event._tag === "Navigated");
227
- const taken = new Set<string>();
228
-
229
- // Where the page was just before a time: the last address it reached by then.
230
- const before = (time: number) => moves.findLast((move) => move.at <= time)?.url ?? opened;
231
-
232
- return new Plan({
233
- version: 1,
234
- steps: steps.map((action, index) => {
235
- const drag = action.name === "drag" ? (action.target ?? "").split(" -> ") : undefined;
236
- const point = pointIn(drag === undefined ? action.target : drag[0]);
237
- const until = steps[index + 1]?.startedAt ?? Number.POSITIVE_INFINITY;
238
- const arrival = moves.findLast((move) => move.at > action.at && move.at <= until);
239
-
240
- // Only a navigation and a press keep their target: an address, or keys.
241
- return new Step({
242
- action: action.name,
243
- url: arrival?.url ?? action.url ?? before(until),
244
- target: action.name === "navigate" || action.name === "press" ? action.target : undefined,
245
- subject: action.subject,
246
- to: action.to,
247
- point,
248
- toPoint: pointIn(drag?.[1]),
249
- box: point === undefined ? undefined : action.box,
250
- input:
251
- action.name === "type"
252
- ? slotFor(taken, action.subject?.name)
253
- : action.name === "navigate" && action.target?.includes(redacted) === true
254
- ? slotFor(taken, "address")
255
- : undefined,
256
- secret: action.name === "type" && action.text === redacted ? true : undefined,
257
- options: action.options,
258
- });
259
- }),
260
- });
261
- };
262
-
263
- /**
264
- * The one element on the page that a subject names, by role, name and context (see `Plan`),
265
- * looking again for two seconds while the page may still be drawing it.
266
- */
267
- export const locate = (page: Page, subject: Subject) =>
268
- page
269
- .find({
270
- name: subject.name,
271
- scope: "document",
272
- ...(subject.role === null ? {} : { role: subject.role }),
273
- })
274
- .pipe(
275
- Effect.flatMap((found) => choose(subject, found)),
276
- Effect.retry({
277
- schedule: Schedule.spaced(Duration.millis(250)),
278
- times: 8,
279
- while: (error) => error._tag !== "BrowserError",
280
- }),
281
- Effect.withSpan("Plan.locate", { attributes: { role: subject.role ?? "" } }),
282
- );
283
-
284
- const invalid = (detail: string) => undispatched("replay", new InvalidRequest({ detail }));
285
-
286
- /**
287
- * Where the step acts: the element its subject names, or, for a step recorded at a point, the same
288
- * place within that element, as long as a press there reaches that element and not one over it.
289
- * An element out of view is first brought into it, by hovering it, as a press by ref would be.
290
- */
291
- const aim = (page: Page, subject: Subject | undefined, point?: Point, recorded?: Box) => {
292
- if (subject === undefined) return Effect.fail(invalid("the step names no element"));
293
- if (point === undefined) return Effect.map(locate(page, subject), ({ ref }): Target => ref);
294
-
295
- const reach = ({ ref, box }: Found) => {
296
- const at =
297
- recorded === undefined || recorded.width <= 0 || recorded.height <= 0
298
- ? point
299
- : {
300
- x: box.x + ((point.x - recorded.x) / recorded.width) * box.width,
301
- y: box.y + ((point.y - recorded.y) / recorded.height) * box.height,
302
- };
303
-
304
- return Effect.map(page.find({ at }), ([reached]) => (reached?.ref === ref ? at : undefined));
305
- };
306
-
307
- const missed = new Drifted({ detail: "a press at the subject's point reaches another element" });
308
-
309
- return locate(page, subject).pipe(
310
- Effect.flatMap((found) =>
311
- Effect.flatMap(reach(found), (at) =>
312
- at !== undefined
313
- ? Effect.succeed<Target>(at)
314
- : page.hover(found.ref).pipe(
315
- Effect.andThen(locate(page, subject)),
316
- Effect.flatMap(reach),
317
- Effect.flatMap((again) =>
318
- again === undefined ? Effect.fail(missed) : Effect.succeed<Target>(again),
319
- ),
320
- ),
321
- ),
322
- ),
323
- );
324
- };
325
-
326
- const dispatch = (
327
- page: Page,
328
- step: Step,
329
- text: string,
330
- ): Effect.Effect<void, Missing | Ambiguous | Drifted | BrowserError> => {
331
- const options = step.options ?? {};
332
-
333
- switch (step.action) {
334
- case "navigate":
335
- return page.goto(step.input === undefined ? (step.target ?? step.url) : text);
336
- case "back":
337
- return page.back;
338
- case "reload":
339
- return page.reload;
340
- case "press":
341
- return step.subject === undefined
342
- ? page.press(step.target ?? "", options)
343
- : Effect.flatMap(locate(page, step.subject), ({ ref }) =>
344
- page.press(step.target ?? "", { ...options, on: ref }),
345
- );
346
- case "click":
347
- return aim(page, step.subject, step.point, step.box).pipe(
348
- Effect.flatMap((at) => page.click(at, options)),
349
- Effect.asVoid,
350
- );
351
- case "hover":
352
- return Effect.flatMap(aim(page, step.subject, step.point, step.box), page.hover);
353
- case "drag":
354
- return Effect.all([
355
- aim(page, step.subject, step.point),
356
- aim(page, step.to, step.toPoint),
357
- ]).pipe(Effect.flatMap(([from, to]) => page.drag(from, to)));
358
- case "select":
359
- return aim(page, step.subject).pipe(
360
- Effect.flatMap((at) => page.select(typeof at === "string" ? at : "", options.values ?? [])),
361
- Effect.asVoid,
362
- );
363
- // A scroll or a typing step may name no element: the page, or whatever has focus.
364
- case "scroll":
365
- return step.subject === undefined
366
- ? page.scroll(options)
367
- : Effect.flatMap(aim(page, step.subject, step.point, step.box), (at) =>
368
- page.scroll({ ...options, at }),
369
- );
370
- case "type":
371
- return step.subject === undefined
372
- ? page.type(text, { ...options, secret: step.secret })
373
- : Effect.flatMap(aim(page, step.subject), (into) =>
374
- page.type(text, {
375
- ...options,
376
- into: typeof into === "string" ? into : undefined,
377
- secret: step.secret,
378
- }),
379
- );
380
- }
381
- };
382
-
383
- export interface TakeOptions {
384
- /** How each step waits first, except an opening navigation, or false. No final-step wait. */
385
- readonly settle?: ReadyOptions | false | undefined;
386
- readonly inputs?: Readonly<Record<string, string>> | undefined;
387
- /**
388
- * Bound for recorded arrival and expected effect, each. Defaults to 5 seconds. Zero makes one
389
- * read without polling; that read retains the page operation's timeout.
390
- */
391
- readonly arrival?: Duration.Input | undefined;
392
- }
393
-
394
- export interface ReplayOptions extends TakeOptions {
395
- readonly from?: number | Stopped | undefined;
396
- }
397
-
398
- /**
399
- * Input that can be repeated without repeating a commitment. `take` also validates a Checked
400
- * target's boolean state before input. Back/reload can resubmit a form.
401
- */
402
- export const repeatable = (step: Step): boolean =>
403
- ["navigate", "hover", "scroll", "select"].includes(step.action) ||
404
- (step.action === "type" &&
405
- step.subject !== undefined &&
406
- step.options?.replace !== false &&
407
- step.options?.submit !== true) ||
408
- (step.action === "click" && step.expect?._tag === "Checked");
409
-
410
- type StepError = Missing | Ambiguous | Drifted | BrowserError | Uncertain;
411
-
412
- // Zero waits make one read; positive waits bound all reads and never repeat input.
413
- const within = (check: Effect.Effect<boolean, StepError>, millis: number) =>
414
- millis === 0
415
- ? check
416
- : check.pipe(
417
- Effect.repeat({ until: (held) => held, schedule: Schedule.spaced(Duration.millis(25)) }),
418
- Effect.timeoutOrElse({
419
- duration: Duration.millis(millis),
420
- orElse: () => Effect.succeed(false),
421
- }),
422
- );
423
-
424
- const sameSite = (url: string, recorded: string) => {
425
- const origin = URL.parse(recorded)?.origin;
426
-
427
- return (
428
- recorded === "" ||
429
- (origin === undefined || origin === "null"
430
- ? url === recorded
431
- : URL.parse(url)?.origin === origin)
432
- );
433
- };
434
-
435
- const arrived = (page: Page, urls: ReadonlyArray<string>, millis: number) =>
436
- within(
437
- Effect.map(page.url, (url) => urls.some((recorded) => sameSite(url, recorded))),
438
- millis,
439
- ).pipe(
440
- Effect.filterOrFail(
441
- (held) => held,
442
- () =>
443
- new Drifted({ detail: "the page did not reach the recorded site within the arrival wait" }),
444
- ),
445
- Effect.asVoid,
446
- );
447
-
448
- const checkEffect = (
449
- page: Page,
450
- step: Step,
451
- first?: { readonly url: string; readonly document: number },
452
- ) => {
453
- const expected = step.expect;
454
-
455
- if (expected === undefined) return Effect.succeed(false);
456
- switch (expected._tag) {
457
- case "Checked":
458
- return step.subject === undefined
459
- ? Effect.fail(invalid("a checked effect needs a subject"))
460
- : Effect.flatMap(locate(page, step.subject), (found) =>
461
- found.state.checked === undefined
462
- ? Effect.fail(invalid("a checked effect needs a checkable subject"))
463
- : Effect.succeed(found.state.checked === expected.checked),
464
- );
465
- case "Navigated":
466
- if (expected.url === undefined && first === undefined) return Effect.succeed(false);
467
-
468
- return Effect.map(page.state, (now) =>
469
- expected.url === undefined
470
- ? now.url !== first?.url || now.document !== first?.document
471
- : now.url === expected.url,
472
- );
473
- case "Appeared":
474
- case "Gone":
475
- return Effect.map(page.find({ ...expected.query, scope: "document" }), (found) =>
476
- expected._tag === "Appeared" ? found.length > 0 : found.length === 0,
477
- );
478
- }
479
- };
480
-
481
- /**
482
- * Take one step. Unknown non-repeatable input is never resent: only positive durable read-back
483
- * can skip it. An interrupted call remains interrupted; persist begun-before-call in the consumer
484
- * and treat a missing receipt as Stopped{input: "unknown"}, including after process restart.
485
- */
486
- export const take = Effect.fn("Plan.take")(function* (
487
- page: Page,
488
- plan: Plan,
489
- at: number | Stopped,
490
- options: TakeOptions = {},
491
- ): Effect.fn.Return<Receipt, ReplayError> {
492
- const index = typeof at === "number" ? at : at.step;
493
- let input: Stopped["input"] = typeof at === "number" ? "unsent" : at.input;
494
-
495
- const work = Effect.gen(function* (): Effect.fn.Return<Receipt, StepError> {
496
- const step = plan.steps[index];
497
-
498
- if (!Number.isInteger(index) || index < 0 || step === undefined)
499
- return yield* invalid("the step index is outside the plan");
500
- const duration = Duration.fromInput(options.arrival ?? Duration.seconds(5));
501
-
502
- if (
503
- Option.isNone(duration) ||
504
- Duration.isNegative(duration.value) ||
505
- !Duration.isFinite(duration.value)
506
- )
507
- return yield* invalid("arrival must be a finite nonnegative duration");
508
- const millis = Duration.toMillis(duration.value);
509
- const first = yield* page.state;
510
-
511
- const uncertain = new Uncertain({
512
- detail: "the step may have been sent; reconcile its durable effect before continuing",
513
- });
514
-
515
- const unresolved = input === "unknown" && !repeatable(step);
516
- const expected = step.expect;
517
-
518
- const durable =
519
- expected !== undefined &&
520
- (expected._tag === "Appeared" ||
521
- (expected._tag === "Navigated" && typeof expected.url === "string")) &&
522
- expected.durable === true;
523
-
524
- if (
525
- !durable &&
526
- (unresolved || (expected !== undefined && "durable" in expected && expected.durable === true))
527
- )
528
- return yield* uncertain;
529
- if (
530
- options.settle !== false &&
531
- (index > 0 || !["navigate", "back", "reload"].includes(step.action))
532
- )
533
- yield* page.ready(options.settle);
534
- const before = plan.steps[index - 1]?.url;
535
-
536
- if (before !== undefined)
537
- yield* arrived(page, unresolved ? [before, step.url] : [before], millis);
538
- const check = checkEffect(page, step);
539
-
540
- const read =
541
- millis === 0
542
- ? check
543
- : check.pipe(
544
- Effect.timeoutOrElse({
545
- duration: Duration.millis(millis),
546
- orElse: () =>
547
- Effect.fail(new Drifted({ detail: "the expected-effect read timed out" })),
548
- }),
549
- );
550
-
551
- const held = yield* read.pipe(Effect.mapError((error) => (unresolved ? uncertain : error)));
552
-
553
- const receipt = (outcome: Receipt["outcome"]) =>
554
- Effect.gen(function* () {
555
- yield* arrived(page, [step.url], millis);
556
- const now = yield* page.state;
557
-
558
- return new Receipt({ step: index, outcome, startedAt: first.at, at: now.at });
559
- });
560
-
561
- if (held) return yield* receipt("skipped");
562
- if (unresolved) return yield* uncertain;
563
- const text = step.input === undefined ? "" : options.inputs?.[step.input];
564
-
565
- if (text === undefined) return yield* invalid(`no text for the input "${step.input ?? ""}"`);
566
- const verify = checkEffect(page, step, yield* page.state);
567
- const acted = yield* Effect.exit(dispatch(page, step, text));
568
-
569
- if (Exit.isFailure(acted)) {
570
- const error = Exit.findErrorOption(acted);
571
-
572
- if (Option.isSome(error) && error.value._tag === "BrowserError" && error.value.dispatched) {
573
- input = "unknown";
574
- if (expected !== undefined && (repeatable(step) || durable)) {
575
- const observed = yield* Effect.exit(within(verify, millis));
576
-
577
- if (Exit.isSuccess(observed) && observed.value) return yield* receipt("verified");
578
- }
579
- }
580
-
581
- return yield* Effect.failCause(acted.cause);
582
- }
583
- input = "unknown";
584
- if (expected !== undefined && !(yield* within(verify, millis)))
585
- return yield* new Drifted({ detail: "the step's expected effect did not arrive" });
586
-
587
- return yield* receipt(expected === undefined ? "taken" : "verified");
588
- });
589
-
590
- return yield* work.pipe(
591
- Effect.mapError(
592
- (reason) =>
593
- new ReplayError({
594
- step: index,
595
- reason,
596
- input,
597
- receipts: [],
598
- }),
599
- ),
600
- );
601
- });
602
-
603
- const run = Effect.fnUntraced(function* (
604
- page: Page,
605
- plan: Plan,
606
- options: TakeOptions,
607
- from: number | Stopped,
608
- until: number,
609
- restoring: boolean,
610
- ) {
611
- const receipts: Array<Receipt> = [];
612
- const start = typeof from === "number" ? from : from.step;
613
-
614
- if (
615
- !Number.isInteger(start) ||
616
- start < 0 ||
617
- start > plan.steps.length ||
618
- !Number.isInteger(until) ||
619
- until < start ||
620
- until > plan.steps.length
621
- )
622
- return yield* new ReplayError({
623
- step: start,
624
- input: "unsent",
625
- receipts,
626
- reason: invalid("the run bounds are outside the plan"),
627
- });
628
- // Fresh runs still ask for all input slots before changing the page. Restoration checks first.
629
- if (!restoring && typeof from === "number") {
630
- const unfilled = plan.steps.findIndex(
631
- (step, index) =>
632
- index >= start && step.input !== undefined && options.inputs?.[step.input] === undefined,
633
- );
634
-
635
- if (unfilled !== -1)
636
- return yield* new ReplayError({
637
- step: start,
638
- input: "unsent",
639
- receipts,
640
- reason: invalid(`no text for the input "${plan.steps[unfilled]?.input ?? ""}"`),
641
- });
642
- }
643
- for (let index = start; index < until; index++) {
644
- const at = restoring
645
- ? new Stopped({ step: index, input: "unknown" })
646
- : index === start
647
- ? from
648
- : index;
649
-
650
- const receipt = yield* take(page, plan, at, options).pipe(
651
- Effect.mapError((error) => new ReplayError({ ...error, receipts: [...receipts] })),
652
- );
653
-
654
- receipts.push(receipt);
655
- }
656
-
657
- return receipts;
658
- });
659
-
660
- /** Take a plan's steps from a fresh index or durable stopping point, returning completed receipts. */
661
- export const replay = (page: Page, plan: Plan, options: ReplayOptions = {}) =>
662
- run(page, plan, options, options.from ?? 0, plan.steps.length, false).pipe(
663
- Effect.withSpan("Plan.replay"),
664
- );
665
-
666
- /** Restore prior steps on a fresh page; unresolved commitments require positive durable evidence. */
667
- export const restore = (
668
- page: Page,
669
- plan: Plan,
670
- options: TakeOptions & { readonly upTo?: number | undefined } = {},
671
- ) =>
672
- run(page, plan, options, 0, options.upTo ?? plan.steps.length, true).pipe(
673
- Effect.withSpan("Plan.restore"),
674
- );