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/Browser.ts CHANGED
@@ -16,6 +16,7 @@ import {
16
16
  Duration,
17
17
  Effect,
18
18
  Exit,
19
+ FiberSet,
19
20
  Option,
20
21
  Queue,
21
22
  Schema,
@@ -23,30 +24,30 @@ import {
23
24
  Semaphore,
24
25
  type Stream,
25
26
  } from "effect";
26
- import type { BrowserContext, Dialog, Page as PlaywrightPage } from "playwright-core";
27
+ import type { BrowserContext, Page as PlaywrightPage } from "playwright-core";
27
28
 
28
- import { type BrowserError, Failed, InvalidRequest, Limit } from "./BrowserError.ts";
29
29
  import {
30
- type BrowserEvent,
31
- DialogShown,
32
- Disconnected,
33
- type DisconnectCause,
34
- PageClosed,
35
- PageOpened,
36
- PageUntracked,
37
- type RecordedEvent,
38
- SessionEnding,
39
- } from "./BrowserEvent.ts";
30
+ type BrowserError,
31
+ Closed,
32
+ Failed,
33
+ InvalidRequest,
34
+ Limit,
35
+ Timeout,
36
+ } from "./BrowserError.ts";
37
+ import * as Events from "./BrowserEvent.ts";
38
+ import * as BrowserClock from "./Clock.ts";
40
39
  import * as Gate from "./internal/input/gate.ts";
41
40
  import { call, failWith, type Settings, undispatched } from "./internal/page/context.ts";
41
+ import { listen } from "./internal/page/dialogs.ts";
42
42
  import * as Identity from "./internal/page/identity.ts";
43
43
  import { FailFast } from "./internal/page/lane.ts";
44
44
  import * as Openings from "./internal/page/openings.ts";
45
45
  import * as PageImpl from "./internal/page/page.ts";
46
- import * as Url from "./internal/page/url.ts";
47
- import * as BrowserClock from "./internal/pictures/clock.ts";
46
+ import * as Port from "./internal/page/port.ts";
47
+ import * as Requests from "./internal/page/requests.ts";
48
48
  import * as Timeline from "./internal/timeline/events.ts";
49
49
  import type * as Page from "./Page.ts";
50
+ import * as Url from "./Url.ts";
50
51
 
51
52
  /** A script that documents run before their own, such as a consent-banner remover. */
