screw-bugs 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +906 -2
  3. package/bin/screw-bugs.js +29 -0
  4. package/dist/browser-playwright/annotate.d.ts +9 -0
  5. package/dist/browser-playwright/annotate.js +86 -0
  6. package/dist/browser-playwright/capture.d.ts +232 -0
  7. package/dist/browser-playwright/capture.js +1049 -0
  8. package/dist/browser-playwright/frames.d.ts +77 -0
  9. package/dist/browser-playwright/frames.js +191 -0
  10. package/dist/browser-playwright/index.d.ts +2 -0
  11. package/dist/browser-playwright/index.js +2 -0
  12. package/dist/browser-playwright/input.d.ts +44 -0
  13. package/dist/browser-playwright/input.js +116 -0
  14. package/dist/browser-playwright/launch.d.ts +21 -0
  15. package/dist/browser-playwright/launch.js +86 -0
  16. package/dist/browser-playwright/page.d.ts +387 -0
  17. package/dist/browser-playwright/page.js +1930 -0
  18. package/dist/build-info.json +5 -0
  19. package/dist/cli/app.d.ts +19 -0
  20. package/dist/cli/app.js +70 -0
  21. package/dist/cli/build-info.d.ts +52 -0
  22. package/dist/cli/build-info.js +82 -0
  23. package/dist/cli/commands.d.ts +14 -0
  24. package/dist/cli/commands.js +308 -0
  25. package/dist/cli/config.d.ts +16 -0
  26. package/dist/cli/config.js +71 -0
  27. package/dist/cli/doctor.d.ts +19 -0
  28. package/dist/cli/doctor.js +113 -0
  29. package/dist/cli/environment.d.ts +20 -0
  30. package/dist/cli/environment.js +34 -0
  31. package/dist/cli/exit-codes.d.ts +29 -0
  32. package/dist/cli/exit-codes.js +28 -0
  33. package/dist/cli/failure.d.ts +20 -0
  34. package/dist/cli/failure.js +15 -0
  35. package/dist/cli/index.d.ts +6 -0
  36. package/dist/cli/index.js +6 -0
  37. package/dist/cli/install-method.d.ts +96 -0
  38. package/dist/cli/install-method.js +148 -0
  39. package/dist/cli/main.d.ts +1 -0
  40. package/dist/cli/main.js +10 -0
  41. package/dist/cli/mcp.d.ts +30 -0
  42. package/dist/cli/mcp.js +309 -0
  43. package/dist/cli/node-version.d.ts +3 -0
  44. package/dist/cli/node-version.js +22 -0
  45. package/dist/cli/operations.d.ts +127 -0
  46. package/dist/cli/operations.js +337 -0
  47. package/dist/cli/package-info.d.ts +22 -0
  48. package/dist/cli/package-info.js +25 -0
  49. package/dist/cli/report-server.d.ts +170 -0
  50. package/dist/cli/report-server.js +387 -0
  51. package/dist/cli/signals.d.ts +37 -0
  52. package/dist/cli/signals.js +61 -0
  53. package/dist/cli/stamp-build.d.ts +1 -0
  54. package/dist/cli/stamp-build.js +9 -0
  55. package/dist/cli/update-check.d.ts +140 -0
  56. package/dist/cli/update-check.js +316 -0
  57. package/dist/cli/uploads.d.ts +16 -0
  58. package/dist/cli/uploads.js +80 -0
  59. package/dist/core/css.d.ts +95 -0
  60. package/dist/core/css.js +436 -0
  61. package/dist/core/engine.d.ts +65 -0
  62. package/dist/core/engine.js +436 -0
  63. package/dist/core/errors.d.ts +66 -0
  64. package/dist/core/errors.js +30 -0
  65. package/dist/core/evidence.d.ts +14 -0
  66. package/dist/core/evidence.js +127 -0
  67. package/dist/core/index.d.ts +12 -0
  68. package/dist/core/index.js +12 -0
  69. package/dist/core/labels.d.ts +47 -0
  70. package/dist/core/labels.js +199 -0
  71. package/dist/core/liveness.d.ts +45 -0
  72. package/dist/core/liveness.js +64 -0
  73. package/dist/core/marks.d.ts +63 -0
  74. package/dist/core/marks.js +410 -0
  75. package/dist/core/services.d.ts +444 -0
  76. package/dist/core/services.js +22 -0
  77. package/dist/core/steps.d.ts +96 -0
  78. package/dist/core/steps.js +656 -0
  79. package/dist/core/uploads.d.ts +49 -0
  80. package/dist/core/uploads.js +133 -0
  81. package/dist/core/video.d.ts +16 -0
  82. package/dist/core/video.js +101 -0
  83. package/dist/core/viewport.d.ts +28 -0
  84. package/dist/core/viewport.js +50 -0
  85. package/dist/report/html.d.ts +37 -0
  86. package/dist/report/html.js +762 -0
  87. package/dist/report/index.d.ts +5 -0
  88. package/dist/report/index.js +5 -0
  89. package/dist/report/markup.d.ts +27 -0
  90. package/dist/report/markup.js +75 -0
  91. package/dist/report/pr-summary.d.ts +11 -0
  92. package/dist/report/pr-summary.js +110 -0
  93. package/dist/report/sha256.d.ts +9 -0
  94. package/dist/report/sha256.js +97 -0
  95. package/dist/report/styles.d.ts +1 -0
  96. package/dist/report/styles.js +328 -0
  97. package/dist/report/view.d.ts +141 -0
  98. package/dist/report/view.js +368 -0
  99. package/dist/report/walkthrough.d.ts +75 -0
  100. package/dist/report/walkthrough.js +458 -0
  101. package/dist/schema/config.d.ts +7 -0
  102. package/dist/schema/config.js +6 -0
  103. package/dist/schema/doctor.d.ts +46 -0
  104. package/dist/schema/doctor.js +23 -0
  105. package/dist/schema/evidence.d.ts +994 -0
  106. package/dist/schema/evidence.js +521 -0
  107. package/dist/schema/findings.d.ts +159 -0
  108. package/dist/schema/findings.js +80 -0
  109. package/dist/schema/index.d.ts +7 -0
  110. package/dist/schema/index.js +7 -0
  111. package/dist/schema/job.d.ts +1724 -0
  112. package/dist/schema/job.js +505 -0
  113. package/dist/schema/ledger.d.ts +951 -0
  114. package/dist/schema/ledger.js +193 -0
  115. package/dist/schema/status.d.ts +7 -0
  116. package/dist/schema/status.js +11 -0
  117. package/dist/store-local/accounts.d.ts +7 -0
  118. package/dist/store-local/accounts.js +9 -0
  119. package/dist/store-local/index.d.ts +3 -0
  120. package/dist/store-local/index.js +3 -0
  121. package/dist/store-local/paths.d.ts +10 -0
  122. package/dist/store-local/paths.js +17 -0
  123. package/dist/store-local/storage.d.ts +20 -0
  124. package/dist/store-local/storage.js +170 -0
  125. package/package.json +73 -4
