effect-browser 0.3.0-beta.21 → 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 (248) hide show
  1. package/README.md +130 -159
  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-CiXHT1yO.d.mts → Browser-wZhwZSlG.d.mts} +51 -13
  12. package/dist/Browser.d.mts +2 -2
  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/Matching.d.mts +37 -0
  38. package/dist/Matching.mjs +72 -0
  39. package/dist/Matching.mjs.map +1 -0
  40. package/dist/Page-BF5izr8R.mjs +795 -0
  41. package/dist/Page-BF5izr8R.mjs.map +1 -0
  42. package/dist/{Page-ku6j5t-v.d.mts → Page-CvsOEorc.d.mts} +158 -185
  43. package/dist/Page.d.mts +2 -2
  44. package/dist/Page.mjs +1 -1
  45. package/dist/Released-tURbFmal.d.mts +15 -0
  46. package/dist/{Snapshot-B34hZ4Jl.d.mts → Snapshot-CtBVOtuu.d.mts} +6 -1
  47. package/dist/Snapshot.d.mts +1 -1
  48. package/dist/Snapshot.mjs.map +1 -1
  49. package/dist/Stillness-CNlvayIo.mjs +136 -0
  50. package/dist/Stillness-CNlvayIo.mjs.map +1 -0
  51. package/dist/Style-AO4V7Czt.mjs +357 -0
  52. package/dist/Style-AO4V7Czt.mjs.map +1 -0
  53. package/dist/Style.d.mts +72 -0
  54. package/dist/Style.mjs +2 -0
  55. package/dist/Url.d.mts +26 -0
  56. package/dist/Url.mjs +74 -0
  57. package/dist/Url.mjs.map +1 -0
  58. package/dist/Window-CMddGMt1.d.mts +34 -0
  59. package/dist/Window.d.mts +2 -0
  60. package/dist/Window.mjs +35 -0
  61. package/dist/Window.mjs.map +1 -0
  62. package/dist/{cdp-DL7XfEj5.d.mts → connection-2KHI4_KN.d.mts} +4 -4
  63. package/dist/{cdp-BMpYMWYe.mjs → connection-BTeO0Hiz.mjs} +5 -6
  64. package/dist/connection-BTeO0Hiz.mjs.map +1 -0
  65. package/dist/index.d.mts +15 -18
  66. package/dist/index.mjs +11 -15
  67. package/dist/moment/Moment.d.mts +86 -0
  68. package/dist/{Moment.mjs → moment/Moment.mjs} +44 -38
  69. package/dist/moment/Moment.mjs.map +1 -0
  70. package/dist/{Plan-DJ4hEEna.d.mts → plan/index.d.mts} +169 -64
  71. package/dist/{Plan-BG1WifW2.mjs → plan/index.mjs} +122 -199
  72. package/dist/plan/index.mjs.map +1 -0
  73. package/dist/{Policy-BGWjbqCl.d.mts → policy/Policy.d.mts} +16 -20
  74. package/dist/{Policy.mjs → policy/Policy.mjs} +11 -21
  75. package/dist/policy/Policy.mjs.map +1 -0
  76. package/dist/presentation/Motion.d.mts +12 -0
  77. package/dist/{Motion.mjs → presentation/Motion.mjs} +4 -27
  78. package/dist/presentation/Motion.mjs.map +1 -0
  79. package/dist/presentation/Presentation.d.mts +30 -0
  80. package/dist/presentation/Presentation.mjs +105 -0
  81. package/dist/presentation/Presentation.mjs.map +1 -0
  82. package/dist/{Stage-NHp8N81k.d.mts → presentation/Stage.d.mts} +12 -15
  83. package/dist/{Stage.mjs → presentation/Stage.mjs} +68 -76
  84. package/dist/presentation/Stage.mjs.map +1 -0
  85. package/dist/presentation/feed.d.mts +20 -0
  86. package/dist/presentation/feed.mjs +18 -0
  87. package/dist/presentation/feed.mjs.map +1 -0
  88. package/dist/providers/Cdp.d.mts +9 -0
  89. package/dist/{Cdp.mjs → providers/Cdp.mjs} +3 -8
  90. package/dist/providers/Cdp.mjs.map +1 -0
  91. package/dist/{Chromium.d.mts → providers/Chromium.d.mts} +6 -7
  92. package/dist/{Chromium.mjs → providers/Chromium.mjs} +6 -15
  93. package/dist/providers/Chromium.mjs.map +1 -0
  94. package/dist/providers/Released.d.mts +2 -0
  95. package/dist/providers/Released.mjs +12 -0
  96. package/dist/providers/Released.mjs.map +1 -0
  97. package/dist/stillness/Stillness.d.mts +12 -0
  98. package/dist/stillness/Stillness.mjs +2 -0
  99. package/dist/supervisor/Supervisor.d.mts +104 -0
  100. package/dist/supervisor/Supervisor.mjs +513 -0
  101. package/dist/supervisor/Supervisor.mjs.map +1 -0
  102. package/dist/testing/index.d.mts +337 -0
  103. package/dist/testing/index.mjs +515 -0
  104. package/dist/testing/index.mjs.map +1 -0
  105. package/dist/workerd/Cdp.d.mts +8 -3
  106. package/dist/workerd/Cdp.mjs +2 -7
  107. package/dist/workerd/Cdp.mjs.map +1 -1
  108. package/package.json +86 -36
  109. package/src/Action.ts +127 -0
  110. package/src/ActionPort.ts +128 -0
  111. package/src/Browser.ts +352 -201
  112. package/src/BrowserError.ts +63 -6
  113. package/src/BrowserEvent.ts +26 -25
  114. package/src/Change.ts +0 -2
  115. package/src/{internal/pictures/clock.ts → Clock.ts} +17 -6
  116. package/src/Frame.ts +14 -0
  117. package/src/Geometry.ts +48 -0
  118. package/src/{internal/reading/match.inpage.ts → Matching.ts} +34 -4
  119. package/src/Page.ts +111 -92
  120. package/src/Snapshot.ts +5 -0
  121. package/src/{internal/input/style.ts → Style.ts} +121 -14
  122. package/src/Window.ts +30 -0
  123. package/src/index.ts +15 -6
  124. package/src/internal/input/actions.ts +61 -119
  125. package/src/internal/input/dispatch.ts +3 -3
  126. package/src/internal/input/gate.ts +21 -18
  127. package/src/internal/input/guard.inpage.ts +25 -58
  128. package/src/internal/input/guard.ts +11 -20
  129. package/src/internal/input/keyboard.ts +12 -3
  130. package/src/internal/input/perform.ts +78 -60
  131. package/src/internal/input/pointer.ts +4 -2
  132. package/src/internal/input/settle.ts +7 -5
  133. package/src/internal/input/targets.inpage.ts +1 -1
  134. package/src/internal/input/targets.ts +4 -9
  135. package/src/internal/page/bridge.ts +209 -113
  136. package/src/internal/page/context.ts +12 -59
  137. package/src/internal/page/dialogs.ts +58 -0
  138. package/src/internal/page/lane.ts +14 -15
  139. package/src/internal/page/navigation.ts +50 -42
  140. package/src/internal/page/openings.ts +11 -5
  141. package/src/internal/page/page.ts +44 -81
  142. package/src/internal/page/port.ts +125 -0
  143. package/src/internal/{input → page}/replies.ts +1 -1
  144. package/src/internal/page/request-owner.ts +269 -0
  145. package/src/internal/page/requests.ts +357 -0
  146. package/src/internal/page/scripts.ts +124 -0
  147. package/src/internal/pictures/capture.ts +255 -332
  148. package/src/internal/pictures/dimensions.ts +162 -0
  149. package/src/internal/pictures/frame.ts +68 -0
  150. package/src/internal/pictures/pictures.ts +57 -23
  151. package/src/internal/pictures/quiescence.ts +1 -1
  152. package/src/internal/pictures/state.ts +26 -0
  153. package/src/internal/pictures/transport.ts +21 -4
  154. package/src/internal/reading/controls.inpage.ts +5 -70
  155. package/src/internal/reading/expect.inpage.ts +13 -17
  156. package/src/internal/reading/names.inpage.ts +89 -45
  157. package/src/internal/reading/outline.inpage.ts +6 -7
  158. package/src/internal/reading/reading.ts +144 -176
  159. package/src/internal/reading/ready.inpage.ts +6 -17
  160. package/src/internal/reading/ready.ts +13 -135
  161. package/src/internal/reading/subjects.inpage.ts +83 -43
  162. package/src/internal/reading/walk.inpage.ts +33 -13
  163. package/src/internal/timeline/changes.ts +55 -6
  164. package/src/internal/timeline/events.ts +15 -5
  165. package/src/internal/timeline/history.inpage.ts +1 -1
  166. package/src/internal/timeline/record.inpage.ts +4 -1
  167. package/src/internal/timeline/window.ts +2 -1
  168. package/src/{Moment.ts → moment/Moment.ts} +13 -31
  169. package/src/{internal/timeline → moment}/words.ts +2 -2
  170. package/src/{internal/reading → plan}/choose.ts +3 -3
  171. package/src/plan/data.ts +117 -0
  172. package/src/plan/execute.ts +411 -0
  173. package/src/plan/index.ts +36 -0
  174. package/src/plan/record.ts +71 -0
  175. package/src/plan/targets.ts +71 -0
  176. package/src/{Policy.ts → policy/Policy.ts} +13 -10
  177. package/src/{Motion.ts → presentation/Motion.ts} +12 -46
  178. package/src/presentation/Presentation.ts +176 -0
  179. package/src/{Stage.ts → presentation/Stage.ts} +147 -112
  180. package/src/presentation/feed.ts +21 -0
  181. package/src/{Cdp.ts → providers/Cdp.ts} +2 -2
  182. package/src/{Chromium.ts → providers/Chromium.ts} +7 -10
  183. package/src/providers/Released.ts +13 -0
  184. package/src/{internal/cdp.ts → providers/connection.ts} +2 -2
  185. package/src/{internal/pictures/motion.ts → stillness/Pixels.ts} +1 -1
  186. package/src/stillness/Stillness.ts +166 -0
  187. package/src/supervisor/Supervisor.ts +170 -0
  188. package/src/supervisor/contract.ts +105 -0
  189. package/src/supervisor/lifecycle.ts +272 -0
  190. package/src/supervisor/runtime.ts +234 -0
  191. package/src/testing/TestBrowser.ts +115 -0
  192. package/src/testing/TestPage.ts +10 -0
  193. package/src/testing/evidence.ts +154 -0
  194. package/src/testing/index.ts +3 -0
  195. package/src/testing/model.ts +222 -0
  196. package/src/testing/page.ts +360 -0
  197. package/src/workerd/Cdp.ts +2 -2
  198. package/dist/Browser-CxXUjxOp.mjs +0 -619
  199. package/dist/Browser-CxXUjxOp.mjs.map +0 -1
  200. package/dist/Cdp-CzCRnMlM.d.mts +0 -10
  201. package/dist/Cdp.d.mts +0 -11
  202. package/dist/Cdp.mjs.map +0 -1
  203. package/dist/Change-DNvztNLu.mjs +0 -138
  204. package/dist/Change-DNvztNLu.mjs.map +0 -1
  205. package/dist/Chromium.mjs.map +0 -1
  206. package/dist/Expect-u3P_ENLX.d.mts +0 -62
  207. package/dist/Expect.d.mts +0 -2
  208. package/dist/Expect.mjs +0 -114
  209. package/dist/Expect.mjs.map +0 -1
  210. package/dist/Moment.d.mts +0 -2
  211. package/dist/Moment.mjs.map +0 -1
  212. package/dist/Motion.d.mts +0 -2
  213. package/dist/Motion.mjs.map +0 -1
  214. package/dist/Page-BP02bmNv.mjs +0 -264
  215. package/dist/Page-BP02bmNv.mjs.map +0 -1
  216. package/dist/Plan-BG1WifW2.mjs.map +0 -1
  217. package/dist/Plan.d.mts +0 -2
  218. package/dist/Plan.mjs +0 -2
  219. package/dist/Policy.d.mts +0 -2
  220. package/dist/Policy.mjs.map +0 -1
  221. package/dist/Presentation-DxVikn9_.d.mts +0 -48
  222. package/dist/Presentation.d.mts +0 -2
  223. package/dist/Presentation.mjs +0 -118
  224. package/dist/Presentation.mjs.map +0 -1
  225. package/dist/Stage.d.mts +0 -2
  226. package/dist/Stage.mjs.map +0 -1
  227. package/dist/Supervisor-2mPjIYYs.mjs +0 -676
  228. package/dist/Supervisor-2mPjIYYs.mjs.map +0 -1
  229. package/dist/Supervisor-CfRxbaso.d.mts +0 -317
  230. package/dist/Supervisor.d.mts +0 -2
  231. package/dist/Supervisor.mjs +0 -2
  232. package/dist/cdp-BMpYMWYe.mjs.map +0 -1
  233. package/dist/context-EGhOqjNN.mjs +0 -335
  234. package/dist/context-EGhOqjNN.mjs.map +0 -1
  235. package/dist/page-PTM8m5wC.mjs +0 -4057
  236. package/dist/page-PTM8m5wC.mjs.map +0 -1
  237. package/dist/url-Bsp2y55M.mjs +0 -264
  238. package/dist/url-Bsp2y55M.mjs.map +0 -1
  239. package/dist/workerd/index.d.mts +0 -16
  240. package/dist/workerd/index.mjs +0 -17
  241. package/src/Expect.ts +0 -180
  242. package/src/Plan.ts +0 -674
  243. package/src/Presentation.ts +0 -196
  244. package/src/Supervisor.ts +0 -632
  245. package/src/internal/supervisor/lifecycle.ts +0 -484
  246. package/src/workerd/index.ts +0 -17
  247. /package/src/{internal/page/url.ts → Url.ts} +0 -0
  248. /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,20 +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