52
53
  export interface InitScript {
@@ -59,7 +60,39 @@ export interface InitScript {
59
60
  readonly source: string;
60
61
  }
61
62
 
63
+ /** Consumer-owned decision for one request caught by a narrow URL pattern. */
64
+ export type RequestDecision =
65
+ | { readonly _tag: "Allowed" }
66
+ | { readonly _tag: "Refused"; readonly reason: string }
67
+ | {
68
+ readonly _tag: "Fulfilled";
69
+ readonly status: number;
70
+ readonly contentType: string;
71
+ readonly headers?: Readonly<Record<string, string>> | undefined;
72
+ readonly body: string;
73
+ };
74
+
75
+ export interface RequestPolicy {
76
+ readonly patterns: ReadonlyArray<string>;
77
+ /**
78
+ * Receives sensitive data for this context only; keep it out of model inputs and logs.
79
+ * Body is exact UTF-8 text, or null when absent. Incomplete/binary body evidence refuses
80
+ * that request. Preexisting shared workers make installation fail InvalidRequest.
81
+ * Enforcement belongs to this connection's scope; it is not a firewall after CDP disconnects.
82
+ */
83
+ readonly decide: (request: {
84
+ readonly url: string;
85
+ readonly method: string;
86
+ readonly body: string | null;
87
+ }) => Effect.Effect<RequestDecision, BrowserError>;
88
+ readonly timeout?: Duration.Input | undefined;
89
+ }
90
+
62
91
  export interface Options {
92
+ /** Fixed viewport applied before each existing or newly opened page registers. */
93
+ readonly viewport?: { readonly width: number; readonly height: number } | undefined;
94
+ /** This context's policy, installed before pages register; redirects retain ownership. */
95
+ readonly requests?: RequestPolicy | undefined;
63
96
  /**
64
97
  * Bound on each action; finite and positive. Defaults to 10 seconds. What a presenter's view
65
98
  * takes to show an action, such as its glides and typing at a person's pace, does not count
@@ -154,8 +187,6 @@ export interface Service {
154
187
  readonly suspend: (
155
188
  options?: SuspendOptions,
156
189
  ) => Effect.Effect<Suspension, BrowserError, Scope.Scope>;
157
- /** The Playwright context, for anything this API does not cover. Never give it to a model. */
158
- readonly context: BrowserContext;
159
190
  /** Open pages in the order this browser began tracking them. */
160
191
  readonly pages: Effect.Effect<ReadonlyArray<Page.Page>>;
161
192
  /** The open page with this id, its CDP target id, as stored before a reconnect. */
@@ -163,15 +194,20 @@ export interface Service {
163
194
  /** The first open page, opening one when there is none. */
164
195
  readonly firstPage: Effect.Effect<Page.Page, BrowserError>;
165
196
  readonly newPage: (url?: string) => Effect.Effect<Page.Page, BrowserError>;
197
+ /** Whether an applicable cookie exists; its value never leaves the browser owner. */
198
+ readonly hasCookie: (query: {
199
+ readonly name: string;
200
+ readonly url: string;
201
+ }) => Effect.Effect<boolean, BrowserError>;
166
202
  /**
167
203
  * Completes once the browser is lost to its owner, with why: its connection dropped, its
168
204
  * provider ended its session, or its owner's scope released it.
169
205
  */
170
- readonly disconnected: Effect.Effect<DisconnectCause>;
206
+ readonly disconnected: Effect.Effect<Events.DisconnectCause>;
171
207
  /** Live events, or replay after a cursor. A reader that falls behind fails with EventHistoryExpired. */
172
- readonly events: (options?: EventOptions) => Stream.Stream<RecordedEvent, BrowserError>;
208
+ readonly events: (options?: EventOptions) => Stream.Stream<Events.RecordedEvent, BrowserError>;
173
209
  /** The latest `eventHistory` events, oldest first. */
174
- readonly recentEvents: Effect.Effect<ReadonlyArray<BrowserEvent>>;
210
+ readonly recentEvents: Effect.Effect<ReadonlyArray<Events.BrowserEvent>>;
175
211
  }
176
212
 
177
213
  export class Browser extends Context.Service<Browser, Service>()("effect-browser/Browser") {}
@@ -203,6 +239,13 @@ const settingsOf = Effect.fnUntraced(function* (options: Options) {
203
239
  policyTimeout: yield* bound("policyTimeout", options.policyTimeout, Duration.minutes(5)),
204
240
  };
205
241
 
242
+ if (
243
+ options.viewport !== undefined &&
244
+ ![options.viewport.width, options.viewport.height].every(
245
+ (size) => Number.isSafeInteger(size) && size > 0,
246
+ )
247
+ )
248
+ return yield* invalid("viewport dimensions must be positive safe integers");
206
249
  const eventHistory = options.eventHistory ?? 4096;
207
250
  const { maxPages } = options;
208
251
 
@@ -230,14 +273,14 @@ const watchLoss = Effect.fnUntraced(function* (
230
273
  context: BrowserContext,
231
274
  expiresAt: DateTime.Utc | undefined,
232
275
  clock: Clock.Clock,
233
- disconnected: (cause: DisconnectCause) => void,
276
+ disconnected: (cause: Events.DisconnectCause) => void,
234
277
  ) {
235
- let lostBy: DisconnectCause | undefined;
236
- const lost = yield* Deferred.make<DisconnectCause>();
278
+ let lostBy: Events.DisconnectCause | undefined;
279
+ const lost = yield* Deferred.make<Events.DisconnectCause>();
237
280
  const inFlight = new Set<(cause: Error) => void>();
238
281
  const gone = () => new Error("Target page, context or browser has been closed");
239
282
 
240
- const lose = (cause: DisconnectCause) => {
283
+ const lose = (cause: Events.DisconnectCause) => {
241
284
  if (lostBy !== undefined) return;
242
285
  lostBy = cause;
243
286
  for (const reject of inFlight) reject(gone());
@@ -270,92 +313,68 @@ const watchLoss = Effect.fnUntraced(function* (
270
313
  if (context.browser()?.isConnected() === false) onClose();
271
314
 
272
315
  const native = <A>(operation: string, run: () => Promise<A>) =>
273
- call(operation, run, () => lostBy ?? "page");
316
+ Effect.suspend(() =>
317
+ lostBy === undefined
318
+ ? call(
319
+ operation,
320
+ () => untilLost(run()),
321
+ () => lostBy ?? "page",
322
+ )
323
+ : failWith(operation, new Closed({ cause: lostBy })),
324
+ );
274
325
 
275
326
  return { lostBy: () => lostBy, lost: Deferred.await(lost), lose, untilLost, native };
276
327
  });
277
328
 
278
- /**
279
- * What a page's own Playwright events publish, its close and crash aside, while its scope is
280
- * open. Dialogs are answered: alerts accepted, others dismissed. The page's own session tells its
281
- * documents' commits and loads.
282
- */
283
- const listen = (
284
- playwright: PlaywrightPage,
285
- page: string,
286
- publish: (event: BrowserEvent) => number,
287
- now: () => number,
288
- on: { readonly close: () => void; readonly crash: () => void },
289
- ) => {
290
- const dialog = (shown: Dialog) => {
291
- const kind = shown.type();
292
- const answer = kind === "alert" || kind === "beforeunload" ? "accepted" : "dismissed";
293
- const message = shown.message().slice(0, 500);
294
-
295
- publish(new DialogShown({ at: now(), page, kind, message, answer }));
296
- (answer === "accepted" ? shown.accept() : shown.dismiss()).catch(() => undefined);
297
- };
298
-
299
- return Effect.acquireRelease(
300
- Effect.sync(() => {
301
- playwright.on("close", on.close);
302
- playwright.on("crash", on.crash);
303
- playwright.on("dialog", dialog);
304
- }),
305
- () =>
306
- Effect.sync(() => {
307
- playwright.off("close", on.close);
308
- playwright.off("crash", on.crash);
309
- playwright.off("dialog", dialog);
310
- }),
311
- );
312
- };
313
-
314
329
  /**
315
330
  * Register each page the site opens, such as a popup, as Playwright reports it, for as long as the
316
331
  * scope is open. One that could not be tracked is published, unless it closed as it opened.
317
332
  */
318
333
  const followOpened = Effect.fnUntraced(function* (
319
334
  context: BrowserContext,
320
- register: (playwright: PlaywrightPage) => Effect.Effect<Page.Page, BrowserError>,
321
- publish: (event: BrowserEvent) => number,
322
- now: () => number,
323
335
  registrations: Openings.Registrations,
336
+ registerPage: (playwright: PlaywrightPage) => Effect.Effect<Page.Page, BrowserError>,
337
+ publish: (event: Events.BrowserEvent) => number,
338
+ now: () => number,
324
339
  ) {
325
- const opened = yield* Queue.unbounded<PlaywrightPage>();
340
+ const registrationSlots = Semaphore.makeUnsafe(8);
341
+ const runRegistration = yield* FiberSet.makeRuntime();
342
+
343
+ const register = (playwright: PlaywrightPage) => {
344
+ const known = registrations.get(playwright);
345
+
346
+ if (known !== undefined) return Deferred.await(known);
347
+ const done = Deferred.makeUnsafe<Page.Page, BrowserError>();
348
+
349
+ // Publish the cell synchronously: the context's page event precedes its opener's popup event.
350
+ registrations.set(playwright, done);
351
+ runRegistration(
352
+ registrationSlots
353
+ .withPermits(1)(registerPage(playwright))
354
+ .pipe(
355
+ Effect.onExit((exit) => Deferred.done(done, exit)),
356
+ Effect.catch((error) =>
357
+ Effect.sync(() => {
358
+ if (!playwright.isClosed())
359
+ publish(
360
+ new Events.PageUntracked({
361
+ at: now(),
362
+ url: Url.redact(playwright.url()),
363
+ detail: error.message,
364
+ }),
365
+ );
366
+ }),
367
+ ),
368
+ ),
369
+ );
326
370
 
327
- const onPage = (playwright: PlaywrightPage) => {
328
- registrations.set(playwright, Deferred.makeUnsafe<void, BrowserError>());
329
- Queue.offerUnsafe(opened, playwright);
371
+ return Deferred.await(done);
330
372
  };
331
373
 
332
- const untracked = (playwright: PlaywrightPage) => (error: BrowserError) =>
333
- Effect.sync(() => {
334
- const url = Url.redact(playwright.url());
374
+ context.on("page", register);
375
+ yield* Effect.addFinalizer(() => Effect.sync(() => context.off("page", register)));
335
376
 
336
- if (!playwright.isClosed())
337
- publish(new PageUntracked({ at: now(), url, detail: error.message }));
338
- });
339
-
340
- context.on("page", onPage);
341
- yield* Effect.addFinalizer(() => Effect.sync(() => context.off("page", onPage)));
342
- yield* Queue.take(opened).pipe(
343
- Effect.flatMap((playwright) =>
344
- register(playwright).pipe(
345
- Effect.asVoid,
346
- Effect.onExit((exit) =>
347
- Effect.sync(() => {
348
- const done = registrations.get(playwright);
349
-
350
- if (done !== undefined) Deferred.doneUnsafe(done, exit);
351
- }),
352
- ),
353
- Effect.catch(untracked(playwright)),
354
- ),
355
- ),
356
- Effect.forever,
357
- Effect.forkScoped,
358
- );
377
+ return register;
359
378
  });
360
379
 
361
380
  /** Release something native, on the owner's clock, giving up after a second: cleanup only. */
@@ -368,7 +387,7 @@ const releaseNative = (clock: Clock.Clock) => (run: () => Promise<unknown>) =>
368
387
  );
369
388
 
370
389
  /** A page's own events among the browser's retained ones, and the openings of tabs it opened. */
371
- const eventsOf = (recent: Effect.Effect<ReadonlyArray<RecordedEvent>>, page: string) =>
390
+ const eventsOf = (recent: Effect.Effect<ReadonlyArray<Events.RecordedEvent>>, page: string) =>
372
391
  Effect.map(recent, (records) =>
373
392
  records.flatMap(({ event }) =>
374
393
  ("page" in event && event.page === page) ||
@@ -448,21 +467,21 @@ const sentNow = <A>(sent: Promise<A>) => {
448
467
 
449
468
  /** Close tab resources after publishing their close; a browser loss speaks for all its tabs. */
450
469
  const closures = (
451
- lostBy: () => DisconnectCause | undefined,
452
- publish: (event: BrowserEvent) => number,
470
+ lostBy: () => Events.DisconnectCause | undefined,
471
+ publish: (event: Events.BrowserEvent) => number,
453
472
  now: () => number,
454
473
  ) =>
455
474
  Effect.gen(function* () {
456
475
  const closing = yield* Queue.unbounded<{
457
476
  readonly scope: Scope.Closeable;
458
477
  readonly page: string;
459
- readonly cause: PageClosed["cause"];
478
+ readonly cause: Events.PageClosed["cause"];
460
479
  }>();
461
480
 
462
481
  yield* Queue.take(closing).pipe(
463
482
  Effect.tap(({ page, cause }) =>
464
483
  Effect.sync(() => {
465
- if (lostBy() === undefined) publish(new PageClosed({ at: now(), page, cause }));
484
+ if (lostBy() === undefined) publish(new Events.PageClosed({ at: now(), page, cause }));
466
485
  }),
467
486
  ),
468
487
  Effect.flatMap(({ scope }) => Scope.close(scope, Exit.void)),
@@ -473,25 +492,78 @@ const closures = (
473
492
  return closing;
474
493
  });
475
494
 
476
- /**
477
- * Build the service over a context the provider owns. The provider closes the context; this only
478
- * tracks its pages and events, for as long as the surrounding scope is open. Each page's protocol
479
- * session, capture and listeners end when that page closes or when the scope does, so a closed
480
- * tab retains nothing and the context keeps none of them afterwards.
481
- */
482
- export const make = Effect.fn("Browser.make")(function* (
495
+ /** Cookie checks disclose presence only, within the browser's native deadline. */
496
+ const cookieQuery =
497
+ (
498
+ context: BrowserContext,
499
+ native: Effect.Success<ReturnType<typeof watchLoss>>["native"],
500
+ timeout: Duration.Duration,
501
+ clock: Clock.Clock,
502
+ ): Service["hasCookie"] =>
503
+ ({ name, url }) =>
504
+ native("hasCookie", () => context.cookies(url)).pipe(
505
+ Effect.map((cookies) => cookies.some((cookie) => cookie.name === name)),
506
+ Effect.timeoutOrElse({
507
+ duration: timeout,
508
+ orElse: () => failWith("hasCookie", new Timeout({ millis: Duration.toMillis(timeout) })),
509
+ }),
510
+ Effect.provideService(Clock.Clock, clock),
511
+ );
512
+
513
+ /** Tab allocation shares its budget, registration and first-tab lock. */
514
+ const tabs = (
483
515
  context: BrowserContext,
484
- info: {
485
- readonly id: string;
486
- readonly provider: string;
487
- readonly expiresAt?: DateTime.Utc | undefined;
488
- /** Where pages' screencasts run, if not on each page's own session. */
489
- readonly capture?: CaptureSource | undefined;
490
- },
491
- options: Options = {},
516
+ registry: Map<PlaywrightPage, Page.Page>,
517
+ budget: ReturnType<typeof pageBudget>,
518
+ native: Effect.Success<ReturnType<typeof watchLoss>>["native"],
519
+ register: (page: PlaywrightPage) => Effect.Effect<Page.Page, BrowserError>,
520
+ release: ReturnType<typeof releaseNative>,
521
+ firstPageLock: Semaphore.Semaphore,
522
+ ) => {
523
+ const pages = Effect.sync(() => [...registry.values()]);
524
+
525
+ const newPage = Effect.fn("Browser.newPage")(function* (url?: string) {
526
+ const page = yield* budget.open(
527
+ native("newPage", () => context.newPage()).pipe(
528
+ Effect.flatMap((playwright) =>
529
+ register(playwright).pipe(Effect.onError(() => release(() => playwright.close()))),
530
+ ),
531
+ ),
532
+ );
533
+
534
+ // A rejected or interrupted navigation must not leave the newly allocated blank tab behind.
535
+ if (url !== undefined)
536
+ yield* page.goto(url).pipe(Effect.onError(() => page.close.pipe(Effect.ignore)));
537
+
538
+ return page;
539
+ });
540
+
541
+ return {
542
+ pages,
543
+ page: (id: string) =>
544
+ Effect.map(pages, (open) => Option.fromNullishOr(open.find((page) => page.id === id))),
545
+ firstPage: firstPageLock.withPermits(1)(
546
+ pages.pipe(
547
+ Effect.map((open) => Option.fromNullishOr(open[0])),
548
+ Effect.flatMap(Option.match({ onNone: () => newPage(), onSome: Effect.succeed })),
549
+ ),
550
+ ),
551
+ newPage,
552
+ };
553
+ };
554
+
555
+ /** One connection owns clocks, loss, authority and its bounded timeline. */
556
+ const runtime = Effect.fnUntraced(function* (
557
+ context: BrowserContext,
558
+ expiresAt: DateTime.Utc | undefined,
559
+ options: Options,
492
560
  ) {
493
561
  const clock = yield* Clock.Clock;
494
562
  const connection = yield* Identity.make;
563
+ const protocol = yield* Port.Current;
564
+ const releasePort = protocol.browser?.(connection, context);
565
+
566
+ yield* Effect.addFinalizer(() => Effect.sync(() => releasePort?.()));
495
567
  const now = () => BrowserClock.monotonicMillis(clock);
496
568
  const { settings, eventHistory, maxPages } = yield* settingsOf(options);
497
569
  // Measured on first need: the first capture of any page measures it, and input never waits.
@@ -502,16 +574,27 @@ export const make = Effect.fn("Browser.make")(function* (
502
574
  yield* Effect.addFinalizer(() => timeline.close);
503
575
  const publish = timeline.publish;
504
576
 
505
- if (info.expiresAt !== undefined)
506
- publish(new SessionEnding({ at: now(), expiresAt: info.expiresAt }));
577
+ if (expiresAt !== undefined)
578
+ publish(new Events.SessionEnding({ at: now(), expiresAt: expiresAt }));
507
579
 
508
580
  const { lostBy, lost, lose, untilLost, native } = yield* watchLoss(
509
581
  context,
510
- info.expiresAt,
582
+ expiresAt,
511
583
  clock,
512
- (cause) => publish(new Disconnected({ at: now(), cause })),
584
+ (cause) => publish(new Events.Disconnected({ at: now(), cause })),
513
585
  );
514
586
 
587
+ if (options.requests !== undefined)
588
+ yield* Requests.install(
589
+ context,
590
+ options.requests,
591
+ clock,
592
+ publish,
593
+ now,
594
+ () => lose("connection"),
595
+ () => lostBy() !== undefined,
596
+ );
597
+
515
598
  const inputGate = Gate.make({
516
599
  now,
517
600
  sequence: timeline.sequence,
@@ -521,9 +604,64 @@ export const make = Effect.fn("Browser.make")(function* (
521
604
  drain: settings.navigationTimeout,
522
605
  });
523
606
 
607
+ return {
608
+ clock,
609
+ connection,
610
+ protocol,
611
+ now,
612
+ settings,
613
+ maxPages,
614
+ mapping,
615
+ timeline,
616
+ publish,
617
+ lostBy,
618
+ lost,
619
+ lose,
620
+ untilLost,
621
+ native,
622
+ inputGate,
623
+ };
624
+ });
625
+
626
+ /**
627
+ * Build the service over a context the provider owns. The provider closes the context; this only
628
+ * tracks its pages and events, for as long as the surrounding scope is open. Each page's protocol
629
+ * session, capture and listeners end when that page closes or when the scope does, so a closed
630
+ * tab retains nothing and the context keeps none of them afterwards.
631
+ */
632
+ export const make = Effect.fn("Browser.make")(function* (
633
+ context: BrowserContext,
634
+ info: {
635
+ readonly id?: string | undefined;
636
+ readonly provider: string;
637
+ readonly expiresAt?: DateTime.Utc | undefined;
638
+ /** Where pages' screencasts run, if not on each page's own session. */
639
+ readonly capture?: CaptureSource | undefined;
640
+ },
641
+ options: Options = {},
642
+ ) {
643
+ const {
644
+ clock,
645
+ connection,
646
+ protocol,
647
+ now,
648
+ settings,
649
+ maxPages,
650
+ mapping,
651
+ timeline,
652
+ publish,
653
+ lostBy,
654
+ lost,
655
+ lose,
656
+ untilLost,
657
+ native,
658
+ inputGate,
659
+ } = yield* runtime(context, info.expiresAt, options);
660
+
661
+ const session = info.id ?? connection;
662
+
524
663
  const registry = new Map<PlaywrightPage, Page.Page>();
525
664
  const registrations: Openings.Registrations = new WeakMap();
526
- const registering = yield* Semaphore.make(1);
527
665
  // The pages' scopes close after the browser is marked released, so what fails as they close
528
666
  // says why.
529
667
  const pagesScope = yield* Scope.fork(yield* Scope.Scope);
@@ -536,131 +674,134 @@ export const make = Effect.fn("Browser.make")(function* (
536
674
  // fiber in a later turn, once Playwright has reported the context's.
537
675
  const closing = yield* closures(lostBy, publish, now);
538
676
 
539
- const register = (playwright: PlaywrightPage) =>
540
- registering.withPermits(1)(
541
- Effect.gen(function* () {
542
- const known = registry.get(playwright);
543
-
544
- if (known !== undefined) return known;
545
- if (playwright.isClosed())
546
- return yield* failWith("newPage", new Failed({ detail: "the page closed as it opened" }));
547
- const scope = yield* Scope.fork(pagesScope);
548
-
549
- return yield* Effect.gen(function* () {
550
- let crashed = false;
551
- const closedBy = () => lostBy() ?? (crashed ? "crashed" : "page");
552
- const cdp = yield* native("newPage", () => context.newCDPSession(playwright));
553
-
554
- yield* Effect.addFinalizer(() => release(() => cdp.detach()));
555
- // The page's name, its target id, costs one round trip, which the calls that keep it
556
- // painting behind other tabs and report its documents share. A renderer busy with its
557
- // first script answers those two late, so what needs them waits, and registering does not.
558
- const send: typeof cdp.send = (method, params) => untilLost(cdp.send(method, params));
559
- const focusing = sentNow(send("Emulation.setFocusEmulationEnabled", { enabled: true }));
560
- const paging = sentNow(send("Page.enable"));
561
- const { targetInfo } = yield* native("newPage", () => send("Target.getTargetInfo"));
562
- const id = targetInfo.targetId;
563
-
564
- const page = yield* PageImpl.make({
565
- id,
566
- session: info.id,
567
- connection,
568
- url: targetInfo.url,
569
- playwright,
570
- cdp,
571
- untilLost,
572
- settings,
573
- inputGate,
574
- clock,
575
- mapping,
576
- publish,
577
- recentEvents: eventsOf(timeline.recent, id),
578
- openings: yield* Openings.make(playwright, cdp, registrations, closedBy),
579
- focused: call("focus", () => focusing, closedBy).pipe(Effect.asVoid),
580
- paging: (operation) => call(operation, () => paging, closedBy).pipe(Effect.asVoid),
581
- closedBy,
582
- capture: info.capture,
583
- });
584
-
585
- const close = () => {
586
- if (registry.get(playwright) !== page) return;
587
- registry.delete(playwright);
588
- budget.makeRoom();
589
- Queue.offerUnsafe(closing, { scope, page: id, cause: crashed ? "crashed" : "page" });
590
- };
591
-
592
- // Playwright drives a crashed page no more and its calls never return, so it is closed:
593
- // they fail at once, `Closed` because it crashed.
594
- const crash = () => {
595
- crashed = true;
596
- void playwright.close().catch(() => undefined);
597
- };
598
-
599
- registry.set(playwright, page);
600
- publish(
601
- new PageOpened({
602
- at: now(),
603
- page: id,
604
- url: Url.redact(targetInfo.url),
605
- opener: targetInfo.openerId,
606
- }),
607
- );
608
- yield* listen(playwright, id, publish, now, { close, crash });
609
- if (playwright.isClosed()) close();
610
-
611
- return page;
612
- }).pipe(
613
- Scope.provide(scope),
614
- Effect.onError(() => Scope.close(scope, Exit.void)),
677
+ const registerPage = (playwright: PlaywrightPage) =>
678
+ Effect.gen(function* () {
679
+ if (playwright.isClosed())
680
+ return yield* failWith("newPage", new Failed({ detail: "the page closed as it opened" }));
681
+ const viewport = options.viewport;
682
+
683
+ if (viewport !== undefined)
684
+ yield* native("viewport", () => playwright.setViewportSize(viewport));
685
+ const scope = yield* Scope.fork(pagesScope);
686
+
687
+ return yield* Effect.gen(function* () {
688
+ let crashed = false;
689
+ const closedBy = () => lostBy() ?? (crashed ? "crashed" : "page");
690
+
691
+ const cdp = yield* Port.openSession(
692
+ () => context.newCDPSession(playwright),
693
+ playwright,
694
+ ).pipe(Effect.provideService(Port.Current, protocol));
695
+
696
+ yield* Effect.addFinalizer(() => release(() => cdp.detach()));
697
+ // The page's name, its target id, costs one round trip, which the calls that keep it
698
+ // painting behind other tabs and report its documents share. A renderer busy with its
699
+ // first script answers those two late, so what needs them waits, and registering does not.
700
+ const send: typeof cdp.send = (method, params) => untilLost(cdp.send(method, params));
701
+ const focusing = sentNow(send("Emulation.setFocusEmulationEnabled", { enabled: true }));
702
+ const paging = sentNow(send("Page.enable"));
703
+ const { targetInfo } = yield* native("newPage", () => send("Target.getTargetInfo"));
704
+ const id = targetInfo.targetId;
705
+
706
+ const page = yield* PageImpl.make({
707
+ id,
708
+ session,
709
+ connection,
710
+ url: targetInfo.url,
711
+ playwright,
712
+ cdp,
713
+ nativePort: protocol.native,
714
+ untilLost,
715
+ settings,
716
+ inputGate,
717
+ clock,
718
+ mapping,
719
+ publish,
720
+ recentEvents: eventsOf(timeline.recent, id),
721
+ openings: yield* Openings.make(playwright, cdp, registrations, closedBy),
722
+ focused: call("focus", () => focusing, closedBy).pipe(Effect.asVoid),
723
+ paging: (operation) => call(operation, () => paging, closedBy).pipe(Effect.asVoid),
724
+ closedBy,
725
+ capture: info.capture,
726
+ }).pipe(Effect.provideService(Port.Current, protocol));
727
+
728
+ const close = () => {
729
+ if (registry.get(playwright) !== page) return;
730
+ registry.delete(playwright);
731
+ registrations.delete(playwright);
732
+ budget.makeRoom();
733
+ Queue.offerUnsafe(closing, { scope, page: id, cause: crashed ? "crashed" : "page" });
734
+ };
735
+
736
+ // Playwright drives a crashed page no more and its calls never return, so it is closed:
737
+ // they fail at once, `Closed` because it crashed.
738
+ const crash = () => {
739
+ crashed = true;
740
+ void playwright.close().catch(() => undefined);
741
+ };
742
+
743
+ registry.set(playwright, page);
744
+ publish(
745
+ new Events.PageOpened({
746
+ at: now(),
747
+ page: id,
748
+ url: Url.redact(targetInfo.url),
749
+ opener: targetInfo.openerId,
750
+ }),
615
751
  );
616
- }),
617
- );
752
+ yield* listen(
753
+ playwright,
754
+ id,
755
+ publish,
756
+ now,
757
+ (accept) =>
758
+ native("dialog", () => send("Page.handleJavaScriptDialog", { accept })).pipe(
759
+ Effect.asVoid,
760
+ Effect.timeoutOrElse({
761
+ duration: settings.actionTimeout,
762
+ orElse: () => failWith("dialog", new Failed({ detail: "dialog answer timed out" })),
763
+ }),
764
+ Effect.provideService(Clock.Clock, clock),
765
+ ),
766
+ {
767
+ close,
768
+ crash,
769
+ failed: () => {
770
+ // An unanswered dialog invalidates this page, not sibling pages or the connection.
771
+ void playwright.close().catch(() => undefined);
772
+ },
773
+ },
774
+ );
775
+ if (playwright.isClosed()) close();
776
+
777
+ return page;
778
+ }).pipe(
779
+ Scope.provide(scope),
780
+ Effect.onError(() => Scope.close(scope, Exit.void)),
781
+ );
782
+ });
618
783
 
619
784
  // Playwright registers its init scripts as it sets up each page, before a popup's first document
620
785
  // runs, and they cost no call per document.
621
786
  for (const script of options.initScripts ?? [])
622
787
  yield* native("initScripts", () => context.addInitScript({ content: scoped(script) }));
623
- yield* followOpened(context, register, publish, now, registrations);
624
- for (const existing of context.pages()) yield* register(existing);
625
-
626
- const pages = Effect.sync(() => [...registry.values()]);
788
+ const register = yield* followOpened(context, registrations, registerPage, publish, now);
627
789
 
628
- const newPage = Effect.fn("Browser.newPage")(function* (url?: string) {
629
- const page = yield* budget.open(
630
- native("newPage", () => context.newPage()).pipe(
631
- Effect.flatMap((playwright) =>
632
- register(playwright).pipe(Effect.onError(() => release(() => playwright.close()))),
633
- ),
634
- ),
635
- );
636
-
637
- // A rejected or interrupted navigation must not leave the newly allocated blank tab behind.
638
- if (url !== undefined)
639
- yield* page.goto(url).pipe(Effect.onError(() => page.close.pipe(Effect.ignore)));
640
-
641
- return page;
642
- });
790
+ for (const existing of context.pages()) yield* register(existing);
643
791
 
644
792
  // Added last, so it runs first as the owner's scope closes.
645
793
  yield* Effect.addFinalizer(() => Effect.sync(() => lose("released")));
646
794
 
647
795
  const service: Service = {
648
- id: info.id,
796
+ id: session,
649
797
  connection,
650
798
  provider: info.provider,
651
799
  expiresAt: info.expiresAt,
652
800
  now: Effect.sync(now),
653
801
  suspend: (options = {}) =>
654
802
  Effect.map(inputGate.suspend(options.drain), (held) => new Suspension(held)),
655
- context,
656
- pages,
657
- page: (id) =>
658
- Effect.map(pages, (open) => Option.fromNullishOr(open.find((page) => page.id === id))),
659
- firstPage: pages.pipe(
660
- Effect.map((open) => Option.fromNullishOr(open[0])),
661
- Effect.flatMap(Option.match({ onNone: () => newPage(), onSome: Effect.succeed })),
662
- ),
663
- newPage,
803
+ ...tabs(context, registry, budget, native, register, release, Semaphore.makeUnsafe(1)),
804
+ hasCookie: cookieQuery(context, native, settings.actionTimeout, clock),
664
805
  disconnected: lost,
665
806
  events: (eventOptions = {}) => timeline.stream(eventOptions.after),
666
807
  recentEvents: timeline.recent.pipe(