@@ -0,0 +1,1930 @@
1
+ import { Clock, Effect, Option, Schema } from 'effect';
2
+ import { devices, errors, } from 'playwright-core';
3
+ import { clampBox, describeFrames, describeTarget, layoutToScreen, PageActionFailed, refusedScheme, } from '../core/index.js';
4
+ import { AncestorNode, ATTR_VALUE_MAX, ATTRS_MAX, Box, CANDIDATES_MAX, Candidate, DEFAULT_LOAD_MS, DEFAULT_WAIT_MS, elementOf, FACT_FRAMES_MAX, FACT_TEXT_MAX, FRAME_CANDIDATES_MAX, FRAME_CANDIDATES_TOTAL, FACT_IMAGES_MAX, FACT_LINKS_MAX, FRAME_ANCESTORS_MAX, FRAMES_MAX, framesOf, ImageFact, LinkFact, HTTP_ERRORS_MAX, isWebUrl, NODES_MAX, PageNode, Truncated, URL_MAX, } from '../schema/index.js';
5
+ import { captureState, contentOf, findText, hasContent, mediaFacts, nearText, revealPage, } from './capture.js';
6
+ import { frameElementInfo, frameSelector, scrollDocument } from './frames.js';
7
+ import { INPUT_BINDING, INPUT_EVENTS, INPUT_WORLD, inputObserverSource } from './input.js';
8
+ /** Waiting for an element to appear before acting on it, unless the step gives `timeoutMs`. */
9
+ export const ACTION_TIMEOUT_MS = DEFAULT_WAIT_MS;
10
+ /**
11
+ * Loading a page: goto and reload wait up to its `load` event; any other page load gets this long
12
+ * from its start to its response. A step's `timeoutMs` changes it (see `loadTimeoutOf`).
13
+ */
14
+ export const NAVIGATION_TIMEOUT_MS = DEFAULT_LOAD_MS;
15
+ /** How long expectText and expectUrl wait for the page to get there, unless given `timeoutMs`. */
16
+ export const EXPECT_TIMEOUT_MS = DEFAULT_WAIT_MS;
17
+ export const SCREENSHOT_TIMEOUT_MS = 10_000;
18
+ /**
19
+ * How long a click or key press waits after it is dispatched, so that a navigation it causes
20
+ * starts while it is still the current step, such as a form that the Enter key submits.
21
+ */
22
+ export const NAVIGATION_START_MS = 250;
23
+ const seconds = (ms) => `${ms / 1000} s`;
24
+ /**
25
+ * The Playwright device profile behind `device: mobile`: an iPhone's viewport, user agent, pixel
26
+ * ratio and touch. We only launch Chromium-based browsers (never WebKit), so the page is still
27
+ * rendered by Chromium; this catches layout and touch problems, not Safari engine quirks.
28
+ */
29
+ export const MOBILE_DEVICE = 'iPhone 17';
30
+ /** The device as reports show it; the engine is named because mobile is not real Safari. */
31
+ export const deviceLabel = (device) => device === 'mobile' ? `${MOBILE_DEVICE} (Chromium)` : 'Desktop';
32
+ const contextOptions = (device) => device === 'mobile' ? devices[MOBILE_DEVICE] : { viewport: { width: 1280, height: 800 } };
33
+ /** Session videos fit in this box, keeping the viewport's shape, so files stay small. */
34
+ export const VIDEO_MAX = { width: 1280, height: 720 };
35
+ /** The size of a session's video for a viewport: the viewport, scaled down into `VIDEO_MAX`. */
36
+ export const videoSize = (viewport) => {
37
+ const scale = Math.min(1, VIDEO_MAX.width / viewport.width, VIDEO_MAX.height / viewport.height);
38
+ const even = (n) => Math.max(2, Math.floor((n * scale) / 2) * 2);
39
+ return { width: even(viewport.width), height: even(viewport.height) };
40
+ };
41
+ /** How long closing a session (and saving its video) may take. */
42
+ export const CLOSE_TIMEOUT_MS = 30_000;
43
+ /** How long measuring an element for a screenshot or reading page facts may take. */
44
+ export const MEASURE_TIMEOUT_MS = 1_000;
45
+ /** How long setting up the input observer (`watchInput`) or taking it down may take. */
46
+ export const INPUT_SETUP_TIMEOUT_MS = 2_000;
47
+ /** How long saving what a screenshot needs besides the image may take. */
48
+ export const CAPTURE_TIMEOUT_MS = 3_000;
49
+ /**
50
+ * Scrolling through a page before a full-page screenshot (see `revealPage`): at most this many
51
+ * viewports, this far apart, and this long in all, the last part of it for what the scrolling
52
+ * revealed to settle once the page is back where it was.
53
+ */
54
+ export const REVEAL = {
55
+ steps: 20,
56
+ stepMs: 120,
57
+ settleMs: 400,
58
+ budgetMs: 3_000,
59
+ };
60
+ /**
61
+ * Images whose alternative text contains `alt`, ignoring case: by their `alt` attribute or ARIA
62
+ * label, as `captureState` reads it, and by their accessible name as an image.
63
+ */
64
+ const imagesIn = (scope, alt) => {
65
+ const value = JSON.stringify(alt);
66
+ return scope
67
+ .locator([
68
+ `img[alt*=${value} i]`,
69
+ `area[alt*=${value} i]`,
70
+ `input[type=image][alt*=${value} i]`,
71
+ `[role=img][aria-label*=${value} i]`,
72
+ `svg[aria-label*=${value} i]`,
73
+ ].join(', '))
74
+ .or(scope.getByRole('img', { name: alt }));
75
+ };
76
+ /** Every element `target` matches in `scope`, visible or not, in page order. */
77
+ const matchesIn = (scope, target) => target.alt !== undefined
78
+ ? imagesIn(scope, target.alt)
79
+ : target.role !== undefined
80
+ ? scope.getByRole(target.role, target.name !== undefined ? { name: target.name } : {})
81
+ : target.text !== undefined
82
+ ? scope.getByText(target.text)
83
+ : target.label !== undefined
84
+ ? scope.getByLabel(target.label)
85
+ : scope.locator(target.css ?? '');
86
+ /**
87
+ * The document `frames` lead to, outermost first: each the first visible match of its target in
88
+ * the one before. Playwright reaches same- and cross-origin frames alike, and waits for each.
89
+ */
90
+ const scopeOf = (page, frames) => frames.reduce((scope, frame) => matchesIn(scope, frame).visible().first().contentFrame(), page);
91
+ /** Every element `target` matches, in its frame when it has one. */
92
+ const matches = (page, target) => matchesIn(scopeOf(page, framesOf(target.frame)), elementOf(target));
93
+ const locate = (page, target) => matches(page, target).visible().first();
94
+ /**
95
+ * Playwright messages carry call logs over several lines; only the first line is kept so a
96
+ * reason stays one short sentence.
97
+ */
98
+ const firstLine = (error) => (error instanceof Error ? error.message : String(error)).split('\n')[0].trim();
99
+ const isTimeout = (error) => error instanceof errors.TimeoutError;
100
+ /** Boundary: Playwright's API is promises; every call goes through here, as a PageActionFailed. */
101
+ const attempt = (run, describe) => Effect.tryPromise({
102
+ try: run,
103
+ catch: (error) => new PageActionFailed({ message: describe(error), cause: error }),
104
+ });
105
+ /** True when the wait succeeded, false when it timed out; any other failure stays a failure. */
106
+ const untilTimeout = (wait) => wait.pipe(Effect.as(true), Effect.catchIf((error) => isTimeout(error.cause), () => Effect.succeed(false)));
107
+ const REDIRECTS = new Set([301, 302, 303, 307, 308]);
108
+ /**
109
+ * Chromium's placeholder for a page or frame whose load failed, such as a port that refused the
110
+ * connection. It holds only Chromium's own error text, never anything off the machine, so it is
111
+ * not a refused URL.
112
+ */
113
+ const LOAD_ERROR_URL = 'chrome-error://chromewebdata/';
114
+ /**
115
+ * The scheme of a URL a page or frame must not show, or undefined when it may: http and https,
116
+ * `about:blank` (where every page and frame starts), Chromium's load-error placeholder, and, for
117
+ * a frame inside a page, `about:srcdoc` (an iframe whose HTML the page itself wrote).
118
+ */
119
+ const refusedIn = (url, child) => url === '' || url === LOAD_ERROR_URL || (child && url === 'about:srcdoc')
120
+ ? undefined
121
+ : refusedScheme(url);
122
+ /**
123
+ * Follows everything that navigates in the case's browser context: every page of the case (its
124
+ * own, and every popup or new tab), and every frame in them. Boundary: Playwright reports these
125
+ * through plain event callbacks.
126
+ *
127
+ * Loads: every main-frame document request, in any of the case's pages, is one load, recorded
128
+ * with the step during which it started. A redirect chain is one load, judged by the document
129
+ * it ends at. Same-document navigations (a hash, the history API) send no request, and
130
+ * subresources (images, XHR) and child frames are not main-frame documents, so none of them is
131
+ * a load. `settle` waits for loads and judges them:
132
+ * - A load is in flight from its request until its final response or its failure. It is waited
133
+ * for up to its step's load timeout from its start (`NAVIGATION_TIMEOUT_MS` unless the step gives
134
+ * `timeoutMs`); one still in flight then did not finish.
135
+ * - A final response of 400 or above is an HTTP error; any other response is fine. A failure
136
+ * reported after the response is ignored: the response already decided. That is how Chromium
137
+ * ends a download (a response with `content-disposition: attachment`, then `ERR_ABORTED`), so a
138
+ * download link does not count against the case, unless the server answered it with an error.
139
+ * - A failure without a response is a load that failed, such as a refused connection, except
140
+ * `net::ERR_ABORTED`: Chromium reports that when it cancels the navigation itself, because a
141
+ * newer navigation of the same frame replaced it, the page stopped it, or its tab closed. The
142
+ * site did not fail then. (Whether a newer navigation replaced it cannot be told reliably at
143
+ * that point: Chromium reports the abort before the newer request.)
144
+ *
145
+ * Refusals: every navigation of every frame in every page is checked against `refusedIn`. The
146
+ * scheme check of links before a click gives clearer reasons, but a page can change a link as
147
+ * it is clicked, navigate by script, or load a frame, so this is the check that holds. `javascript:`
148
+ * URLs never show up here: a link or frame with one runs it as the page's own script, without
149
+ * navigating, the same as any other script the page runs. That is not a way off the web, so it is
150
+ * not blocked.
151
+ */
152
+ const watchContext = (context, page, clock) => {
153
+ /** Loads since the last settle, by the first request of their redirect chain. */
154
+ let loads = new Map();
155
+ let step = 0;
156
+ /** How long loads of `step` may take. */
157
+ let stepTimeoutMs = NAVIGATION_TIMEOUT_MS;
158
+ /** How many loads have ended so far, so a wait cannot miss one that ends as it starts. */
159
+ let endings = 0;
160
+ let refused;
161
+ let waiters = [];
162
+ /** Responses with an HTTP error status in this case, documents or not; a fact, not a verdict. */
163
+ let httpErrors = [];
164
+ const firstOf = (request) => {
165
+ let first = request;
166
+ for (let from = first.redirectedFrom(); from; from = from.redirectedFrom())
167
+ first = from;
168
+ return first;
169
+ };
170
+ /** Whether a request loads a document of the case's page, of another page, or neither. */
171
+ const kindOf = (request) => {
172
+ if (!request.isNavigationRequest())
173
+ return undefined;
174
+ let frame;
175
+ try {
176
+ frame = request.frame();
177
+ }
178
+ catch {
179
+ // No frame yet: a new page's first document, unless it comes from a service worker.
180
+ return request.serviceWorker() === null ? 'popup' : undefined;
181
+ }
182
+ if (frame === page.mainFrame())
183
+ return 'page';
184
+ return frame === frame.page().mainFrame() ? 'popup' : undefined;
185
+ };
186
+ const ended = (request, outcome) => {
187
+ const load = loads.get(firstOf(request));
188
+ if (load === undefined || load.outcome !== undefined)
189
+ return;
190
+ load.outcome = outcome;
191
+ endings++;
192
+ const waiting = waiters;
193
+ waiters = [];
194
+ waiting.forEach((w) => w());
195
+ };
196
+ context.on('request', (request) => {
197
+ const kind = kindOf(request);
198
+ const first = firstOf(request);
199
+ if (kind === undefined || loads.has(first))
200
+ return;
201
+ loads.set(first, {
202
+ step,
203
+ inNewTab: kind === 'popup',
204
+ startedAt: clock.currentTimeMillisUnsafe(),
205
+ timeoutMs: stepTimeoutMs,
206
+ outcome: undefined,
207
+ });
208
+ });
209
+ context.on('response', (response) => {
210
+ const url = response.url();
211
+ if (response.status() >= 400 && httpErrors.length < HTTP_ERRORS_MAX && isWebUrl(url))
212
+ httpErrors.push({ url: url.slice(0, 300), status: response.status() });
213
+ // The redirect's target is requested next; only the document it ends at counts.
214
+ if (REDIRECTS.has(response.status()))
215
+ return;
216
+ ended(response.request(), { status: response.status() });
217
+ });
218
+ context.on('requestfailed', (request) => {
219
+ const error = request.failure()?.errorText ?? 'unknown error';
220
+ ended(request, error === 'net::ERR_ABORTED' ? 'ignored' : { error });
221
+ });
222
+ const check = (frame, where) => {
223
+ if (refused !== undefined)
224
+ return;
225
+ const child = frame.parentFrame() !== null;
226
+ const scheme = refusedIn(frame.url(), child);
227
+ if (scheme !== undefined)
228
+ refused = { scheme, where: child ? 'frame' : where };
229
+ };
230
+ const watchPage = (watched, where) => {
231
+ watched.on('framenavigated', (frame) => check(frame, where));
232
+ // A new page may have navigated before it was handed over.
233
+ for (const frame of watched.frames())
234
+ check(frame, where);
235
+ };
236
+ watchPage(page, 'page');
237
+ context.on('page', (opened) => {
238
+ if (opened !== page)
239
+ watchPage(opened, 'window');
240
+ });
241
+ /** The earliest time a load still in flight runs out of time, if one is in flight. */
242
+ const nextDeadline = () => {
243
+ const now = clock.currentTimeMillisUnsafe();
244
+ let deadline;
245
+ for (const load of loads.values()) {
246
+ const end = load.startedAt + load.timeoutMs;
247
+ if (load.outcome === undefined && end > now)
248
+ deadline = Math.min(deadline ?? end, end);
249
+ }
250
+ return deadline === undefined ? undefined : deadline - now;
251
+ };
252
+ /** Resumes when a load ends, or at once if one has since `seen` endings. */
253
+ const anyEnds = (seen) => Effect.callback((resume) => {
254
+ const wake = () => resume(Effect.void);
255
+ if (endings !== seen)
256
+ return wake();
257
+ waiters.push(wake);
258
+ return Effect.sync(() => {
259
+ waiters = waiters.filter((w) => w !== wake);
260
+ });
261
+ });
262
+ const problemOf = (load) => {
263
+ const { outcome } = load;
264
+ const base = { step: load.step, inNewTab: load.inNewTab };
265
+ if (outcome === undefined)
266
+ return { ...base, _tag: 'Unfinished', timeoutMs: load.timeoutMs };
267
+ if (outcome === 'ignored')
268
+ return undefined;
269
+ if ('error' in outcome)
270
+ return { ...base, _tag: 'LoadFailed', error: outcome.error };
271
+ return outcome.status >= 400
272
+ ? { ...base, _tag: 'HttpError', status: outcome.status }
273
+ : undefined;
274
+ };
275
+ return {
276
+ settle: (next, loadTimeoutMs) => Effect.gen(function* () {
277
+ for (let wait = nextDeadline(); wait !== undefined; wait = nextDeadline())
278
+ yield* Effect.timeoutOption(anyEnds(endings), wait);
279
+ // From the last check on, this runs without yielding: no load can start in between.
280
+ const judged = [...loads.values()];
281
+ loads = new Map();
282
+ step = next;
283
+ stepTimeoutMs = loadTimeoutMs;
284
+ let first;
285
+ for (const load of judged) {
286
+ const problem = problemOf(load);
287
+ if (problem !== undefined && (first === undefined || problem.step < first.step))
288
+ first = problem;
289
+ }
290
+ return first;
291
+ }),
292
+ refused: Effect.sync(() => refused),
293
+ httpErrors: () => httpErrors,
294
+ /**
295
+ * Forgets everything of the last case: its loads (one still going is no longer judged), where
296
+ * it went and its HTTP errors. Loads from now on are the new case's step 0. With `keepRefused`,
297
+ * a way off the web it took is kept, for a case that goes on from its page.
298
+ */
299
+ reset: (keepRefused = false) => {
300
+ loads = new Map();
301
+ step = 0;
302
+ stepTimeoutMs = NAVIGATION_TIMEOUT_MS;
303
+ if (!keepRefused)
304
+ refused = undefined;
305
+ httpErrors = [];
306
+ },
307
+ };
308
+ };
309
+ /** Width and height of a PNG, from its header. */
310
+ export const pngSize = (bytes) => {
311
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
312
+ return bytes.byteLength >= 24
313
+ ? { width: view.getUint32(16), height: view.getUint32(20) }
314
+ : { width: 0, height: 0 };
315
+ };
316
+ const scaled = (box, scale) => ({
317
+ x: box.x * scale,
318
+ y: box.y * scale,
319
+ width: box.width * scale,
320
+ height: box.height * scale,
321
+ });
322
+ /** Gives up on `effect` after `ms`, with undefined. Page scripts have no timeout of their own. */
323
+ const within = (ms, effect) => effect.pipe(Effect.timeoutOption(ms), Effect.map((value) => (value._tag === 'Some' ? value.value : undefined)), Effect.orElseSucceed(() => undefined));
324
+ /** The part of `box` inside every clip, or undefined when none of it is. */
325
+ const intersect = (box, ...clips) => {
326
+ let [x, y] = [box.x, box.y];
327
+ let [right, bottom] = [box.x + box.width, box.y + box.height];
328
+ for (const clip of clips) {
329
+ [x, y] = [Math.max(x, clip.x), Math.max(y, clip.y)];
330
+ right = Math.min(right, clip.x + clip.width);
331
+ bottom = Math.min(bottom, clip.y + clip.height);
332
+ }
333
+ return right > x && bottom > y ? { x, y, width: right - x, height: bottom - y } : undefined;
334
+ };
335
+ /** What `captureState` saves of each document for CSS selectors in highlights. */
336
+ const SELECTOR_STATE = {
337
+ attrsMax: ATTRS_MAX,
338
+ attrValueMax: ATTR_VALUE_MAX,
339
+ nodesMax: NODES_MAX,
340
+ };
341
+ /** A box around any page, for frames wherever they are (finite, so its edges add up). */
342
+ const EVERYWHERE = { x: -1e9, y: -1e9, width: 2e9, height: 2e9 };
343
+ /** How long reading the frames of a screenshot may take, all together. */
344
+ export const FRAMES_TIMEOUT_MS = 4_000;
345
+ /** Below this opacity, with that of what is around it, an element is not seen (as in `captureState`). */
346
+ const SEEN_OPACITY = 0.1;
347
+ /*
348
+ * Numbers as page functions give them. Playwright carries NaN and ±Infinity across, and
349
+ * `Schema.Number` lets them through, so these are finite; sizes are not negative and a scale is
350
+ * above 0. What does not fit fails to decode, as any other answer that does not fit.
351
+ */
352
+ const PageNumber = Schema.Finite;
353
+ const PageSize = Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0));
354
+ const PageScale = Schema.Finite.check(Schema.isGreaterThan(0));
355
+ /** A box a page function gives, in CSS pixels: the stored `Box`, held to finite numbers. */
356
+ export const PageBox = Schema.Struct({
357
+ x: PageNumber,
358
+ y: PageNumber,
359
+ width: PageSize,
360
+ height: PageSize,
361
+ });
362
+ /** A trusted input event the main frame's page got, as `observeInput` reports it. */
363
+ export const Dispatched = Schema.Struct({
364
+ type: Schema.Literals(INPUT_EVENTS),
365
+ /** When the browser dispatched it to the page, in ms since the epoch. */
366
+ at: PageNumber,
367
+ /** A mouse press's `screenX` and `screenY`: where it pressed on the screen (see `framePoint`). */
368
+ x: Schema.optionalKey(PageNumber),
369
+ y: Schema.optionalKey(PageNumber),
370
+ /** Its `clientX` and `clientY`: the same point in the page's layout viewport. */
371
+ clientX: Schema.optionalKey(PageNumber),
372
+ clientY: Schema.optionalKey(PageNumber),
373
+ /** The visual viewport's `scale` then: screen pixels per layout pixel. */
374
+ scale: Schema.optionalKey(PageNumber),
375
+ /** The window's `screenX` and `screenY` then: where the widget is on the screen. */
376
+ windowX: Schema.optionalKey(PageNumber),
377
+ windowY: Schema.optionalKey(PageNumber),
378
+ });
379
+ const dispatchedOf = Schema.decodeUnknownOption(Schema.fromJsonString(Dispatched));
380
+ /** How far, in CSS pixels, a press may be outside where `framePoint` can place it. */
381
+ const FRAME_SLACK_PX = 1;
382
+ /**
383
+ * Where a mouse press shows in the video, in CSS pixels of `viewport` (the size Playwright set,
384
+ * which the video shows whole); undefined unless that is certain.
385
+ *
386
+ * On a desktop, where nothing but pinch zoom scales the page, the visual viewport is the layout
387
+ * one whenever its `scale` is 1: they are the same size, so it cannot be moved inside it. Then
388
+ * the press is at its `clientX` and `clientY`, the point in the layout viewport, when that is
389
+ * inside the frame. Zoomed (by CDP's `Emulation.setPageScaleFactor`, say), it is not certain.
390
+ *
391
+ * On a phone, not `clientX` and `clientY`: those are in the page's layout viewport, while the
392
+ * video shows the visual viewport, scaled to fill the frame and moved by pinch zoom. A page
393
+ * without a viewport meta tag is laid out 980 wide and shown at 0.41, so a press at `clientX` 250
394
+ * is 25% across the video, not 62%. Measuring the visual viewport (`visualViewport.offsetLeft`,
395
+ * CDP's `Page.getLayoutMetrics`) brings the page's style and layout up to date, which a page can
396
+ * notice (see `observeInput`), so it is not measured. The event's `screenX` and `screenY` are the
397
+ * point on the screen, in CSS pixels: the browser fixed them when it made the event from
398
+ * Playwright's input. They are the point on the frame when the browser draws the page on a widget
399
+ * at the screen's origin with nothing above it (`atOrigin`; the window's own `screenX` and
400
+ * `screenY` are 0 then), and the press is inside the frame.
401
+ *
402
+ * Checked against the layout point: the visual viewport is never left of or above the layout one,
403
+ * so `clientX - x / scale`, its offset, is at least 0, and so is `clientY - y / scale`. A screen
404
+ * point that is not on the widget (a window with the browser's toolbar above the page) fails that
405
+ * when the page is not moved. Device pixels play no part: `screenX` is in CSS pixels at any device
406
+ * scale.
407
+ *
408
+ * Never on a phone in a browser with windows of its own: headed, or Chrome's and Edge's headless
409
+ * mode, which lays its windows out as headed. A window has the browser's toolbars above the page,
410
+ * so `screenY` is that much below the frame's point, and a page whose visual viewport is moved
411
+ * down passes the check all the same (tested: zoomed in twice and moved to 30,100, a press shows
412
+ * 87 px above where `screenY` has it). In Chrome's headless mode the window is also moved (tested
413
+ * on Linux: to 10,10), while a phone's emulation still says 0,0. Nothing on the event tells these apart, so a phone in
414
+ * such a browser records no point.
415
+ */
416
+ export const framePoint = (dispatched, viewport, drawn) => {
417
+ const { x, y, clientX, clientY, scale, windowX, windowY } = dispatched;
418
+ if (clientX === undefined || clientY === undefined || scale === undefined || scale <= 0)
419
+ return undefined;
420
+ const inside = (n, size) => n >= -FRAME_SLACK_PX && n <= size + FRAME_SLACK_PX;
421
+ const onFrame = (px, py) => inside(px, viewport.width) && inside(py, viewport.height) ? { x: px, y: py } : undefined;
422
+ if (!drawn.mobile)
423
+ return scale === 1 ? onFrame(clientX, clientY) : undefined;
424
+ if (!drawn.atOrigin ||
425
+ x === undefined ||
426
+ y === undefined ||
427
+ windowX !== 0 ||
428
+ windowY !== 0 ||
429
+ clientX - x / scale < -FRAME_SLACK_PX ||
430
+ clientY - y / scale < -FRAME_SLACK_PX)
431
+ return undefined;
432
+ return onFrame(x, y);
433
+ };
434
+ const BrowserVersion = Schema.Struct({ product: Schema.String });
435
+ /**
436
+ * Whether `browser` draws its pages on a widget at the screen's origin with nothing above it:
437
+ * Chromium's headless shell, which Playwright runs headless when no channel is given, and which
438
+ * names itself `HeadlessChrome` in CDP's `Browser.getVersion`. Any other browser has windows:
439
+ * Chrome and Chromium, headed or in their headless mode, name themselves `Chrome`. False when it
440
+ * cannot be told.
441
+ */
442
+ export const widgetAtOrigin = (browser) => within(INPUT_SETUP_TIMEOUT_MS,
443
+ // Boundary: Playwright's CDP session is promises.
444
+ attempt(async () => {
445
+ const cdp = await browser.newBrowserCDPSession();
446
+ try {
447
+ return await cdp.send('Browser.getVersion');
448
+ }
449
+ finally {
450
+ await cdp.detach().catch(() => undefined);
451
+ }
452
+ }, firstLine)).pipe(Effect.map((version) => Option.match(Schema.decodeUnknownOption(BrowserVersion)(version), {
453
+ onNone: () => false,
454
+ onSome: ({ product }) => product.startsWith('HeadlessChrome/'),
455
+ })));
456
+ /**
457
+ * The visual viewport a screenshot's boxes can be placed with (see `VisualViewport`): the one
458
+ * `captureState` measured with the page's own boxes (`seen`), when the page still showed at its
459
+ * scale once every box was measured (`scaleNow`), so the page was not zoomed meanwhile. A
460
+ * full-page screenshot shows the layout itself, where boxes measured from the visual viewport's
461
+ * top left (`boundingBox`'s) are where they are only when it is at the layout's: so only when it
462
+ * shows all of the layout's width and height at once, at a scale of at most 1. Else undefined:
463
+ * where the boxes show cannot be told for sure.
464
+ */
465
+ export const visualOf = (seen, scaleNow, fullPage) => {
466
+ if (seen === undefined || scaleNow === undefined || scaleNow !== seen.scale)
467
+ return undefined;
468
+ if (fullPage && (seen.scale > 1 || seen.x !== 0 || seen.y !== 0))
469
+ return undefined;
470
+ return seen;
471
+ };
472
+ /**
473
+ * How much earlier than the action's start an event may be dispatched and still be the action's:
474
+ * the page's clock and this process's are the same system clock, read in whole milliseconds.
475
+ */
476
+ const STAMP_SLACK_MS = 1;
477
+ /** An `InputWatch` that sees nothing: every action is recorded without a time or a point. */
478
+ const unobserved = {
479
+ during: (_types, act) => Effect.map(act, (value) => ({ value, dispatched: Effect.succeed(undefined) })),
480
+ };
481
+ /**
482
+ * Watches the trusted input events the browser dispatches to `page`'s main frame, from where no
483
+ * page script can see it: `observeInput`, set up by CDP in an isolated world of every document
484
+ * the page loads (and the one it has now), reporting through a binding only that world has. So
485
+ * where and when an action happened is the event the browser actually dispatched for it, not a
486
+ * guess from measuring the page around it. An action takes the first event of its types that
487
+ * came while it ran: only a mouse press or a key going down, which nothing but Playwright's real
488
+ * input makes trusted (see `INPUT_EVENTS`), so whatever the page's own timers do meanwhile cannot
489
+ * be taken for it. Child frames, a document a page rewrites with
490
+ * `document.open` (which removes every listener of its window) and browsers without CDP report
491
+ * nothing, and so do actions there.
492
+ *
493
+ * An event comes in after the action that sent it may have returned: Playwright's input returns
494
+ * when the browser acknowledges it on Playwright's own CDP session, while the binding call comes
495
+ * from the page's renderer on this one, and the two are not ordered (under load the call came in
496
+ * after a click had returned). So an action's watcher stays open, taking only events dispatched
497
+ * while the action ran, until a call this session sends to the renderer afterwards is answered:
498
+ * the renderer answers on the same channel it reports binding calls on, after every report it
499
+ * sent before. That waits on nothing: the step reads its event after its pause, and an event
500
+ * still not in then is not recorded.
501
+ *
502
+ * Setting up never fails the session: without it, every action reports nothing. The CDP session
503
+ * is let go of when the scope closes, before the session's context is.
504
+ */
505
+ const watchInput = (page) => Effect.gen(function* () {
506
+ const watchers = new Set();
507
+ // Boundary: CDP reports binding calls through an event callback. It only reads and records.
508
+ const heard = (event) => {
509
+ if (event.name !== INPUT_BINDING || watchers.size === 0)
510
+ return;
511
+ const dispatched = Option.getOrUndefined(dispatchedOf(event.payload));
512
+ if (dispatched === undefined)
513
+ return;
514
+ for (const watcher of watchers)
515
+ if (watcher.first === undefined &&
516
+ watcher.types.has(dispatched.type) &&
517
+ dispatched.at >= watcher.since - STAMP_SLACK_MS &&
518
+ dispatched.at <= watcher.until + STAMP_SLACK_MS)
519
+ watcher.first = dispatched;
520
+ };
521
+ const scope = yield* Effect.scope;
522
+ /** The session set up, once it is. */
523
+ let watching;
524
+ yield* Effect.gen(function* () {
525
+ const session = yield* Effect.acquireRelease(attempt(() => page.context().newCDPSession(page), firstLine), (session) => within(INPUT_SETUP_TIMEOUT_MS, Effect.sync(() => session.off('Runtime.bindingCalled', heard)).pipe(Effect.andThen(attempt(() => session.detach(), firstLine)))));
526
+ session.on('Runtime.bindingCalled', heard);
527
+ // The binding first, so the world has it from the start. Its calls are reported only
528
+ // with `Runtime.enable`, and this session's scripts run in new documents only with
529
+ // `Page.enable`; Playwright's own session has both on already.
530
+ yield* attempt(() => session.send('Runtime.enable'), firstLine);
531
+ yield* attempt(() => session.send('Runtime.addBinding', {
532
+ name: INPUT_BINDING,
533
+ executionContextName: INPUT_WORLD,
534
+ }), firstLine);
535
+ yield* attempt(() => session.send('Page.enable'), firstLine);
536
+ yield* attempt(() => session.send('Page.addScriptToEvaluateOnNewDocument', {
537
+ source: inputObserverSource,
538
+ worldName: INPUT_WORLD,
539
+ runImmediately: true,
540
+ }), firstLine);
541
+ watching = session;
542
+ }).pipe(Effect.timeoutOption(INPUT_SETUP_TIMEOUT_MS), Effect.ignore);
543
+ return {
544
+ during: (types, act) => Effect.gen(function* () {
545
+ const watcher = {
546
+ types,
547
+ since: yield* Clock.currentTimeMillis,
548
+ until: Infinity,
549
+ first: undefined,
550
+ };
551
+ const session = watching;
552
+ // Answered once every binding call the renderer sent before it has come in.
553
+ const caughtUp = session === undefined
554
+ ? Effect.void
555
+ : within(INPUT_SETUP_TIMEOUT_MS, attempt(() => session.send('Runtime.getIsolateId'), firstLine));
556
+ const value = yield* Effect.acquireUseRelease(Effect.sync(() => watchers.add(watcher)), () => act, () => Effect.gen(function* () {
557
+ watcher.until = yield* Clock.currentTimeMillis;
558
+ yield* caughtUp.pipe(Effect.ensuring(Effect.sync(() => watchers.delete(watcher))), Effect.forkIn(scope));
559
+ }));
560
+ return { value, dispatched: Effect.sync(() => watcher.first) };
561
+ }),
562
+ };
563
+ });
564
+ /** A candidate as `captureState` gives it: its boxes are `PageBox`es. */
565
+ const PageCandidate = Schema.Struct({
566
+ ...Candidate.fields,
567
+ box: PageBox,
568
+ content: Schema.optionalKey(PageBox),
569
+ });
570
+ /** An image fact as `mediaFacts` gives it: its size is finite. */
571
+ const PageImageFact = Schema.Struct({ ...ImageFact.fields, width: PageSize, height: PageSize });
572
+ /** What `frameElementInfo` gives, decoded as it comes back from the page (see `FrameElementInfo`). */
573
+ export const FrameInfo = Schema.Struct({
574
+ ...AncestorNode.fields,
575
+ role: Schema.optionalKey(Schema.String),
576
+ name: Schema.optionalKey(Schema.String),
577
+ ancestors: Schema.Array(AncestorNode),
578
+ moreAncestors: Schema.optionalKey(Schema.Boolean),
579
+ visible: Schema.Boolean,
580
+ opacity: PageSize,
581
+ clip: Schema.optionalKey(PageBox),
582
+ left: PageNumber,
583
+ top: PageNumber,
584
+ width: PageSize,
585
+ height: PageSize,
586
+ offsetWidth: PageSize,
587
+ offsetHeight: PageSize,
588
+ });
589
+ /**
590
+ * The frames visible in the page, outer ones before those inside them, at most `max`, each
591
+ * shown at least partly inside `view` (CSS pixels of the main viewport) and the frames around
592
+ * it; with how many there were in all. A frame whose element cannot be read, or whose description
593
+ * does not decode, is left out, and counted in `unread`.
594
+ *
595
+ * Boxes are as Playwright's `boundingBox` gives them: from the top left of the visual viewport, in
596
+ * CSS pixels of the page's layout. `origin` is where the visual viewport is in the layout viewport
597
+ * (see `VisualViewport`), which what clips a frame in the page itself is measured from; on a
598
+ * desktop, and on a phone that shows the whole layout, it is at the layout's top left.
599
+ */
600
+ const visibleFrames = (page, view, max, scope, origin = { x: 0, y: 0 }) => Effect.gen(function* () {
601
+ const listed = [];
602
+ let found = 0;
603
+ let kept = 0;
604
+ /** The frames above `scope.root`, which lead to it: measured, but not counted or kept. */
605
+ const above = new Set();
606
+ for (let up = scope?.root.parentFrame() ?? null; up; up = up.parentFrame())
607
+ above.add(up);
608
+ /**
609
+ * Frames whose element could not be read, so whether they show anything is unknown, with the
610
+ * listed frame they are in (undefined for the page itself).
611
+ */
612
+ const unread = [];
613
+ /**
614
+ * `path`: `frame` is above the scope, so only the frame that leads to it is looked at; `root`:
615
+ * it holds the scope, so only frames inside the scope's element are; `in`: it is inside.
616
+ */
617
+ const visit = (frame, parent, clip, mode) => Effect.gen(function* () {
618
+ for (const child of frame.childFrames()) {
619
+ if (mode === 'path' && child !== scope?.root && !above.has(child))
620
+ continue;
621
+ if (mode === 'root' && scope !== undefined) {
622
+ const inside = yield* scope.holds(child);
623
+ if (inside === undefined)
624
+ unread.push({ frame: child, parent });
625
+ if (inside !== true)
626
+ continue;
627
+ }
628
+ const counts = mode !== 'path';
629
+ const next = mode === 'path' ? (child === scope?.root ? 'root' : 'path') : 'in';
630
+ const read = yield* within(MEASURE_TIMEOUT_MS, attempt(async () => {
631
+ const handle = await child.frameElement();
632
+ try {
633
+ // Decoded here, between the two calls on the handle; one that does not fit throws.
634
+ const info = Schema.decodeUnknownSync(FrameInfo)(await handle.evaluate(frameElementInfo, {
635
+ attrsMax: ATTRS_MAX,
636
+ attrValueMax: ATTR_VALUE_MAX,
637
+ ancestorsMax: FRAME_ANCESTORS_MAX,
638
+ }));
639
+ return { info, box: info.visible ? await handle.boundingBox() : null };
640
+ }
641
+ finally {
642
+ await handle.dispose();
643
+ }
644
+ }, firstLine));
645
+ if (read === undefined) {
646
+ unread.push({ frame: child, parent });
647
+ continue;
648
+ }
649
+ if (read.box === null)
650
+ continue;
651
+ const { info, box } = read;
652
+ const sx = info.offsetWidth > 0 ? box.width / info.offsetWidth : 1;
653
+ const sy = info.offsetHeight > 0 ? box.height / info.offsetHeight : 1;
654
+ const content = {
655
+ x: box.x + info.left * sx,
656
+ y: box.y + info.top * sy,
657
+ width: info.width * sx,
658
+ height: info.height * sy,
659
+ };
660
+ // What clips the `<iframe>` is in its own document's viewport: the one of the frame it
661
+ // is in, which shows at that frame's `content`, scaled as it is.
662
+ const outer = parent === undefined ? undefined : listed[parent];
663
+ const own = info.clip === undefined
664
+ ? undefined
665
+ : outer === undefined
666
+ ? { ...info.clip, x: info.clip.x - origin.x, y: info.clip.y - origin.y }
667
+ : {
668
+ x: outer.content.x + info.clip.x * outer.sx,
669
+ y: outer.content.y + info.clip.y * outer.sy,
670
+ width: info.clip.width * outer.sx,
671
+ height: info.clip.height * outer.sy,
672
+ };
673
+ const cut = own === undefined
674
+ ? outer?.cut
675
+ : outer?.cut === undefined
676
+ ? own
677
+ : (intersect(own, outer.cut) ?? { ...own, width: 0, height: 0 });
678
+ const shown = intersect(content, clip, ...(cut === undefined ? [] : [cut]));
679
+ if (shown === undefined)
680
+ continue;
681
+ if (counts) {
682
+ found++;
683
+ if (kept >= max)
684
+ continue;
685
+ kept++;
686
+ }
687
+ const element = {
688
+ tag: info.tag,
689
+ ...(info.role !== undefined ? { role: info.role } : {}),
690
+ ...(info.name !== undefined ? { name: info.name } : {}),
691
+ ...(info.id !== undefined ? { id: info.id } : {}),
692
+ ...(info.classes !== undefined ? { classes: info.classes } : {}),
693
+ ...(info.testId !== undefined ? { testId: info.testId } : {}),
694
+ ...(info.attrs !== undefined ? { attrs: info.attrs } : {}),
695
+ ...(info.cutAttrs !== undefined ? { cutAttrs: info.cutAttrs } : {}),
696
+ ...(info.omittedAttrs !== undefined ? { omittedAttrs: info.omittedAttrs } : {}),
697
+ ...(info.moreAttrs === true ? { moreAttrs: true } : {}),
698
+ ...(info.moreClasses === true ? { moreClasses: true } : {}),
699
+ ...(info.foreign === true ? { foreign: true } : {}),
700
+ ...(info.ancestors.length > 0 ? { ancestors: info.ancestors } : {}),
701
+ ...(info.moreAncestors === true ? { moreAncestors: true } : {}),
702
+ };
703
+ const opacity = (outer?.opacity ?? 1) * info.opacity;
704
+ listed.push({
705
+ frame: child,
706
+ parent,
707
+ element,
708
+ content,
709
+ shown,
710
+ cut,
711
+ opacity,
712
+ sx,
713
+ sy,
714
+ inScope: counts,
715
+ });
716
+ yield* visit(child, listed.length - 1, shown, next);
717
+ }
718
+ });
719
+ const main = page.mainFrame();
720
+ yield* visit(main, undefined, view, scope === undefined ? 'in' : scope.root === main ? 'root' : 'path');
721
+ return { listed, found: found, kept, unread };
722
+ });
723
+ /** The frames that lead to a listed one, outermost first, each as a person names it. */
724
+ const framePath = (listed, index) => Effect.gen(function* () {
725
+ const path = [];
726
+ for (let at = index; at !== undefined; at = listed[at].parent) {
727
+ const frame = listed[at].frame;
728
+ const css = yield* attempt(async () => {
729
+ const handle = await frame.frameElement();
730
+ try {
731
+ return Schema.decodeUnknownSync(Schema.String)(await handle.evaluate(frameSelector));
732
+ }
733
+ finally {
734
+ await handle.dispose();
735
+ }
736
+ }, firstLine);
737
+ path.unshift({ css });
738
+ }
739
+ return path;
740
+ });
741
+ /** How often `watchText` looks again, while it waits and while it watches. */
742
+ export const WATCH_POLL_MS = 200;
743
+ /**
744
+ * The most frames `watchText` reads where it looks; where more show, it cannot be told free of a
745
+ * text. It lists at most `FRAMES_LISTED_MAX` frames of the page to tell which those are.
746
+ */
747
+ export const ABSENCE_FRAMES_MAX = 20;
748
+ export const FRAMES_LISTED_MAX = 200;
749
+ /**
750
+ * A frame that shows less than this many CSS pixels both across and down, where it shows (a 1×1
751
+ * tracking pixel), is read like any other, but when it cannot be read or stays empty, that
752
+ * blocks nothing: it cannot show text a person can read.
753
+ */
754
+ export const READABLE_FRAME_PX = 16;
755
+ /** How long reading the closed shadow roots of one look may take, all together. */
756
+ export const CLOSED_ROOTS_TIMEOUT_MS = 3_000;
757
+ /**
758
+ * The longest one look's read of closed shadow roots may take once `watchText` reads them on every
759
+ * look: past it, they cannot be watched as closely as the rest, so the check is blocked.
760
+ */
761
+ export const CLOSED_POLL_BUDGET_MS = 1_000;
762
+ /** Decodes what a page function or CDP gave with `schema`; what does not decode fails. */
763
+ const decodedAs = (schema) => (effect) => effect.pipe(Effect.flatMap((value) => Schema.decodeUnknownEffect(schema)(value).pipe(Effect.mapError((error) => new PageActionFailed({
764
+ message: `The page gave an answer that does not fit: ${error.message}`,
765
+ })))));
766
+ /** How long `watchText` remembers whether an empty document's closed shadow roots show anything. */
767
+ export const CLOSED_SHOWS_MS = 1_000;
768
+ const CdpNode = Schema.Struct({
769
+ backendNodeId: Schema.Number,
770
+ shadowRootType: Schema.optionalKey(Schema.String),
771
+ children: Schema.optionalKey(Schema.Array(Schema.suspend(() => CdpNode))),
772
+ shadowRoots: Schema.optionalKey(Schema.Array(Schema.suspend(() => CdpNode))),
773
+ contentDocument: Schema.optionalKey(Schema.suspend(() => CdpNode)),
774
+ });
775
+ /** CDP's answers, decoded: they are outside input like any other. */
776
+ export const CdpDocument = Schema.Struct({ root: CdpNode });
777
+ const CdpResolved = Schema.Struct({ object: Schema.Struct({ objectId: Schema.String }) });
778
+ /** What `findText` gives, decoded as it comes back from the page. */
779
+ const FoundFields = {
780
+ as: Schema.Literals(['text', 'alt', 'label']),
781
+ value: Schema.String,
782
+ near: Schema.optionalKey(Schema.String),
783
+ };
784
+ const TextSearchResult = Schema.Union([
785
+ Schema.Struct({ _tag: Schema.Literal('found'), ...FoundFields }),
786
+ Schema.Struct({ _tag: Schema.Literal('absent') }),
787
+ Schema.Struct({ _tag: Schema.Literal('incomplete'), reason: Schema.String }),
788
+ ]);
789
+ /** What `closedSearchSource` gives for one closed root, with the document it is in. */
790
+ const ClosedResult = Schema.Union([
791
+ Schema.Struct({ _tag: Schema.Literal('outside') }),
792
+ Schema.Struct({ _tag: Schema.Literal('content'), shows: Schema.Boolean }),
793
+ Schema.Struct({ _tag: Schema.Literal('found'), ...FoundFields, index: Schema.Int }),
794
+ Schema.Struct({ _tag: Schema.Literal('absent'), index: Schema.Int }),
795
+ Schema.Struct({ _tag: Schema.Literal('incomplete'), reason: Schema.String, index: Schema.Int }),
796
+ ]);
797
+ export const CdpCalled = Schema.Struct({
798
+ result: Schema.Struct({ value: ClosedResult }),
799
+ exceptionDetails: Schema.optionalKey(Schema.Unknown),
800
+ });
801
+ /** The isolated world `visualScaleNow` and `visualOriginNow` read the visual viewport in. */
802
+ const MEASURE_WORLD = 'screw-bugs-measure';
803
+ const FrameTreeRead = Schema.Struct({
804
+ frameTree: Schema.Struct({ frame: Schema.Struct({ id: Schema.String }) }),
805
+ });
806
+ const IsolatedWorldMade = Schema.Struct({ executionContextId: Schema.Int });
807
+ /**
808
+ * What `captureState` gives, decoded as it comes back from the page: its candidates and nodes are
809
+ * those of a screenshot's page state, in CSS pixels and without a frame.
810
+ */
811
+ export const CapturedState = Schema.Struct({
812
+ scale: PageScale,
813
+ scrollX: PageNumber,
814
+ scrollY: PageNumber,
815
+ candidates: Schema.Array(PageCandidate),
816
+ nodes: Schema.Array(PageNode),
817
+ truncated: Schema.optionalKey(Truncated),
818
+ /** Decoded on its own (`seenOf`): one that does not fit leaves the rest as it is. */
819
+ visual: Schema.optionalKey(Schema.Unknown),
820
+ });
821
+ /** The visual viewport `captureState` gives, held to finite numbers and a positive scale. */
822
+ const seenOf = Schema.decodeUnknownOption(Schema.Struct({ scale: PageScale, x: PageNumber, y: PageNumber }));
823
+ /** What `contentOf` gives. */
824
+ export const ContentBox = Schema.UndefinedOr(PageBox);
825
+ /** What `nearText` gives. */
826
+ export const NearText = Schema.UndefinedOr(Schema.String);
827
+ /** What `mediaFacts` gives, decoded as it comes back from the page. */
828
+ const MediaFactsResult = Schema.Struct({
829
+ images: Schema.Array(PageImageFact),
830
+ links: Schema.Array(LinkFact),
831
+ });
832
+ /** The CDP object group closed roots are resolved in, let go of after each read. */
833
+ const CDP_GROUP = 'screw-bugs';
834
+ const closedSessionsOf = (page) => {
835
+ const known = new Map();
836
+ const of = (frame, main) => Effect.gen(function* () {
837
+ const parent = frame.parentFrame();
838
+ if (frame === page.mainFrame() || parent === null)
839
+ return main;
840
+ let session = known.get(frame);
841
+ if (session === undefined) {
842
+ session = yield* attempt(() => page.context().newCDPSession(frame), firstLine).pipe(Effect.map((made) => made), Effect.catchIf((error) => /part of the parent frame's session/.test(error.message), () => Effect.succeed('parent')));
843
+ known.set(frame, session);
844
+ }
845
+ return session === 'parent' ? yield* of(parent, main) : session;
846
+ });
847
+ return {
848
+ of,
849
+ detach: Effect.suspend(() => Effect.forEach([...known.values()], (session) => session === 'parent'
850
+ ? Effect.void
851
+ : attempt(() => session.detach(), firstLine).pipe(Effect.ignore))).pipe(Effect.asVoid),
852
+ };
853
+ };
854
+ /** How many closed-root reads this process made: part of the token that marks their documents. */
855
+ let closedChecks = 0;
856
+ /**
857
+ * Runs on a closed shadow root, through CDP (`this` is the root): when it is inside the document
858
+ * root marked with the same token (across slots and hosts), reads it with `findText`, or without
859
+ * a search, tells with `hasContent` whether it shows anything. The same
860
+ * walker as for open roots, sent as its source, as Playwright sends page functions.
861
+ */
862
+ const closedSearchSource = `function (arg) {
863
+ const mark = globalThis[Symbol.for('screw-bugs/absence')];
864
+ if (!mark || mark.token !== arg.token) return { _tag: 'outside' };
865
+ let inside = false;
866
+ for (let n = this; n; n = n.assignedSlot ?? n.parentNode ?? n.host)
867
+ if (n === mark.root) { inside = true; break; }
868
+ if (!inside) return { _tag: 'outside' };
869
+ if (arg.search === undefined)
870
+ return { _tag: 'content', shows: (${hasContent.toString()})(this, { opacity: mark.opacity }) };
871
+ const result = (${findText.toString()})(this, { ...arg.search, opacity: mark.opacity });
872
+ return { ...result, index: mark.index };
873
+ }`;
874
+ /** How much of one document `findText` reads before it says it could not read it whole. */
875
+ export const ABSENCE_BUDGET = { nodesMax: 200_000, labelsMax: 20_000 };
876
+ /**
877
+ * How long looking for what a step did not find elsewhere may take, all together (see
878
+ * `findElsewhere`), and how long finding the frame the step named may take within it.
879
+ */
880
+ export const ELSEWHERE_TIMEOUT_MS = 1_000;
881
+ const NAMED_FRAME_MS = 250;
882
+ /** Images and links as `PageFacts` holds them: only lists that have something in them. */
883
+ const mediaFields = (media) => ({
884
+ ...(media !== undefined && media.images.length > 0 ? { images: [...media.images] } : {}),
885
+ ...(media !== undefined && media.links.length > 0
886
+ ? { links: media.links.slice(0, FACT_LINKS_MAX) }
887
+ : {}),
888
+ });
889
+ const FILE_INPUT = 'input[type=file]';
890
+ const pageOperations = (page, watch, input,
891
+ /** How the page is drawn, for placing a press in the video (see `framePoint`). */
892
+ drawn) => {
893
+ const { settle, refused } = watch;
894
+ /** Finds the first visible match, or fails with a plain "not found". */
895
+ const element = (target, timeout) => Effect.gen(function* () {
896
+ const locator = locate(page, target);
897
+ yield* attempt(() => locator.waitFor({ state: 'visible', timeout }), firstLine).pipe(Effect.mapError((error) => isTimeout(error.cause)
898
+ ? new PageActionFailed({
899
+ message: `No visible element matched ${describeTarget(target)} within ${seconds(timeout)}.`,
900
+ cause: error.cause,
901
+ notFound: true,
902
+ })
903
+ : error));
904
+ return locator;
905
+ });
906
+ /** Gives a navigation the input causes time to start during its step. */
907
+ const thenPause = (effect) => effect.pipe(Effect.tap(() => Effect.sleep(NAVIGATION_START_MS)));
908
+ /** The viewport's size now, in CSS pixels; undefined when the page has none set. */
909
+ const viewportNow = () => {
910
+ const size = page.viewportSize();
911
+ return size === null ? undefined : { width: size.width, height: size.height };
912
+ };
913
+ /**
914
+ * The events a mouse press and a key reach the page with: only those a page cannot make trusted
915
+ * itself (see `INPUT_EVENTS`). A fill, and files set on an input directly, reach the page as
916
+ * edits, which it can make trusted too (`document.execCommand`), so they are not watched.
917
+ */
918
+ const PRESSED = new Set(['pointerdown', 'mousedown']);
919
+ const KEYED = new Set(['keydown']);
920
+ /**
921
+ * The trace of an action that began at `began`, from the trusted event it reached the page with
922
+ * (`InputWatch.during`): when the browser dispatched it and, for a mouse press (`pointer`),
923
+ * where it shows in the video, in the viewport Playwright set (`framePoint`). Recording never
924
+ * touches the action itself. Nothing when no event of it was seen, and no point unless where it
925
+ * shows is certain: then the step has no time or point rather than a guessed one.
926
+ */
927
+ const traceOf = (began, dispatched, pointer) => {
928
+ if (dispatched === undefined)
929
+ return {};
930
+ const viewport = viewportNow();
931
+ const point = pointer && viewport !== undefined ? framePoint(dispatched, viewport, drawn) : undefined;
932
+ return {
933
+ afterMs: Math.max(0, dispatched.at - began),
934
+ ...(point !== undefined ? { point } : {}),
935
+ ...(viewport !== undefined ? { viewport } : {}),
936
+ };
937
+ };
938
+ /**
939
+ * The step's pause (see `thenPause`), then the trace of the action that began at `began`, from
940
+ * the event `InputWatch.during` gave: read once the pause is over, when an event the browser
941
+ * dispatched while the action ran has come in.
942
+ */
943
+ const tracedAfterPause = (began, dispatched, pointer) => Effect.sleep(NAVIGATION_START_MS).pipe(Effect.andThen(dispatched), Effect.map((event) => traceOf(began, event, pointer)));
944
+ /**
945
+ * The trace of an action that sends no input, such as scrolling: when it returned, and the
946
+ * element measured after it, where it acted: `box` as `boundingBox` gives it, shown at the
947
+ * visual viewport's `scale` then (see `visibleFrames`), so where it shows in the viewport.
948
+ * Without the scale, no element: it could be anywhere on a phone.
949
+ */
950
+ const traceAt = (began, acted, box, scale) => {
951
+ const viewport = viewportNow();
952
+ return {
953
+ afterMs: acted - began,
954
+ ...(box !== undefined && scale !== undefined
955
+ ? { target: layoutToScreen(box, { scale, x: 0, y: 0 }), scale }
956
+ : {}),
957
+ ...(viewport !== undefined ? { viewport } : {}),
958
+ };
959
+ };
960
+ const fail = (message) => Effect.fail(new PageActionFailed({ message }));
961
+ /** The page's own CDP session, made once; null where the browser has no CDP (not Chromium). */
962
+ let pageSession;
963
+ const sessionOfPage = Effect.gen(function* () {
964
+ if (pageSession === undefined)
965
+ pageSession = yield* attempt(() => page.context().newCDPSession(page), firstLine).pipe(Effect.orElseSucceed(() => null));
966
+ return pageSession;
967
+ });
968
+ /** A CDP call whose answer is decoded with `schema`; one that does not decode fails. */
969
+ const cdp = (session, method, params, schema) => attempt(() => session.send(method, params), firstLine).pipe(Effect.flatMap((answer) => Schema.decodeUnknownEffect(schema)(answer)), Effect.mapError((error) => new PageActionFailed({
970
+ message: error instanceof PageActionFailed ? error.message : `CDP ${method}: ${error}`,
971
+ })));
972
+ /**
973
+ * Evaluates `expression` in the main frame's isolated world (see `MEASURE_WORLD`), through the
974
+ * page's own CDP session, decoding its value with `schema`. Undefined without CDP or when it
975
+ * cannot be read.
976
+ */
977
+ let measureWorld;
978
+ const measured = (expression, schema) => Effect.gen(function* () {
979
+ const session = yield* sessionOfPage;
980
+ if (session === null)
981
+ return undefined;
982
+ const read = (contextId) => cdp(session, 'Runtime.evaluate', { expression, contextId, returnByValue: true }, Schema.Struct({ result: Schema.Struct({ value: schema }) })).pipe(Effect.map((answer) => answer.result.value));
983
+ const world = Effect.gen(function* () {
984
+ const { frameTree } = yield* cdp(session, 'Page.getFrameTree', {}, FrameTreeRead);
985
+ const { executionContextId } = yield* cdp(session, 'Page.createIsolatedWorld', { frameId: frameTree.frame.id, worldName: MEASURE_WORLD }, IsolatedWorldMade);
986
+ measureWorld = executionContextId;
987
+ return executionContextId;
988
+ });
989
+ // The world made earlier is gone once the page loads another document: then a new one.
990
+ return yield* (measureWorld === undefined ? world : Effect.succeed(measureWorld)).pipe(Effect.flatMap(read), Effect.catch(() => Effect.flatMap(world, read)), Effect.timeoutOption(MEASURE_TIMEOUT_MS), Effect.map(Option.getOrUndefined), Effect.orElseSucceed(() => undefined));
991
+ });
992
+ /**
993
+ * The main frame's visual viewport `scale` now (see `VisualViewport`), read from an isolated
994
+ * world of the page that no page script can see. Reading it brings no style or layout up to
995
+ * date (tested: unlike its offsets and size), so a page cannot tell it was read, however often.
996
+ * Undefined without CDP or when it cannot be read.
997
+ */
998
+ const visualScaleNow = measured('visualViewport.scale', PageScale);
999
+ /**
1000
+ * Where the main frame's visual viewport is in its layout viewport now (`offsetLeft`,
1001
+ * `offsetTop`), read like `visualScaleNow`. Reading the offsets brings style and layout up to
1002
+ * date, which a page can notice: only for where they already are (`watchText` reads after
1003
+ * measuring the page's own boxes, which does that). Undefined without CDP or when it cannot be
1004
+ * read.
1005
+ */
1006
+ const visualOriginNow = measured('[visualViewport.offsetLeft, visualViewport.offsetTop]', Schema.Tuple([PageNumber, PageNumber])).pipe(Effect.map((read) => (read === undefined ? undefined : { x: read[0], y: read[1] })));
1007
+ /**
1008
+ * Reads what the closed shadow roots in `docs` show, which no page script can reach: CDP lists
1009
+ * every shadow root, closed ones too, and hands each one to the same walker as open ones
1010
+ * (`findText`, or `hasContent` without a search), so visibility, opacity, slots and budgets are
1011
+ * judged alike. Each document is marked with a token first, so only roots inside where it looks
1012
+ * are read. Each document is read through the CDP session of its frame's process (`sessions`):
1013
+ * one that cannot be had fails the read. Marks and CDP objects are let go of whatever happens.
1014
+ * `no-cdp` without CDP; bounded by `CLOSED_ROOTS_TIMEOUT_MS`.
1015
+ */
1016
+ const readClosed = (docs, search, sessions) => Effect.gen(function* () {
1017
+ const main = yield* sessionOfPage;
1018
+ if (main === null)
1019
+ return 'no-cdp';
1020
+ const token = `${yield* Clock.currentTimeMillis}-${++closedChecks}`;
1021
+ /**
1022
+ * Every document whose marking was started, with the call that marks it: registered before
1023
+ * it starts, so a mark still on its way when the read ends is taken off too.
1024
+ */
1025
+ const marked = [];
1026
+ const read = Effect.gen(function* () {
1027
+ for (const [index, doc] of docs.entries()) {
1028
+ const marking = doc.onRoot((el, mark) => {
1029
+ globalThis[Symbol.for('screw-bugs/absence')] = {
1030
+ ...mark,
1031
+ root: el,
1032
+ };
1033
+ }, { token, index, opacity: doc.opacity });
1034
+ marked.push({ doc, marking });
1035
+ yield* attempt(() => marking, firstLine);
1036
+ }
1037
+ // Every process a document where it looks is in, each once.
1038
+ const involved = new Set();
1039
+ for (const doc of docs)
1040
+ involved.add(yield* sessions.of(doc.frame ?? page.mainFrame(), main));
1041
+ const found = [];
1042
+ for (const session of involved) {
1043
+ const each = Effect.gen(function* () {
1044
+ const { root } = yield* cdp(session, 'DOM.getDocument', { depth: -1, pierce: true }, CdpDocument);
1045
+ const closed = [];
1046
+ const walk = (node) => {
1047
+ for (const shadow of node.shadowRoots ?? []) {
1048
+ if (shadow.shadowRootType === 'closed')
1049
+ closed.push(shadow.backendNodeId);
1050
+ walk(shadow);
1051
+ }
1052
+ for (const child of node.children ?? [])
1053
+ walk(child);
1054
+ if (node.contentDocument !== undefined)
1055
+ walk(node.contentDocument);
1056
+ };
1057
+ walk(root);
1058
+ for (const backendNodeId of closed) {
1059
+ const { object } = yield* cdp(session, 'DOM.resolveNode', { backendNodeId, objectGroup: CDP_GROUP }, CdpResolved);
1060
+ const called = yield* cdp(session, 'Runtime.callFunctionOn', {
1061
+ objectId: object.objectId,
1062
+ functionDeclaration: closedSearchSource,
1063
+ arguments: [{ value: { token, ...(search !== undefined ? { search } : {}) } }],
1064
+ returnByValue: true,
1065
+ }, CdpCalled);
1066
+ if (called.exceptionDetails !== undefined)
1067
+ return yield* Effect.fail(new PageActionFailed({ message: 'reading a closed shadow root threw' }));
1068
+ found.push(called.result.value);
1069
+ }
1070
+ }).pipe(
1071
+ // Let go of the roots resolved, whatever happened.
1072
+ Effect.ensuring(attempt(() => session.send('Runtime.releaseObjectGroup', { objectGroup: CDP_GROUP }), firstLine).pipe(Effect.ignore)));
1073
+ yield* each;
1074
+ }
1075
+ return found;
1076
+ });
1077
+ return yield* read.pipe(Effect.timeoutOrElse({
1078
+ duration: CLOSED_ROOTS_TIMEOUT_MS,
1079
+ orElse: () => Effect.fail(new PageActionFailed({ message: 'reading closed shadow roots took too long' })),
1080
+ }),
1081
+ // The marks set are taken off again, whatever happened: at once, and again once a
1082
+ // marking call still on its way has landed. Only this check's mark is taken off.
1083
+ Effect.ensuring(Effect.forEach(marked, ({ doc, marking }) => {
1084
+ const unmark = () => doc.onRoot((_, own) => {
1085
+ const key = Symbol.for('screw-bugs/absence');
1086
+ if (globalThis[key]?.token === own)
1087
+ delete globalThis[key];
1088
+ }, token);
1089
+ // Boundary: a Playwright call that outlived its Effect can only be followed by its
1090
+ // promise; whatever it comes to, its mark goes.
1091
+ void marking.then(unmark, unmark).catch(() => undefined);
1092
+ return attempt(unmark, firstLine).pipe(Effect.ignore);
1093
+ })));
1094
+ });
1095
+ /**
1096
+ * What the closed shadow roots in `docs` show (see `readClosed`), as a look of `watchText`:
1097
+ * `survey` is undefined when nothing was found and all could be read, and `inScope` says how
1098
+ * many closed roots were where it looks, so later looks know whether to read them again.
1099
+ */
1100
+ const closedRoots = (docs, search, sessions) => readClosed(docs, search, sessions).pipe(Effect.map((results) => {
1101
+ if (results === 'no-cdp')
1102
+ return { survey: undefined, inScope: 0 };
1103
+ const inScope = results.filter((r) => r._tag !== 'outside').length;
1104
+ for (const result of results) {
1105
+ if (result._tag === 'found') {
1106
+ const { _tag, index, ...seen } = result;
1107
+ const survey = {
1108
+ _tag: 'shown',
1109
+ seen: { ...seen, frames: docs[index]?.path ?? [] },
1110
+ };
1111
+ return { survey, inScope };
1112
+ }
1113
+ if (result._tag === 'incomplete')
1114
+ return {
1115
+ survey: {
1116
+ _tag: 'incomplete',
1117
+ reason: `a closed shadow root where it looks: ${result.reason}`,
1118
+ },
1119
+ inScope,
1120
+ };
1121
+ }
1122
+ return { survey: undefined, inScope };
1123
+ }), Effect.orElseSucceed(() => ({
1124
+ survey: {
1125
+ _tag: 'incomplete',
1126
+ reason: 'a closed shadow root where it looks could not be read',
1127
+ },
1128
+ inScope: 1,
1129
+ })));
1130
+ /**
1131
+ * Whether a closed shadow root in `doc` shows anything, for a document that otherwise shows
1132
+ * nothing; undefined when that could not be read. False without CDP.
1133
+ */
1134
+ const closedShows = (doc, sessions) => readClosed([doc], undefined, sessions).pipe(Effect.map((results) => results === 'no-cdp' ? false : results.some((r) => r._tag === 'content' && r.shows)), Effect.orElseSucceed(() => undefined));
1135
+ return {
1136
+ // The page starts loading when they are called: that is when they acted.
1137
+ goto: (url, wait) => {
1138
+ const timeout = wait?.timeoutMs ?? NAVIGATION_TIMEOUT_MS;
1139
+ return attempt(() => page.goto(url, { timeout, waitUntil: 'load' }), (error) => isTimeout(error)
1140
+ ? `The page did not load within ${seconds(timeout)}.`
1141
+ : `Could not open ${url}: ${firstLine(error)}`).pipe(Effect.as({ afterMs: 0 }));
1142
+ },
1143
+ reload: (wait) => {
1144
+ const timeout = wait?.timeoutMs ?? NAVIGATION_TIMEOUT_MS;
1145
+ return attempt(() => page.reload({ timeout, waitUntil: 'load' }), (error) => isTimeout(error)
1146
+ ? `The page did not reload within ${seconds(timeout)}.`
1147
+ : `Could not reload the page: ${firstLine(error)}`).pipe(Effect.as({ afterMs: 0 }));
1148
+ },
1149
+ click: (target, wait) => Effect.gen(function* () {
1150
+ const began = yield* Clock.currentTimeMillis;
1151
+ const timeout = wait?.timeoutMs ?? ACTION_TIMEOUT_MS;
1152
+ const locator = yield* element(target, timeout);
1153
+ const { dispatched } = yield* input.during(PRESSED, attempt(
1154
+ // `noWaitAfter`: return once the click is dispatched rather than wait for a
1155
+ // navigation it starts, so a timeout here always means the click did not happen.
1156
+ // Page loads are waited for and judged by `settle`.
1157
+ () => locator.click({ timeout, noWaitAfter: true }), (error) => isTimeout(error)
1158
+ ? `The element was found but could not be clicked within ${seconds(timeout)}.`
1159
+ : firstLine(error)));
1160
+ return yield* tracedAfterPause(began, dispatched, true);
1161
+ }),
1162
+ fill: (target, value, wait) => Effect.gen(function* () {
1163
+ const timeout = wait?.timeoutMs ?? ACTION_TIMEOUT_MS;
1164
+ const locator = yield* element(target, timeout);
1165
+ // Not watched (see `PRESSED`): a fill records no time or point.
1166
+ yield* attempt(() => locator.fill(value, { timeout }), (error) => isTimeout(error)
1167
+ ? `The element was found but could not be filled within ${seconds(timeout)}.`
1168
+ : `The element could not be filled; it may not be an input. ${firstLine(error)}`);
1169
+ return {};
1170
+ }),
1171
+ /*
1172
+ * A file input among the matches or inside one, visible or not (styled dropzones hide theirs),
1173
+ * gets the files directly. Otherwise the first visible match is clicked while waiting for the
1174
+ * file chooser it opens, and the chooser gets them. Whichever comes first within the timeout.
1175
+ */
1176
+ upload: (target, files, wait) => Effect.gen(function* () {
1177
+ const timeout = wait?.timeoutMs ?? ACTION_TIMEOUT_MS;
1178
+ const what = describeTarget(target);
1179
+ const none = `No file input or file chooser for ${what} within ${seconds(timeout)}.`;
1180
+ const tooMany = (where) => `${where} takes one file, but ${files.length} were given.`;
1181
+ const startedAt = yield* Clock.currentTimeMillis;
1182
+ const scope = scopeOf(page, framesOf(target.frame));
1183
+ const all = matchesIn(scope, elementOf(target));
1184
+ const fileInput = all.and(scope.locator(FILE_INPUT)).or(all.locator(FILE_INPUT)).first();
1185
+ const visible = all.visible().first();
1186
+ const found = yield* attempt(() => fileInput.or(visible).first().waitFor({ state: 'attached', timeout }), firstLine).pipe(untilTimeout);
1187
+ if (!found)
1188
+ return yield* Effect.fail(new PageActionFailed({ message: none, notFound: true }));
1189
+ const remaining = Math.max(MEASURE_TIMEOUT_MS, timeout - ((yield* Clock.currentTimeMillis) - startedAt));
1190
+ if ((yield* attempt(() => fileInput.count(), firstLine)) > 0) {
1191
+ const multiple = yield* attempt(() => fileInput.evaluate((el) => el.multiple, undefined, {
1192
+ timeout: remaining,
1193
+ }), firstLine).pipe(decodedAs(Schema.Boolean));
1194
+ if (!multiple && files.length > 1)
1195
+ return yield* fail(tooMany(`The file input for ${what}`));
1196
+ // No mouse: the files are set on the input directly, hidden or not, which the page
1197
+ // gets as an edit. Not watched (see `PRESSED`): no time or point.
1198
+ yield* attempt(() => fileInput.setInputFiles([...files], { timeout: remaining }), (error) => `The files could not be set on the file input for ${what}: ${firstLine(error)}`);
1199
+ yield* Effect.sleep(NAVIGATION_START_MS);
1200
+ return {};
1201
+ }
1202
+ // Both promises are subscribed at once: the chooser may open before the click returns.
1203
+ const { value: chooser, dispatched } = yield* input.during(PRESSED, attempt(() => Promise.all([
1204
+ page.waitForEvent('filechooser', { timeout: remaining }),
1205
+ visible.click({ timeout: remaining, noWaitAfter: true }),
1206
+ ]).then(([opened]) => opened), (error) => (isTimeout(error) ? none : firstLine(error))));
1207
+ if (!chooser.isMultiple() && files.length > 1)
1208
+ return yield* fail(tooMany(`The file chooser that ${what} opens`));
1209
+ yield* attempt(() => chooser.setFiles([...files], { timeout: remaining }), (error) => `The files could not be chosen for ${what}: ${firstLine(error)}`);
1210
+ return yield* tracedAfterPause(startedAt, dispatched, true);
1211
+ }),
1212
+ // The keyboard never waits for navigations.
1213
+ press: (key) => Effect.gen(function* () {
1214
+ const began = yield* Clock.currentTimeMillis;
1215
+ const { dispatched } = yield* input.during(KEYED, attempt(() => page.keyboard.press(key), (error) => `Could not press ${key}: ${firstLine(error)}`));
1216
+ return yield* tracedAfterPause(began, dispatched, false);
1217
+ }),
1218
+ linkUrl: (target, wait) => {
1219
+ const timeout = wait?.timeoutMs ?? ACTION_TIMEOUT_MS;
1220
+ return element(target, timeout).pipe(Effect.flatMap((locator) => attempt(
1221
+ // Runs in the page. `href` there is already resolved against the page's URL.
1222
+ () => locator.evaluate((element) => element.closest('a[href], area[href]')?.href, undefined, { timeout }), firstLine)),
1223
+ // Anything but a string (an SVG link's `href` is an object) is no address.
1224
+ Effect.map((href) => Option.getOrUndefined(Schema.decodeUnknownOption(Schema.String)(href))));
1225
+ },
1226
+ hasText: (text, wait, frames = []) => attempt(() => scopeOf(page, frames)
1227
+ .getByText(text)
1228
+ .visible()
1229
+ .first()
1230
+ .waitFor({ state: 'visible', timeout: wait?.timeoutMs ?? EXPECT_TIMEOUT_MS }), firstLine).pipe(untilTimeout),
1231
+ watchText: (text, { frames, target }, watchMs, wait) => {
1232
+ // The CDP sessions of frames in processes of their own, made as needed, detached at the end.
1233
+ const sessions = closedSessionsOf(page);
1234
+ return Effect.gen(function* () {
1235
+ const timeout = wait?.timeoutMs ?? EXPECT_TIMEOUT_MS;
1236
+ const deadline = (yield* Clock.currentTimeMillis) + timeout;
1237
+ // Where it looks: the target (waited for like a click's), or the root of the frame or page.
1238
+ let root;
1239
+ if (target !== undefined)
1240
+ root = yield* element(target, timeout);
1241
+ else {
1242
+ const [frame] = frames.slice(-1);
1243
+ if (frame !== undefined)
1244
+ yield* attempt(() => matchesIn(scopeOf(page, frames.slice(0, -1)), frame)
1245
+ .visible()
1246
+ .first()
1247
+ .waitFor({ state: 'visible', timeout }), (error) => isTimeout(error)
1248
+ ? `No visible frame matched ${describeFrames(frames).replace(/^ in iframe /, '')} within ${seconds(timeout)}.`
1249
+ : firstLine(error));
1250
+ root = scopeOf(page, frames).locator(':root');
1251
+ }
1252
+ const search = { text, max: 60, ...ABSENCE_BUDGET };
1253
+ // A read that failed, or did not answer in time.
1254
+ const outOfTime = 'could not be read';
1255
+ const named = (path) => describeFrames(path).replace(/^ in /, '');
1256
+ /**
1257
+ * Whether `outer` holds `inner`, across the edges of shadow roots: an `<iframe>` in a custom
1258
+ * element's shadow root is in what the element shows.
1259
+ */
1260
+ const holds = (outer, inner) => outer.evaluate((o, i) => {
1261
+ // Up the composed tree, as everywhere: its slot, else its parent, else the host.
1262
+ for (let n = i; n; n = n.assignedSlot ?? n.parentElement ?? n.parentNode?.host ?? n.host ?? null)
1263
+ if (n === o)
1264
+ return true;
1265
+ return false;
1266
+ }, inner);
1267
+ /**
1268
+ * Whether a closed shadow root shows something in a document that otherwise shows nothing,
1269
+ * remembered for `CLOSED_SHOWS_MS` per document: listing them through CDP reads the whole
1270
+ * page, which polls must not pay for every time.
1271
+ */
1272
+ const remembered = new Map();
1273
+ const showsClosed = (doc) => Effect.gen(function* () {
1274
+ const key = JSON.stringify(doc.path);
1275
+ const now = yield* Clock.currentTimeMillis;
1276
+ const known = remembered.get(key);
1277
+ if (known !== undefined && now - known.at < CLOSED_SHOWS_MS)
1278
+ return known.shows;
1279
+ const shows = yield* closedShows(doc, sessions);
1280
+ remembered.set(key, { at: now, shows });
1281
+ return shows;
1282
+ });
1283
+ /** One complete look, or why it was not complete, or what is not ready to be looked at. */
1284
+ /** Whether closed shadow roots were found where it looks: then every look reads them. */
1285
+ let closedSeen = false;
1286
+ const survey = (deep) => Effect.gen(function* () {
1287
+ const handle = yield* within(MEASURE_TIMEOUT_MS, attempt(() => root.elementHandle({ timeout: MEASURE_TIMEOUT_MS }), firstLine));
1288
+ if (handle === undefined)
1289
+ return { _tag: 'incomplete', reason: `where it looks ${outOfTime}` };
1290
+ try {
1291
+ const own = yield* within(MEASURE_TIMEOUT_MS, attempt(() => handle.evaluate(findText, { ...search, opacity: 1 }), firstLine).pipe(decodedAs(TextSearchResult)));
1292
+ if (own === undefined)
1293
+ return { _tag: 'incomplete', reason: `where it looks ${outOfTime}` };
1294
+ if (own._tag === 'found') {
1295
+ const { _tag, ...seen } = own;
1296
+ return { _tag: 'shown', seen: { ...seen, frames: [] } };
1297
+ }
1298
+ if (own._tag === 'incomplete')
1299
+ return { _tag: 'incomplete', reason: `where it looks, ${own.reason}` };
1300
+ const filled = yield* within(MEASURE_TIMEOUT_MS, attempt(() => handle.evaluate(hasContent, { opacity: 1 }), firstLine).pipe(decodedAs(Schema.Boolean)));
1301
+ if (filled === undefined)
1302
+ return { _tag: 'incomplete', reason: `where it looks ${outOfTime}` };
1303
+ // The frames inside where it looks, as a person sees them: every one must be read.
1304
+ const rootFrame = yield* attempt(() => handle.ownerFrame(), firstLine).pipe(Effect.orElseSucceed(() => null));
1305
+ if (rootFrame === null)
1306
+ return { _tag: 'incomplete', reason: `the frames in the page ${outOfTime}` };
1307
+ const whereItLooks = target === undefined && frames.length === 0 ? 'the page' : 'where it looks';
1308
+ // Frame boxes are measured from the visual viewport's top left, and what clips a
1309
+ // frame in the page from the layout's: on a phone zoomed in and moved, they differ by
1310
+ // where the visual viewport is. Read before and after the frames are measured (both
1311
+ // right after their own boxes, so the page's layout is already up to date and the
1312
+ // reads change nothing it can notice); when it cannot be read or moved meanwhile,
1313
+ // which frames show cannot be told. Without frames it plays no part.
1314
+ const framed = page.mainFrame().childFrames().length > 0;
1315
+ const origin = framed ? yield* visualOriginNow : { x: 0, y: 0 };
1316
+ const unplaced = {
1317
+ _tag: 'incomplete',
1318
+ reason: `where the frames in ${whereItLooks} show on the screen ${outOfTime}`,
1319
+ };
1320
+ if (origin === undefined)
1321
+ return unplaced;
1322
+ // Only the frames inside where it looks are measured, counted and read.
1323
+ const visible = yield* within(FRAMES_TIMEOUT_MS, visibleFrames(page, EVERYWHERE, FRAMES_LISTED_MAX, {
1324
+ root: rootFrame,
1325
+ holds: (child) => within(MEASURE_TIMEOUT_MS, attempt(async () => {
1326
+ const el = await child.frameElement();
1327
+ try {
1328
+ // Not a boolean: whether it holds the frame is unknown, so it is unread.
1329
+ return Schema.decodeUnknownSync(Schema.Boolean)(await holds(handle, el));
1330
+ }
1331
+ finally {
1332
+ await el.dispose();
1333
+ }
1334
+ }, firstLine)),
1335
+ }, origin));
1336
+ if (visible === undefined)
1337
+ return { _tag: 'incomplete', reason: `the frames in ${whereItLooks} ${outOfTime}` };
1338
+ // A frame whose element could not be read: whether it is there to see is unknown.
1339
+ if (visible.unread.length > 0)
1340
+ return { _tag: 'incomplete', reason: `a frame in ${whereItLooks} ${outOfTime}` };
1341
+ if (visible.found > visible.kept)
1342
+ return {
1343
+ _tag: 'incomplete',
1344
+ reason: `${whereItLooks} shows more than ${FRAMES_LISTED_MAX} frames, more than are read`,
1345
+ };
1346
+ // Frames that came meanwhile were measured without it; it moved, or it went.
1347
+ if (framed || page.mainFrame().childFrames().length > 0) {
1348
+ const after = framed ? yield* visualOriginNow : undefined;
1349
+ if (after === undefined || after.x !== origin.x || after.y !== origin.y)
1350
+ return unplaced;
1351
+ }
1352
+ const where = visible.listed.flatMap((frame, index) => frame.inScope && frame.opacity >= SEEN_OPACITY ? [index] : []);
1353
+ if (where.length > ABSENCE_FRAMES_MAX)
1354
+ return {
1355
+ _tag: 'incomplete',
1356
+ reason: `${whereItLooks} shows ${where.length} frames, more than the ${ABSENCE_FRAMES_MAX} that are read`,
1357
+ };
1358
+ /** The documents read where it looks, for the closed shadow roots in them. */
1359
+ const docs = [
1360
+ {
1361
+ onRoot: (fn, arg) => handle.evaluate(fn, arg),
1362
+ path: [],
1363
+ opacity: 1,
1364
+ // Its own frame's process too, when where it looks is in a frame.
1365
+ frame: rootFrame,
1366
+ },
1367
+ ];
1368
+ let framesFilled = false;
1369
+ /** The first frame where it looks that shows nothing yet, though it may. */
1370
+ let unready;
1371
+ /** A frame that may show it later and need not: watch it for the whole wait. */
1372
+ let quiet = false;
1373
+ for (const index of where) {
1374
+ const frame = visible.listed[index];
1375
+ // Too small in both directions to read from, such as a tracking pixel: what it
1376
+ // shows is read, but one that cannot be read or shows nothing blocks nothing.
1377
+ const tiny = frame.shown.width < READABLE_FRAME_PX && frame.shown.height < READABLE_FRAME_PX;
1378
+ const path = yield* framePath(visible.listed, index).pipe(Effect.orElseSucceed(() => [{ css: 'iframe' }]));
1379
+ const unreadable = (reason) => {
1380
+ if (tiny) {
1381
+ quiet = true;
1382
+ return undefined;
1383
+ }
1384
+ return { _tag: 'incomplete', reason: `the frame ${named(path)}${reason}` };
1385
+ };
1386
+ const inner = yield* within(MEASURE_TIMEOUT_MS, attempt(() => frame.frame
1387
+ .locator(':root')
1388
+ .evaluate(findText, { ...search, opacity: frame.opacity }, { timeout: MEASURE_TIMEOUT_MS }), firstLine).pipe(decodedAs(TextSearchResult)));
1389
+ if (inner === undefined) {
1390
+ const blocks = unreadable(` ${outOfTime}`);
1391
+ if (blocks !== undefined)
1392
+ return blocks;
1393
+ continue;
1394
+ }
1395
+ if (inner._tag === 'found') {
1396
+ const { _tag, ...seen } = inner;
1397
+ return { _tag: 'shown', seen: { ...seen, frames: path } };
1398
+ }
1399
+ if (inner._tag === 'incomplete') {
1400
+ const blocks = unreadable(`: ${inner.reason}`);
1401
+ if (blocks !== undefined)
1402
+ return blocks;
1403
+ continue;
1404
+ }
1405
+ const shows = yield* within(MEASURE_TIMEOUT_MS, attempt(() => frame.frame
1406
+ .locator(':root')
1407
+ .evaluate(hasContent, { opacity: frame.opacity }, { timeout: MEASURE_TIMEOUT_MS }), firstLine).pipe(decodedAs(Schema.Boolean)));
1408
+ if (shows === undefined) {
1409
+ const blocks = unreadable(` ${outOfTime}`);
1410
+ if (blocks !== undefined)
1411
+ return blocks;
1412
+ continue;
1413
+ }
1414
+ const doc = {
1415
+ onRoot: (fn, arg) => frame.frame.locator(':root').evaluate(fn, arg),
1416
+ path,
1417
+ opacity: frame.opacity,
1418
+ frame: frame.frame,
1419
+ };
1420
+ docs.push(doc);
1421
+ // What it shows may be all in closed shadow roots: asked only when it seems empty.
1422
+ if (shows || (yield* showsClosed(doc)) === true) {
1423
+ framesFilled = true;
1424
+ continue;
1425
+ }
1426
+ // A tiny frame, or a blank one nothing was loaded into (about:blank, such as a
1427
+ // widget's placeholder), may be filled later and may stay empty: it is watched for
1428
+ // the whole wait, and blocks nothing if it stays empty. Any other frame that shows
1429
+ // nothing yet may still be rendering.
1430
+ const url = frame.frame.url();
1431
+ if (tiny || url === 'about:blank' || url === '')
1432
+ quiet = true;
1433
+ else
1434
+ unready ??= `the frame ${named(path)} showed nothing`;
1435
+ }
1436
+ if (unready !== undefined)
1437
+ return { _tag: 'waiting', reason: unready };
1438
+ if (!filled && !framesFilled && (yield* showsClosed(docs[0])) !== true)
1439
+ return { _tag: 'waiting' };
1440
+ // What closed shadow roots show: as the watch starts and ends, and on every look once
1441
+ // there are any where it looks, unless that takes too long to repeat.
1442
+ if (deep) {
1443
+ const started = yield* Clock.currentTimeMillis;
1444
+ const closed = yield* closedRoots(docs, search, sessions);
1445
+ if (closed.inScope > 0)
1446
+ closedSeen = true;
1447
+ if (closed.survey !== undefined)
1448
+ return closed.survey;
1449
+ const took = (yield* Clock.currentTimeMillis) - started;
1450
+ if (closedSeen && took > CLOSED_POLL_BUDGET_MS)
1451
+ return {
1452
+ _tag: 'incomplete',
1453
+ reason: `reading its closed shadow roots took ${seconds(Math.round(took / 100) * 100)}, too long to watch them`,
1454
+ };
1455
+ }
1456
+ return { _tag: 'absent', quiet };
1457
+ }
1458
+ finally {
1459
+ yield* attempt(() => handle.dispose(), firstLine).pipe(Effect.ignore);
1460
+ }
1461
+ });
1462
+ // Absent only once every look for `watchMs` was complete and found nothing; before the
1463
+ // page and its frames show something, every text is absent, so that proves nothing.
1464
+ let watchedFrom;
1465
+ for (;;) {
1466
+ let looked = yield* survey(closedSeen);
1467
+ if (looked._tag === 'shown')
1468
+ return looked;
1469
+ let now = yield* Clock.currentTimeMillis;
1470
+ if (looked._tag === 'absent') {
1471
+ const starting = watchedFrom === undefined;
1472
+ // A frame that may still be filled is watched until the end of the wait.
1473
+ const ending = watchedFrom !== undefined &&
1474
+ now - watchedFrom >= watchMs &&
1475
+ (!looked.quiet || now >= deadline);
1476
+ // Closed shadow roots are read through CDP as the watch starts and ends; once there
1477
+ // are any where it looks, on every look.
1478
+ if ((starting || ending) && !closedSeen) {
1479
+ looked = yield* survey(true);
1480
+ if (looked._tag === 'shown')
1481
+ return looked;
1482
+ now = yield* Clock.currentTimeMillis;
1483
+ }
1484
+ if (looked._tag === 'absent') {
1485
+ if (ending)
1486
+ return { _tag: 'absent' };
1487
+ watchedFrom ??= now;
1488
+ yield* Effect.sleep(WATCH_POLL_MS);
1489
+ continue;
1490
+ }
1491
+ }
1492
+ {
1493
+ watchedFrom = undefined;
1494
+ if (now >= deadline)
1495
+ return looked._tag === 'incomplete'
1496
+ ? { _tag: 'incomplete', reason: looked.reason }
1497
+ : looked.reason === undefined
1498
+ ? { _tag: 'empty' }
1499
+ : {
1500
+ _tag: 'incomplete',
1501
+ reason: `${looked.reason} within ${seconds(timeout)}`,
1502
+ };
1503
+ }
1504
+ yield* Effect.sleep(WATCH_POLL_MS);
1505
+ }
1506
+ }).pipe(Effect.ensuring(sessions.detach));
1507
+ },
1508
+ waitFor: (target, state, wait) => {
1509
+ const all = matches(page, target);
1510
+ // Each state is whether a match (a visible one for visible and hidden) is there or not.
1511
+ const seen = state === 'visible' || state === 'hidden' ? all.visible().first() : all.first();
1512
+ return attempt(() => seen.waitFor({
1513
+ state: state === 'visible' || state === 'attached' ? 'attached' : 'detached',
1514
+ timeout: wait?.timeoutMs ?? EXPECT_TIMEOUT_MS,
1515
+ }), firstLine).pipe(untilTimeout);
1516
+ },
1517
+ scroll: (to, wait) => {
1518
+ const timeout = wait?.timeoutMs ?? ACTION_TIMEOUT_MS;
1519
+ if (to._tag === 'target')
1520
+ return Effect.gen(function* () {
1521
+ const began = yield* Clock.currentTimeMillis;
1522
+ const locator = yield* element(to.target, timeout);
1523
+ yield* attempt(() => locator.scrollIntoViewIfNeeded({ timeout }), (error) => isTimeout(error)
1524
+ ? `The element was found but could not be scrolled into view within ${seconds(timeout)}.`
1525
+ : firstLine(error));
1526
+ const acted = yield* Clock.currentTimeMillis;
1527
+ // Where it was scrolled to, measured just after, and the scale it showed at then.
1528
+ const box = yield* within(MEASURE_TIMEOUT_MS + 250, attempt(() => locator.boundingBox({ timeout: MEASURE_TIMEOUT_MS }), firstLine).pipe(decodedAs(Schema.NullOr(PageBox))));
1529
+ const scale = box ? yield* visualScaleNow : undefined;
1530
+ return traceAt(began, acted, box ?? undefined, scale);
1531
+ }).pipe(thenPause);
1532
+ return Effect.gen(function* () {
1533
+ const began = yield* Clock.currentTimeMillis;
1534
+ const [frame] = to.frames.slice(-1);
1535
+ if (frame !== undefined)
1536
+ yield* attempt(() => matchesIn(scopeOf(page, to.frames.slice(0, -1)), frame)
1537
+ .visible()
1538
+ .first()
1539
+ .waitFor({ state: 'visible', timeout }), (error) => isTimeout(error)
1540
+ ? `No visible frame matched ${describeFrames(to.frames).replace(/^ in iframe /, '')} within ${seconds(timeout)}.`
1541
+ : firstLine(error));
1542
+ yield* attempt(() => scopeOf(page, to.frames)
1543
+ .locator(':root')
1544
+ .evaluate(scrollDocument, to._tag === 'end' ? { to: to.to } : { by: to.by }, {
1545
+ timeout,
1546
+ }), (error) => `Could not scroll: ${firstLine(error)}`).pipe(decodedAs(PageNumber));
1547
+ return traceAt(began, yield* Clock.currentTimeMillis, undefined, undefined);
1548
+ }).pipe(thenPause);
1549
+ },
1550
+ urlIncludes: (includes, wait) => attempt(() => page.waitForURL((url) => url.href.includes(includes), {
1551
+ timeout: wait?.timeoutMs ?? EXPECT_TIMEOUT_MS,
1552
+ waitUntil: 'commit',
1553
+ }), firstLine).pipe(untilTimeout),
1554
+ url: Effect.sync(() => page.url()),
1555
+ settle,
1556
+ refused,
1557
+ screenshot: (path, { fullPage, target: asked }) => Effect.gen(function* () {
1558
+ const began = yield* Clock.currentTimeMillis;
1559
+ // Nothing is waited for: an element that is not visible now (gone, or a hidden file input
1560
+ // an upload set) gets no box, at once.
1561
+ const visible = asked === undefined
1562
+ ? 0
1563
+ : ((yield* within(MEASURE_TIMEOUT_MS, attempt(() => locate(page, asked).count(), firstLine))) ?? 0);
1564
+ const target = visible > 0 ? asked : undefined;
1565
+ // Playwright scrolls to an element only as it acts on it, after this screenshot; scroll
1566
+ // first, so the image shows the element the step acts on. Best effort: it may be gone.
1567
+ if (target !== undefined)
1568
+ yield* within(MEASURE_TIMEOUT_MS + 250, attempt(() => locate(page, target).scrollIntoViewIfNeeded({ timeout: MEASURE_TIMEOUT_MS }), firstLine));
1569
+ // A full-page screenshot does not scroll, so what shows only once scrolled to would be
1570
+ // blank in it: scroll through the page first. Best effort, and bounded.
1571
+ if (fullPage)
1572
+ yield* within(REVEAL.budgetMs + 500, attempt(() => page.evaluate(revealPage, REVEAL), firstLine));
1573
+ // What the page holds is read right before the image, so the two match.
1574
+ const state = yield* within(CAPTURE_TIMEOUT_MS, attempt(() => page.evaluate(captureState, {
1575
+ fullPage,
1576
+ max: CANDIDATES_MAX,
1577
+ textMax: 200,
1578
+ urlMax: URL_MAX,
1579
+ ...SELECTOR_STATE,
1580
+ }), firstLine).pipe(decodedAs(CapturedState)));
1581
+ const measured = target === undefined
1582
+ ? undefined
1583
+ : yield* within(MEASURE_TIMEOUT_MS + 250, attempt(() => locate(page, target).boundingBox({ timeout: MEASURE_TIMEOUT_MS }), firstLine));
1584
+ // When the box was measured, which is what the video shows it at: reading the frames and
1585
+ // taking the image after this can take seconds.
1586
+ const measuredAfterMs = (yield* Clock.currentTimeMillis) - began;
1587
+ // Where its text is inside it, relative to its own box; best effort, as the box is.
1588
+ const inside = target === undefined || measured === undefined || measured === null
1589
+ ? undefined
1590
+ : yield* within(MEASURE_TIMEOUT_MS + 250, attempt(() => locate(page, target).evaluate(contentOf, undefined, {
1591
+ timeout: MEASURE_TIMEOUT_MS,
1592
+ }), firstLine).pipe(decodedAs(ContentBox)));
1593
+ // The frames on the image, and their elements, read right before it too. A viewport
1594
+ // screenshot shows the visual viewport: on a phone, as much of the layout as it shows.
1595
+ const viewport = page.viewportSize();
1596
+ const seen = Option.getOrUndefined(seenOf(state?.visual));
1597
+ const view = {
1598
+ x: fullPage ? -(state?.scrollX ?? 0) : 0,
1599
+ y: fullPage ? -(state?.scrollY ?? 0) : 0,
1600
+ width: fullPage ? Infinity : (viewport?.width ?? Infinity) / (seen?.scale ?? 1),
1601
+ height: fullPage ? Infinity : (viewport?.height ?? Infinity) / (seen?.scale ?? 1),
1602
+ };
1603
+ const framed = yield* within(FRAMES_TIMEOUT_MS, Effect.gen(function* () {
1604
+ const { listed, found, unread } = yield* visibleFrames(page, view, FRAMES_MAX, undefined, seen);
1605
+ let budget = FRAME_CANDIDATES_TOTAL;
1606
+ const read = [];
1607
+ for (const frame of listed) {
1608
+ const max = Math.min(FRAME_CANDIDATES_MAX, budget);
1609
+ const answer = max <= 0
1610
+ ? undefined
1611
+ : yield* within(MEASURE_TIMEOUT_MS, attempt(() => frame.frame.evaluate(captureState, {
1612
+ fullPage: false,
1613
+ max,
1614
+ textMax: 200,
1615
+ urlMax: URL_MAX,
1616
+ ...SELECTOR_STATE,
1617
+ opacity: frame.opacity,
1618
+ }), firstLine));
1619
+ // What does not decode is dropped, as one that did not answer is, with why.
1620
+ const inner = answer === undefined
1621
+ ? undefined
1622
+ : Option.getOrUndefined(Schema.decodeUnknownOption(CapturedState)(answer));
1623
+ budget -= inner?.candidates.length ?? 0;
1624
+ read.push({
1625
+ frame,
1626
+ inner,
1627
+ unread: max <= 0
1628
+ ? 'the frames on this screenshot had too many elements to save them all'
1629
+ : answer === undefined
1630
+ ? 'its document did not answer in time'
1631
+ : inner === undefined
1632
+ ? 'what its document gave could not be read'
1633
+ : undefined,
1634
+ });
1635
+ }
1636
+ // Frames that could not be described, by the document they are in (`-1` the page's):
1637
+ // kept as counts, so a highlight that names a frame there is never taken as unique.
1638
+ const unreadIn = new Map();
1639
+ for (const { parent } of unread)
1640
+ unreadIn.set(parent ?? -1, (unreadIn.get(parent ?? -1) ?? 0) + 1);
1641
+ return { read, found, unreadIn };
1642
+ }));
1643
+ // The scale the page shows at now, after every box was measured: the same as when the
1644
+ // page's own were (`seen`), or the page was zoomed meanwhile and the boxes cannot be placed.
1645
+ const scaleNow = seen === undefined ? undefined : yield* visualScaleNow;
1646
+ const visual = visualOf(seen, scaleNow, fullPage);
1647
+ const bytes = yield* attempt(() => page.screenshot({ path, fullPage, timeout: SCREENSHOT_TIMEOUT_MS }), (error) => `Could not take a screenshot: ${firstLine(error)}`);
1648
+ const { width, height } = pngSize(bytes);
1649
+ const scale = state?.scale ?? (viewport ? width / viewport.width : 1);
1650
+ const [dx, dy] = fullPage && state ? [state.scrollX, state.scrollY] : [0, 0];
1651
+ // Boxes measured in the layout (`captureState`'s) and from the visual viewport's top left
1652
+ // (`boundingBox`'s, see `visibleFrames`), as the viewport shows them. A full-page
1653
+ // screenshot shows the layout itself; one whose visual viewport is not known, as before.
1654
+ const fromLayout = (b) => visual === undefined || fullPage ? b : layoutToScreen(b, visual);
1655
+ const fromVisual = (b) => visual === undefined || fullPage
1656
+ ? b
1657
+ : layoutToScreen(b, { scale: visual.scale, x: 0, y: 0 });
1658
+ const box = measured === undefined || measured === null
1659
+ ? undefined
1660
+ : scaled(fromVisual({ ...measured, x: measured.x + dx, y: measured.y + dy }), scale);
1661
+ const content = measured === undefined || measured === null || inside === undefined
1662
+ ? undefined
1663
+ : scaled(fromVisual({
1664
+ ...inside,
1665
+ x: measured.x + dx + inside.x,
1666
+ y: measured.y + dy + inside.y,
1667
+ }), scale);
1668
+ // A box off the image would point at nothing; say so instead of drawing it.
1669
+ const onImage = box !== undefined && clampBox(box, width, height) !== undefined;
1670
+ const own = (state?.candidates ?? []).map((c) => ({
1671
+ ...c,
1672
+ box: scaled(fromLayout(c.box), scale),
1673
+ ...(c.content !== undefined ? { content: scaled(fromLayout(c.content), scale) } : {}),
1674
+ }));
1675
+ // Elements of a frame: from its viewport into the image, after the page's own, with
1676
+ // `parent` counted among all candidates. One wholly in a part of the frame that an
1677
+ // element around it cuts away is not visible, as one cut away in the page is not; one
1678
+ // only outside where the frame shows is outside the screenshot (see `resolveHighlight`).
1679
+ const frames = [];
1680
+ const inFrames = [];
1681
+ // The elements that hold candidates: the page's, then each frame's, so `up` and `parent`
1682
+ // in a frame's are counted after those before them.
1683
+ const nodes = [...(state?.nodes ?? [])];
1684
+ for (const [index, { frame, inner, unread }] of (framed?.read ?? []).entries()) {
1685
+ const { content, shown, cut, sx, sy } = frame;
1686
+ const onPage = (b) => scaled(fromVisual({
1687
+ x: content.x + b.x * sx + dx,
1688
+ y: content.y + b.y * sy + dy,
1689
+ width: b.width * sx,
1690
+ height: b.height * sy,
1691
+ }), scale);
1692
+ const offset = own.length + inFrames.length;
1693
+ const nodesBefore = nodes.length;
1694
+ for (const node of inner?.nodes ?? [])
1695
+ nodes.push(node.parent === undefined ? node : { ...node, parent: node.parent + nodesBefore });
1696
+ frames.push({
1697
+ ...frame.element,
1698
+ ...(frame.parent !== undefined ? { parent: frame.parent } : {}),
1699
+ box: scaled(fromVisual({ ...shown, x: shown.x + dx, y: shown.y + dy }), scale),
1700
+ url: frame.frame.url().slice(0, 300),
1701
+ ...(inner?.truncated !== undefined ? { truncated: inner.truncated } : {}),
1702
+ ...(unread !== undefined ? { unread } : {}),
1703
+ ...(framed?.unreadIn.has(index) === true
1704
+ ? { framesUnread: framed.unreadIn.get(index) }
1705
+ : {}),
1706
+ });
1707
+ const cutOnImage = cut === undefined
1708
+ ? undefined
1709
+ : scaled(fromVisual({ ...cut, x: cut.x + dx, y: cut.y + dy }), scale);
1710
+ for (const c of inner?.candidates ?? []) {
1711
+ const on = onPage(c.box);
1712
+ const cutAway = cutOnImage !== undefined && intersect(on, cutOnImage) === undefined;
1713
+ inFrames.push({
1714
+ ...c,
1715
+ box: on,
1716
+ ...(c.content !== undefined ? { content: onPage(c.content) } : {}),
1717
+ ...(c.parent !== undefined ? { parent: c.parent + offset } : {}),
1718
+ ...(c.up !== undefined ? { up: c.up + nodesBefore } : {}),
1719
+ ...(cutAway ? { visible: false } : {}),
1720
+ frame: index,
1721
+ });
1722
+ }
1723
+ }
1724
+ return {
1725
+ width,
1726
+ height,
1727
+ scale,
1728
+ url: page.url(),
1729
+ target: onImage ? box : undefined,
1730
+ ...(onImage && content !== undefined ? { targetContent: content } : {}),
1731
+ ...(onImage ? { targetAfterMs: measuredAfterMs } : {}),
1732
+ ...(box !== undefined && !onImage
1733
+ ? { targetProblem: 'the element was outside this screenshot' }
1734
+ : {}),
1735
+ candidates: [...own, ...inFrames],
1736
+ ...(state?.truncated !== undefined ? { truncated: state.truncated } : {}),
1737
+ ...(frames.length > 0 ? { frames } : {}),
1738
+ ...(framed !== undefined && framed.found > frames.length
1739
+ ? { framesFound: framed.found }
1740
+ : {}),
1741
+ ...(framed?.unreadIn.has(-1) === true ? { framesUnread: framed.unreadIn.get(-1) } : {}),
1742
+ ...(nodes.length > 0 ? { nodes } : {}),
1743
+ ...(visual !== undefined ? { visual } : {}),
1744
+ };
1745
+ }),
1746
+ findElsewhere: (sought, frames) => within(ELSEWHERE_TIMEOUT_MS, Effect.gen(function* () {
1747
+ /** Whether a document (not the frames in it) shows what was sought now. */
1748
+ const holds = (frame) => attempt(() => (sought._tag === 'text'
1749
+ ? frame.getByText(sought.text)
1750
+ : matchesIn(frame, sought.target))
1751
+ .visible()
1752
+ .count(), firstLine).pipe(Effect.map((n) => n > 0));
1753
+ // The frame the step named, if it leads to one; there after all, there is nothing to say.
1754
+ const [last] = frames.slice(-1);
1755
+ const named = last === undefined
1756
+ ? undefined
1757
+ : yield* attempt(async () => {
1758
+ const handle = await matchesIn(scopeOf(page, frames.slice(0, -1)), last)
1759
+ .visible()
1760
+ .first()
1761
+ .elementHandle({ timeout: NAMED_FRAME_MS });
1762
+ try {
1763
+ return (await handle.contentFrame()) ?? undefined;
1764
+ }
1765
+ finally {
1766
+ await handle.dispose();
1767
+ }
1768
+ }, firstLine).pipe(Effect.orElseSucceed(() => undefined));
1769
+ if (named !== undefined && (yield* holds(named)))
1770
+ return undefined;
1771
+ const inPage = frames.length > 0 && (yield* holds(page.mainFrame()));
1772
+ // The same frames a screenshot reads, wherever they are in the page; seen ones only.
1773
+ const { listed } = yield* visibleFrames(page, EVERYWHERE, FRAMES_MAX);
1774
+ const holding = [];
1775
+ for (const [index, frame] of listed.entries())
1776
+ if (frame.frame !== named &&
1777
+ frame.opacity >= SEEN_OPACITY &&
1778
+ (yield* holds(frame.frame)))
1779
+ holding.push(index);
1780
+ if (!inPage && holding.length === 0)
1781
+ return undefined;
1782
+ return {
1783
+ inPage,
1784
+ frames: yield* Effect.forEach(holding.slice(0, 2), (index) => framePath(listed, index)),
1785
+ count: holding.length,
1786
+ };
1787
+ })),
1788
+ facts: ({ target, text }) => Effect.gen(function* () {
1789
+ const title = yield* within(MEASURE_TIMEOUT_MS, attempt(() => page.title(), firstLine));
1790
+ const near = !text || target === undefined
1791
+ ? undefined
1792
+ : yield* within(MEASURE_TIMEOUT_MS + 250, attempt(() => locate(page, target).evaluate(nearText, FACT_TEXT_MAX, {
1793
+ timeout: MEASURE_TIMEOUT_MS,
1794
+ }), firstLine).pipe(decodedAs(NearText)));
1795
+ const shown = near || !text
1796
+ ? near
1797
+ : yield* within(MEASURE_TIMEOUT_MS + 250, attempt(() => page
1798
+ .locator('body')
1799
+ .evaluate(nearText, FACT_TEXT_MAX, { timeout: MEASURE_TIMEOUT_MS }), firstLine).pipe(decodedAs(NearText)));
1800
+ /** The images and links a document shows, as facts; none when it does not answer. */
1801
+ const media = (frame) => within(MEASURE_TIMEOUT_MS, attempt(() => frame.evaluate(mediaFacts, { max: FACT_IMAGES_MAX, textMax: 100, urlMax: URL_MAX }), firstLine).pipe(decodedAs(MediaFactsResult))).pipe(Effect.map(mediaFields));
1802
+ const own = yield* media(page.mainFrame());
1803
+ // The start of each visible frame's text, such as a preview the page shows in one.
1804
+ const visible = yield* within(FRAMES_TIMEOUT_MS,
1805
+ // Wherever they are in the page, scrolled into view or not.
1806
+ visibleFrames(page, EVERYWHERE, FACT_FRAMES_MAX));
1807
+ const frames = [];
1808
+ for (const { frame, opacity } of visible?.listed ?? []) {
1809
+ // A frame there but too transparent to see has no text to show.
1810
+ if (opacity < SEEN_OPACITY)
1811
+ continue;
1812
+ const excerpt = yield* within(MEASURE_TIMEOUT_MS + 250, attempt(() => frame
1813
+ .locator('body')
1814
+ .evaluate(nearText, FACT_TEXT_MAX, { timeout: MEASURE_TIMEOUT_MS }), firstLine).pipe(decodedAs(NearText)));
1815
+ frames.push({
1816
+ url: frame.url().slice(0, 300),
1817
+ ...(excerpt ? { text: excerpt } : {}),
1818
+ ...(yield* media(frame)),
1819
+ });
1820
+ }
1821
+ return {
1822
+ url: page.url().slice(0, 300),
1823
+ ...(title?.trim() ? { title: title.trim().slice(0, 120) } : {}),
1824
+ ...(shown ? { text: shown } : {}),
1825
+ httpErrors: [...watch.httpErrors()],
1826
+ ...own,
1827
+ ...(frames.length > 0 ? { frames } : {}),
1828
+ };
1829
+ }),
1830
+ };
1831
+ };
1832
+ /**
1833
+ * One session: a fresh context (no cookies or storage from other runs) with one tab that every
1834
+ * case of the session runs in, recorded as one continuous video. Tabs and windows a case opens
1835
+ * are in the same context and are closed before the next case. Closed with its scope; the video
1836
+ * is saved then too, so a run that is stopped keeps it.
1837
+ *
1838
+ * Playwright records each tab's video separately, so only the session's own tab is kept: the
1839
+ * videos of tabs the cases opened are deleted. Recording needs Playwright's ffmpeg; without it,
1840
+ * the session runs without a video and says why.
1841
+ */
1842
+ export const newSession = (browser, device, video,
1843
+ /** Whether to watch the input the page gets, for recording actions; for tests to compare. */
1844
+ observed = true) => Effect.gen(function* () {
1845
+ const clock = yield* Effect.clockWith((clock) => Effect.succeed(clock));
1846
+ const options = contextOptions(device);
1847
+ const failed = (error) => `Could not open a new browser tab: ${firstLine(error)}`;
1848
+ /** A context with its tab; with `record`, both are recorded. Boundary: Playwright promises. */
1849
+ const open = (record) => Effect.acquireRelease(attempt(() => browser.newContext({
1850
+ ...options,
1851
+ ...(record && video !== undefined
1852
+ ? { recordVideo: { dir: video.dir, size: videoSize(options.viewport) } }
1853
+ : {}),
1854
+ }), failed),
1855
+ // Only reached when opening it went wrong, or once the session closed it already
1856
+ // (`closeAll`): a failure to close it again cannot change what the session found.
1857
+ (context) => attempt(() => context.close(), firstLine).pipe(Effect.ignore)).pipe(Effect.flatMap((context) => attempt(() => context.newPage(), failed).pipe(Effect.map((page) => ({ context, page })))));
1858
+ let videoProblem;
1859
+ const { context, page } = yield* video === undefined
1860
+ ? open(false)
1861
+ : open(true).pipe(Effect.catchTag('PageActionFailed', (error) => {
1862
+ videoProblem = `Video could not be recorded: ${error.message}`;
1863
+ return open(false);
1864
+ }));
1865
+ const videoStartedAt = clock.currentTimeMillisUnsafe();
1866
+ // Boundary: Playwright reports crashes and closes through event callbacks.
1867
+ let closing = false;
1868
+ let crashed;
1869
+ const opened = [];
1870
+ context.on('page', (other) => opened.push(other));
1871
+ page.on('crash', () => {
1872
+ crashed ??= 'the page crashed.';
1873
+ });
1874
+ page.on('close', () => {
1875
+ if (!closing)
1876
+ crashed ??= 'its tab closed.';
1877
+ });
1878
+ browser.on('disconnected', () => {
1879
+ if (!closing)
1880
+ crashed ??= 'the browser closed.';
1881
+ });
1882
+ /** Closes the context, then saves the session's video and deletes the other tabs' videos. */
1883
+ let closed;
1884
+ const closeAll = () => (closed ??= (async () => {
1885
+ closing = true;
1886
+ await context.close().catch(() => undefined);
1887
+ const recorded = page.video();
1888
+ if (video === undefined || recorded === null)
1889
+ return videoProblem;
1890
+ try {
1891
+ await recorded.saveAs(video.path);
1892
+ await recorded.delete();
1893
+ }
1894
+ catch (error) {
1895
+ return `The video could not be saved: ${firstLine(error)}`;
1896
+ }
1897
+ for (const other of opened)
1898
+ if (other !== page)
1899
+ await other
1900
+ .video()
1901
+ ?.delete()
1902
+ .catch(() => undefined);
1903
+ return videoProblem;
1904
+ })());
1905
+ // Closing never fails the session: what went wrong is said about the video, which it is for.
1906
+ const close = attempt(closeAll, (error) => `The video could not be saved: ${firstLine(error)}`).pipe(Effect.catchTag('PageActionFailed', (error) => Effect.succeed(video === undefined ? videoProblem : error.message)), Effect.timeoutOption(CLOSE_TIMEOUT_MS), Effect.map((problem) => ({
1907
+ videoProblem: problem._tag === 'Some'
1908
+ ? problem.value
1909
+ : `The video was not saved within ${seconds(CLOSE_TIMEOUT_MS)}.`,
1910
+ })));
1911
+ yield* Effect.addFinalizer(() => close);
1912
+ const watch = watchContext(context, page, clock);
1913
+ // Let go of before the context closes: finalizers run last added first.
1914
+ const input = observed ? yield* watchInput(page) : unobserved;
1915
+ const drawn = {
1916
+ mobile: device === 'mobile',
1917
+ atOrigin: device === 'mobile' && observed ? yield* widgetAtOrigin(browser) : false,
1918
+ };
1919
+ return {
1920
+ page: pageOperations(page, watch, input, drawn),
1921
+ beginCase: (options) => Effect.tryPromise(async () => {
1922
+ for (const other of context.pages())
1923
+ if (other !== page)
1924
+ await other.close();
1925
+ }).pipe(Effect.timeoutOption(ACTION_TIMEOUT_MS), Effect.ignore, Effect.andThen(Effect.sync(() => watch.reset(options?.continues === true)))),
1926
+ crashed: Effect.sync(() => crashed),
1927
+ videoStartedAt,
1928
+ close,
1929
+ };
1930
+ });