+ import {
30
+ type BrowserError,
31
+ Closed,
32
+ Failed,
33
+ InvalidRequest,
34
+ Limit,
35
+ Timeout,
36
+ } from "./BrowserError.ts";
29
37
  import * as Events from "./BrowserEvent.ts";
38
+ import * as BrowserClock from "./Clock.ts";
30
39
  import * as Gate from "./internal/input/gate.ts";
31
40
  import { call, failWith, type Settings, undispatched } from "./internal/page/context.ts";
41
+ import { listen } from "./internal/page/dialogs.ts";
32
42
  import * as Identity from "./internal/page/identity.ts";
33
43
  import { FailFast } from "./internal/page/lane.ts";
34
44
  import * as Openings from "./internal/page/openings.ts";
35
45
  import * as PageImpl from "./internal/page/page.ts";
36
- import * as Url from "./internal/page/url.ts";
37
- 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";
38
48
  import * as Timeline from "./internal/timeline/events.ts";
39
49
  import type * as Page from "./Page.ts";
50
+ import * as Url from "./Url.ts";
40
51
 
41
52
  /** A script that documents run before their own, such as a consent-banner remover. */
42
53
  export interface InitScript {
@@ -49,7 +60,39 @@ export interface InitScript {
49
60
  readonly source: string;
50
61
  }
51
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
+
52
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;
53
96
  /**
54
97
  * Bound on each action; finite and positive. Defaults to 10 seconds. What a presenter's view
55
98
  * takes to show an action, such as its glides and typing at a person's pace, does not count
@@ -144,8 +187,6 @@ export interface Service {
144
187
  readonly suspend: (
145
188
  options?: SuspendOptions,
146
189
  ) => Effect.Effect<Suspension, BrowserError, Scope.Scope>;
147
- /** The Playwright context, for anything this API does not cover. Never give it to a model. */
148
- readonly context: BrowserContext;
149
190
  /** Open pages in the order this browser began tracking them. */
150
191
  readonly pages: Effect.Effect<ReadonlyArray<Page.Page>>;
151
192
  /** The open page with this id, its CDP target id, as stored before a reconnect. */
@@ -153,6 +194,11 @@ export interface Service {
153
194
  /** The first open page, opening one when there is none. */
154
195
  readonly firstPage: Effect.Effect<Page.Page, BrowserError>;
155
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>;
156
202
  /**
157
203
  * Completes once the browser is lost to its owner, with why: its connection dropped, its
158
204
  * provider ended its session, or its owner's scope released it.
@@ -193,6 +239,13 @@ const settingsOf = Effect.fnUntraced(function* (options: Options) {
193
239
  policyTimeout: yield* bound("policyTimeout", options.policyTimeout, Duration.minutes(5)),
194
240
  };
195
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");
196
249
  const eventHistory = options.eventHistory ?? 4096;
197
250
  const { maxPages } = options;
198
251
 
@@ -260,92 +313,68 @@ const watchLoss = Effect.fnUntraced(function* (
260
313
  if (context.browser()?.isConnected() === false) onClose();
261
314
 
262
315
  const native = <A>(operation: string, run: () => Promise<A>) =>
263
- 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
+ );
264
325
 
265
326
  return { lostBy: () => lostBy, lost: Deferred.await(lost), lose, untilLost, native };
266
327
  });
267
328
 
268
- /**
269
- * What a page's own Playwright events publish, its close and crash aside, while its scope is
270
- * open. Dialogs are answered: alerts accepted, others dismissed. The page's own session tells its
271
- * documents' commits and loads.
272
- */
273
- const listen = (
274
- playwright: PlaywrightPage,
275
- page: string,
276
- publish: (event: Events.BrowserEvent) => number,
277
- now: () => number,
278
- on: { readonly close: () => void; readonly crash: () => void },
279
- ) => {
280
- const dialog = (shown: Dialog) => {
281
- const kind = shown.type();
282
- const answer = kind === "alert" || kind === "beforeunload" ? "accepted" : "dismissed";
283
- const message = shown.message().slice(0, 500);
284
-
285
- publish(new Events.DialogShown({ at: now(), page, kind, message, answer }));
286
- (answer === "accepted" ? shown.accept() : shown.dismiss()).catch(() => undefined);
287
- };
288
-
289
- return Effect.acquireRelease(
290
- Effect.sync(() => {
291
- playwright.on("close", on.close);
292
- playwright.on("crash", on.crash);
293
- playwright.on("dialog", dialog);
294
- }),
295
- () =>
296
- Effect.sync(() => {
297
- playwright.off("close", on.close);
298
- playwright.off("crash", on.crash);
299
- playwright.off("dialog", dialog);
300
- }),
301
- );
302
- };
303
-
304
329
  /**
305
330
  * Register each page the site opens, such as a popup, as Playwright reports it, for as long as the
306
331
  * scope is open. One that could not be tracked is published, unless it closed as it opened.
307
332
  */
308
333
  const followOpened = Effect.fnUntraced(function* (
309
334
  context: BrowserContext,
310
- register: (playwright: PlaywrightPage) => Effect.Effect<Page.Page, BrowserError>,
335
+ registrations: Openings.Registrations,
336
+ registerPage: (playwright: PlaywrightPage) => Effect.Effect<Page.Page, BrowserError>,
311
337
  publish: (event: Events.BrowserEvent) => number,
312
338
  now: () => number,
313
- registrations: Openings.Registrations,
314
339
  ) {
315
- 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
+ );
316
370
 
317
- const onPage = (playwright: PlaywrightPage) => {
318
- registrations.set(playwright, Deferred.makeUnsafe<void, BrowserError>());
319
- Queue.offerUnsafe(opened, playwright);
371
+ return Deferred.await(done);
320
372
  };
321
373
 
322
- const untracked = (playwright: PlaywrightPage) => (error: BrowserError) =>
323
- Effect.sync(() => {
324
- const url = Url.redact(playwright.url());
325
-
326
- if (!playwright.isClosed())
327
- publish(new Events.PageUntracked({ at: now(), url, detail: error.message }));
328
- });
374
+ context.on("page", register);
375
+ yield* Effect.addFinalizer(() => Effect.sync(() => context.off("page", register)));
329
376
 
330
- context.on("page", onPage);
331
- yield* Effect.addFinalizer(() => Effect.sync(() => context.off("page", onPage)));
332
- yield* Queue.take(opened).pipe(
333
- Effect.flatMap((playwright) =>
334
- register(playwright).pipe(
335
- Effect.asVoid,
336
- Effect.onExit((exit) =>
337
- Effect.sync(() => {
338
- const done = registrations.get(playwright);
339
-
340
- if (done !== undefined) Deferred.doneUnsafe(done, exit);
341
- }),
342
- ),
343
- Effect.catch(untracked(playwright)),
344
- ),
345
- ),
346
- Effect.forever,
347
- Effect.forkScoped,
348
- );
377
+ return register;
349
378
  });
350
379
 
351
380
  /** Release something native, on the owner's clock, giving up after a second: cleanup only. */
@@ -463,25 +492,78 @@ const closures = (
463
492
  return closing;
464
493
  });
465
494
 
466
- /**
467
- * Build the service over a context the provider owns. The provider closes the context; this only
468
- * tracks its pages and events, for as long as the surrounding scope is open. Each page's protocol
469
- * session, capture and listeners end when that page closes or when the scope does, so a closed
470
- * tab retains nothing and the context keeps none of them afterwards.
471
- */
472
- 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 = (
473
515
  context: BrowserContext,
474
- info: {
475
- readonly id: string;
476
- readonly provider: string;
477
- readonly expiresAt?: DateTime.Utc | undefined;
478
- /** Where pages' screencasts run, if not on each page's own session. */
479
- readonly capture?: CaptureSource | undefined;
480
- },
481
- 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,
482
560
  ) {
483
561
  const clock = yield* Clock.Clock;
484
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?.()));
485
567
  const now = () => BrowserClock.monotonicMillis(clock);
486
568
  const { settings, eventHistory, maxPages } = yield* settingsOf(options);
487
569
  // Measured on first need: the first capture of any page measures it, and input never waits.
@@ -492,16 +574,27 @@ export const make = Effect.fn("Browser.make")(function* (
492
574
  yield* Effect.addFinalizer(() => timeline.close);
493
575
  const publish = timeline.publish;
494
576
 
495
- if (info.expiresAt !== undefined)
496
- publish(new Events.SessionEnding({ at: now(), expiresAt: info.expiresAt }));
577
+ if (expiresAt !== undefined)
578
+ publish(new Events.SessionEnding({ at: now(), expiresAt: expiresAt }));
497
579
 
498
580
  const { lostBy, lost, lose, untilLost, native } = yield* watchLoss(
499
581
  context,
500
- info.expiresAt,
582
+ expiresAt,
501
583
  clock,
502
584
  (cause) => publish(new Events.Disconnected({ at: now(), cause })),
503
585
  );
504
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
+
505
598
  const inputGate = Gate.make({
506
599
  now,
507
600
  sequence: timeline.sequence,
@@ -511,9 +604,64 @@ export const make = Effect.fn("Browser.make")(function* (
511
604
  drain: settings.navigationTimeout,
512
605
  });
513
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
+
514
663
  const registry = new Map<PlaywrightPage, Page.Page>();
515
664
  const registrations: Openings.Registrations = new WeakMap();
516
- const registering = yield* Semaphore.make(1);
517
665
  // The pages' scopes close after the browser is marked released, so what fails as they close
518
666
  // says why.
519
667
  const pagesScope = yield* Scope.fork(yield* Scope.Scope);
@@ -526,131 +674,134 @@ export const make = Effect.fn("Browser.make")(function* (
526
674
  // fiber in a later turn, once Playwright has reported the context's.
527
675
  const closing = yield* closures(lostBy, publish, now);
528
676
 
529
- const register = (playwright: PlaywrightPage) =>
530
- registering.withPermits(1)(
531
- Effect.gen(function* () {
532
- const known = registry.get(playwright);
533
-
534
- if (known !== undefined) return known;
535
- if (playwright.isClosed())
536
- return yield* failWith("newPage", new Failed({ detail: "the page closed as it opened" }));
537
- const scope = yield* Scope.fork(pagesScope);
538
-
539
- return yield* Effect.gen(function* () {
540
- let crashed = false;
541
- const closedBy = () => lostBy() ?? (crashed ? "crashed" : "page");
542
- const cdp = yield* native("newPage", () => context.newCDPSession(playwright));
543
-
544
- yield* Effect.addFinalizer(() => release(() => cdp.detach()));
545
- // The page's name, its target id, costs one round trip, which the calls that keep it
546
- // painting behind other tabs and report its documents share. A renderer busy with its
547
- // first script answers those two late, so what needs them waits, and registering does not.
548
- const send: typeof cdp.send = (method, params) => untilLost(cdp.send(method, params));
549
- const focusing = sentNow(send("Emulation.setFocusEmulationEnabled", { enabled: true }));
550
- const paging = sentNow(send("Page.enable"));
551
- const { targetInfo } = yield* native("newPage", () => send("Target.getTargetInfo"));
552
- const id = targetInfo.targetId;
553
-
554
- const page = yield* PageImpl.make({
555
- id,
556
- session: info.id,
557
- connection,
558
- url: targetInfo.url,
559
- playwright,
560
- cdp,
561
- untilLost,
562
- settings,
563
- inputGate,
564
- clock,
565
- mapping,
566
- publish,
567
- recentEvents: eventsOf(timeline.recent, id),
568
- openings: yield* Openings.make(playwright, cdp, registrations, closedBy),
569
- focused: call("focus", () => focusing, closedBy).pipe(Effect.asVoid),
570
- paging: (operation) => call(operation, () => paging, closedBy).pipe(Effect.asVoid),
571
- closedBy,
572
- capture: info.capture,
573
- });
574
-
575
- const close = () => {
576
- if (registry.get(playwright) !== page) return;
577
- registry.delete(playwright);
578
- budget.makeRoom();
579
- Queue.offerUnsafe(closing, { scope, page: id, cause: crashed ? "crashed" : "page" });
580
- };
581
-
582
- // Playwright drives a crashed page no more and its calls never return, so it is closed:
583
- // they fail at once, `Closed` because it crashed.
584
- const crash = () => {
585
- crashed = true;
586
- void playwright.close().catch(() => undefined);
587
- };
588
-
589
- registry.set(playwright, page);
590
- publish(
591
- new Events.PageOpened({
592
- at: now(),
593
- page: id,
594
- url: Url.redact(targetInfo.url),
595
- opener: targetInfo.openerId,
596
- }),
597
- );
598
- yield* listen(playwright, id, publish, now, { close, crash });
599
- if (playwright.isClosed()) close();
600
-
601
- return page;
602
- }).pipe(
603
- Scope.provide(scope),
604
- 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
+ }),
605
751
  );
606
- }),
607
- );
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
+ });
608
783
 
609
784
  // Playwright registers its init scripts as it sets up each page, before a popup's first document
610
785
  // runs, and they cost no call per document.
611
786
  for (const script of options.initScripts ?? [])
612
787
  yield* native("initScripts", () => context.addInitScript({ content: scoped(script) }));
613
- yield* followOpened(context, register, publish, now, registrations);
614
- for (const existing of context.pages()) yield* register(existing);
615
-
616
- const pages = Effect.sync(() => [...registry.values()]);
617
-
618
- const newPage = Effect.fn("Browser.newPage")(function* (url?: string) {
619
- const page = yield* budget.open(
620
- native("newPage", () => context.newPage()).pipe(
621
- Effect.flatMap((playwright) =>
622
- register(playwright).pipe(Effect.onError(() => release(() => playwright.close()))),
623
- ),
624
- ),
625
- );
626
-
627
- // A rejected or interrupted navigation must not leave the newly allocated blank tab behind.
628
- if (url !== undefined)
629
- yield* page.goto(url).pipe(Effect.onError(() => page.close.pipe(Effect.ignore)));
788
+ const register = yield* followOpened(context, registrations, registerPage, publish, now);
630
789
 
631
- return page;
632
- });
790
+ for (const existing of context.pages()) yield* register(existing);
633
791
 
634
792
  // Added last, so it runs first as the owner's scope closes.
635
793
  yield* Effect.addFinalizer(() => Effect.sync(() => lose("released")));
636
794
 
637
795
  const service: Service = {
638
- id: info.id,
796
+ id: session,
639
797
  connection,
640
798
  provider: info.provider,
641
799
  expiresAt: info.expiresAt,
642
800
  now: Effect.sync(now),
643
801
  suspend: (options = {}) =>
644
802
  Effect.map(inputGate.suspend(options.drain), (held) => new Suspension(held)),
645
- context,
646
- pages,
647
- page: (id) =>
648
- Effect.map(pages, (open) => Option.fromNullishOr(open.find((page) => page.id === id))),
649
- firstPage: pages.pipe(
650
- Effect.map((open) => Option.fromNullishOr(open[0])),
651
- Effect.flatMap(Option.match({ onNone: () => newPage(), onSome: Effect.succeed })),
652
- ),
653
- newPage,
803
+ ...tabs(context, registry, budget, native, register, release, Semaphore.makeUnsafe(1)),
804
+ hasCookie: cookieQuery(context, native, settings.actionTimeout, clock),
654
805
  disconnected: lost,
655
806
  events: (eventOptions = {}) => timeline.stream(eventOptions.after),
656
807
  recentEvents: timeline.recent.pipe(