@e2e-dev/web 0.11.0-canary-20260928184528
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.
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +138 -0
- package/dist/.build.json +1 -0
- package/dist/actions.d.ts +23 -0
- package/dist/actions.d.ts.map +1 -0
- package/dist/actions.js +174 -0
- package/dist/actions.js.map +1 -0
- package/dist/attempt-session.d.ts +77 -0
- package/dist/attempt-session.d.ts.map +1 -0
- package/dist/attempt-session.js +293 -0
- package/dist/attempt-session.js.map +1 -0
- package/dist/browser-connection.d.ts +34 -0
- package/dist/browser-connection.d.ts.map +1 -0
- package/dist/browser-connection.js +86 -0
- package/dist/browser-connection.js.map +1 -0
- package/dist/capture-scope.d.ts +21 -0
- package/dist/capture-scope.d.ts.map +1 -0
- package/dist/capture-scope.js +61 -0
- package/dist/capture-scope.js.map +1 -0
- package/dist/cdp-recovery.d.ts +29 -0
- package/dist/cdp-recovery.d.ts.map +1 -0
- package/dist/cdp-recovery.js +84 -0
- package/dist/cdp-recovery.js.map +1 -0
- package/dist/cdp-selectors.d.ts +15 -0
- package/dist/cdp-selectors.d.ts.map +1 -0
- package/dist/cdp-selectors.js +52 -0
- package/dist/cdp-selectors.js.map +1 -0
- package/dist/closed-shadow.d.ts +64 -0
- package/dist/closed-shadow.d.ts.map +1 -0
- package/dist/closed-shadow.js +142 -0
- package/dist/closed-shadow.js.map +1 -0
- package/dist/dialogs.d.ts +38 -0
- package/dist/dialogs.d.ts.map +1 -0
- package/dist/dialogs.js +87 -0
- package/dist/dialogs.js.map +1 -0
- package/dist/engine.d.ts +26 -0
- package/dist/engine.d.ts.map +1 -0
- package/dist/engine.js +176 -0
- package/dist/engine.js.map +1 -0
- package/dist/evaluation.d.ts +18 -0
- package/dist/evaluation.d.ts.map +1 -0
- package/dist/evaluation.js +35 -0
- package/dist/evaluation.js.map +1 -0
- package/dist/in-page/read-semantics.d.ts +28 -0
- package/dist/in-page/read-semantics.d.ts.map +1 -0
- package/dist/in-page/read-semantics.js +1178 -0
- package/dist/in-page/read-semantics.js.map +1 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +14 -0
- package/dist/index.js.map +1 -0
- package/dist/install.d.ts +40 -0
- package/dist/install.d.ts.map +1 -0
- package/dist/install.js +117 -0
- package/dist/install.js.map +1 -0
- package/dist/label-selector.d.ts +37 -0
- package/dist/label-selector.d.ts.map +1 -0
- package/dist/label-selector.js +53 -0
- package/dist/label-selector.js.map +1 -0
- package/dist/locators.d.ts +76 -0
- package/dist/locators.d.ts.map +1 -0
- package/dist/locators.js +289 -0
- package/dist/locators.js.map +1 -0
- package/dist/observation-capture.d.ts +12 -0
- package/dist/observation-capture.d.ts.map +1 -0
- package/dist/observation-capture.js +93 -0
- package/dist/observation-capture.js.map +1 -0
- package/dist/observation.d.ts +63 -0
- package/dist/observation.d.ts.map +1 -0
- package/dist/observation.js +280 -0
- package/dist/observation.js.map +1 -0
- package/dist/observe.d.ts +51 -0
- package/dist/observe.d.ts.map +1 -0
- package/dist/observe.js +105 -0
- package/dist/observe.js.map +1 -0
- package/dist/operation-budget.d.ts +11 -0
- package/dist/operation-budget.d.ts.map +1 -0
- package/dist/operation-budget.js +40 -0
- package/dist/operation-budget.js.map +1 -0
- package/dist/protected-app.d.ts +32 -0
- package/dist/protected-app.d.ts.map +1 -0
- package/dist/protected-app.js +39 -0
- package/dist/protected-app.js.map +1 -0
- package/dist/provider.d.ts +158 -0
- package/dist/provider.d.ts.map +1 -0
- package/dist/provider.js +311 -0
- package/dist/provider.js.map +1 -0
- package/dist/read-node.d.ts +152 -0
- package/dist/read-node.d.ts.map +1 -0
- package/dist/read-node.js +42 -0
- package/dist/read-node.js.map +1 -0
- package/dist/refs.d.ts +43 -0
- package/dist/refs.d.ts.map +1 -0
- package/dist/refs.js +85 -0
- package/dist/refs.js.map +1 -0
- package/dist/route-pattern.d.ts +13 -0
- package/dist/route-pattern.d.ts.map +1 -0
- package/dist/route-pattern.js +55 -0
- package/dist/route-pattern.js.map +1 -0
- package/dist/selector-engines.d.ts +6 -0
- package/dist/selector-engines.d.ts.map +1 -0
- package/dist/selector-engines.js +8 -0
- package/dist/selector-engines.js.map +1 -0
- package/dist/support.d.ts +147 -0
- package/dist/support.d.ts.map +1 -0
- package/dist/support.js +366 -0
- package/dist/support.js.map +1 -0
- package/dist/surface.d.ts +313 -0
- package/dist/surface.d.ts.map +1 -0
- package/dist/surface.js +691 -0
- package/dist/surface.js.map +1 -0
- package/dist/video.d.ts +59 -0
- package/dist/video.d.ts.map +1 -0
- package/dist/video.js +116 -0
- package/dist/video.js.map +1 -0
- package/dist/web.d.ts +191 -0
- package/dist/web.d.ts.map +1 -0
- package/dist/web.js +382 -0
- package/dist/web.js.map +1 -0
- package/package.json +67 -0
package/dist/surface.js
ADDED
|
@@ -0,0 +1,691 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Playwright surface: one browser per worker, one browser context per
|
|
3
|
+
* attempt, and the page every engine member delegates to. This is the closure
|
|
4
|
+
* state behind `web()`; the engine hooks in `engine.ts` and the `web`
|
|
5
|
+
* fixture in `web.ts` are thin delegates onto it. Action dispatch lives in
|
|
6
|
+
* `actions.ts` and tree capture in `observation.ts`. `AttemptSession` owns
|
|
7
|
+
* the attempt's live binding, recovery, references, and recordings.
|
|
8
|
+
*/
|
|
9
|
+
import { mkdirSync } from 'node:fs';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { EngineError, raceAbort, withinCleanupBudget, } from 'e2e/engine';
|
|
12
|
+
import { matchesText } from 'e2e/engine';
|
|
13
|
+
import { classifyActionError, dispatchLocatorAction, dispatchPointerAction } from './actions.js';
|
|
14
|
+
import { BrowserConnection, connectCdp } from './browser-connection.js';
|
|
15
|
+
import { AttemptSession } from './attempt-session.js';
|
|
16
|
+
import { LeasedBrowsers } from './provider.js';
|
|
17
|
+
import { DialogRouter } from './dialogs.js';
|
|
18
|
+
import { ensureBrowsersInstalled } from './install.js';
|
|
19
|
+
import { applyPostSteps, frameSelectors, projectExpression } from './locators.js';
|
|
20
|
+
import { ROOT_NODE_ID, toSemanticNode } from './observation.js';
|
|
21
|
+
import { captureObservation } from './observation-capture.js';
|
|
22
|
+
import { maskOptions, secureFieldMasks } from './observe.js';
|
|
23
|
+
import { connectionAbort } from './operation-budget.js';
|
|
24
|
+
import { CLOSED_SHADOW_ROOTS_INIT_SCRIPT } from './closed-shadow.js';
|
|
25
|
+
import { readHandlesSemanticsFunction, readManySemanticsFunction, SECURE_FIELD_SELECTOR } from './read-node.js';
|
|
26
|
+
import { httpCredentials, installSiteHeaders, lowercaseNames } from './protected-app.js';
|
|
27
|
+
import { RefRegistry } from './refs.js';
|
|
28
|
+
import { cancelled, DEFAULT_VIEWPORT, ErrorLatch, invalidState, message, navigationStaleOr, performViewportSwipe, sanitizeFilename, staleOr, translatePwError, } from './support.js';
|
|
29
|
+
/** Browser launch budget when the harness init budget is not otherwise expressed. */
|
|
30
|
+
const BROWSER_LAUNCH_TIMEOUT_MS = 60_000;
|
|
31
|
+
const STATE_FORMAT = 'playwright-storage-state';
|
|
32
|
+
/** Default budget Playwright applies to context operations that carry no explicit timeout. */
|
|
33
|
+
const CONTEXT_DEFAULT_TIMEOUT_MS = 30_000;
|
|
34
|
+
/** True for the storage-state object shape; a string (a file path) or anything else is refused. */
|
|
35
|
+
function isStorageState(data) {
|
|
36
|
+
return (typeof data === 'object' &&
|
|
37
|
+
data !== null &&
|
|
38
|
+
Array.isArray(data.cookies) &&
|
|
39
|
+
Array.isArray(data.origins));
|
|
40
|
+
}
|
|
41
|
+
/** The test-id attribute when the options name none. */
|
|
42
|
+
const DEFAULT_TEST_ID_ATTRIBUTE = 'data-testid';
|
|
43
|
+
export class PlaywrightSurface {
|
|
44
|
+
/**
|
|
45
|
+
* Errors raised where nobody awaits them (dialog routing, route handlers)
|
|
46
|
+
* wait here and fail the next step that enters the surface.
|
|
47
|
+
*/
|
|
48
|
+
latch = new ErrorLatch();
|
|
49
|
+
dialogs = new DialogRouter(this.latch);
|
|
50
|
+
browserName;
|
|
51
|
+
connection = new BrowserConnection();
|
|
52
|
+
connect;
|
|
53
|
+
/** The provider's browsers, when `browser` names one; the runner and worker halves of the lease bookkeeping. */
|
|
54
|
+
leases;
|
|
55
|
+
session;
|
|
56
|
+
usedContexts = new Set();
|
|
57
|
+
viewport;
|
|
58
|
+
/** Injected request headers, names lowercased so they replace the browser's own of the same name. */
|
|
59
|
+
headers;
|
|
60
|
+
basicAuth;
|
|
61
|
+
testIdAttribute;
|
|
62
|
+
app = {};
|
|
63
|
+
headed = false;
|
|
64
|
+
artifactsDir = '';
|
|
65
|
+
artifactCounter = 0;
|
|
66
|
+
/**
|
|
67
|
+
* Attempt-scoped network routes. Registered on the
|
|
68
|
+
* context, not a page, so they cover every page the attempt opens - the
|
|
69
|
+
* first navigation included - and re-applied to each context the attempt
|
|
70
|
+
* replaces on `reset` or session restore.
|
|
71
|
+
*/
|
|
72
|
+
routes = [];
|
|
73
|
+
constructor(options) {
|
|
74
|
+
this.browserName = typeof options.browser === 'string' ? options.browser : 'chromium';
|
|
75
|
+
this.leases = typeof options.browser === 'object' && options.browser !== null ? new LeasedBrowsers(options.browser) : undefined;
|
|
76
|
+
this.connect = options.connect;
|
|
77
|
+
this.viewport = options.viewport === undefined ? DEFAULT_VIEWPORT : options.viewport;
|
|
78
|
+
this.headers = options.headers === undefined ? undefined : lowercaseNames(options.headers);
|
|
79
|
+
this.basicAuth = options.basicAuth;
|
|
80
|
+
this.testIdAttribute = options.testIdAttribute ?? DEFAULT_TEST_ID_ATTRIBUTE;
|
|
81
|
+
}
|
|
82
|
+
// --- lifecycle ---
|
|
83
|
+
/**
|
|
84
|
+
* Installs the browser on first run, once per run before any worker, or
|
|
85
|
+
* leases the run's browsers from a provider. A CDP attach uses the
|
|
86
|
+
* remote's browser, so only a local launch needs the browser here. The
|
|
87
|
+
* download narrates through `info.log` and is bounded by the run's
|
|
88
|
+
* interrupt alone, never by a launch budget.
|
|
89
|
+
*/
|
|
90
|
+
async prepare(info) {
|
|
91
|
+
if (this.leases !== undefined)
|
|
92
|
+
return this.leases.prepare(info);
|
|
93
|
+
if (this.connect !== undefined)
|
|
94
|
+
return;
|
|
95
|
+
await ensureBrowsersInstalled([this.browserName], { env: info.env, signal: info.signal, log: info.log });
|
|
96
|
+
}
|
|
97
|
+
/** Releases the browsers `prepare` leased; a local launch or a `connect` has nothing to release. */
|
|
98
|
+
async finish(info) {
|
|
99
|
+
await this.leases?.finish(info);
|
|
100
|
+
}
|
|
101
|
+
/** Provisions the shared browser once per worker: a local launch, or a CDP attach. */
|
|
102
|
+
async init(info) {
|
|
103
|
+
this.app = info.app;
|
|
104
|
+
this.headed = info.headed;
|
|
105
|
+
this.leases?.init(info);
|
|
106
|
+
// The browser was installed in `prepare`; a launch or attach is the one
|
|
107
|
+
// boot step left that can outlive a launch budget, and it honours the
|
|
108
|
+
// init signal.
|
|
109
|
+
if (!this.persistent)
|
|
110
|
+
await this.acquireBrowser(info.signal);
|
|
111
|
+
}
|
|
112
|
+
/** Whether attempts ride a persistent remote context, provisioned per attempt, instead of contexts on one shared browser. */
|
|
113
|
+
get persistent() {
|
|
114
|
+
return this.connect?.reconnectEndpoint !== undefined || this.leases?.scope === 'attempt';
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Provisions the shared browser through the shared connection — a launch, or a CDP attach
|
|
118
|
+
* via the connector — bounded by `signal`. Checked before the endpoint is
|
|
119
|
+
* resolved: a cancelled caller must never provision a remote session it will
|
|
120
|
+
* not use.
|
|
121
|
+
*/
|
|
122
|
+
async acquireBrowser(signal) {
|
|
123
|
+
const verb = this.connect === undefined && this.leases === undefined ? 'launch' : 'connect';
|
|
124
|
+
if (signal.aborted)
|
|
125
|
+
throw cancelled(`browser ${verb} cancelled`);
|
|
126
|
+
try {
|
|
127
|
+
return await raceAbort(this.connection.acquire(this.browserName, this.headed, BROWSER_LAUNCH_TIMEOUT_MS, this.connector(signal)), signal, `browser ${verb}`);
|
|
128
|
+
}
|
|
129
|
+
catch (cause) {
|
|
130
|
+
if (cause instanceof EngineError)
|
|
131
|
+
throw cause;
|
|
132
|
+
throw new EngineError('ENGINE_FAILURE', `browser ${verb} failed: ${message(cause)}`, {
|
|
133
|
+
retryable: false,
|
|
134
|
+
cause,
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Builds the connection's connector when attaching over CDP; undefined for a local
|
|
140
|
+
* launch. The connector honours `signal` at every await: the resolver
|
|
141
|
+
* receives it, the endpoint is not used once aborted, and a browser that
|
|
142
|
+
* connects after cancellation is detached at once rather than cached — the
|
|
143
|
+
* host's session is never held by an init or attempt that already gave up.
|
|
144
|
+
*/
|
|
145
|
+
connector(signal) {
|
|
146
|
+
const source = this.endpointSource();
|
|
147
|
+
if (source === undefined)
|
|
148
|
+
return undefined;
|
|
149
|
+
return async () => {
|
|
150
|
+
const endpoint = await source.resolve(signal);
|
|
151
|
+
if (signal.aborted)
|
|
152
|
+
throw cancelled('browser connect cancelled');
|
|
153
|
+
if (typeof endpoint !== 'string' || endpoint.trim() === '') {
|
|
154
|
+
throw new EngineError('ENGINE_FAILURE', `${source.name} resolved to an empty CDP endpoint`, {
|
|
155
|
+
retryable: false,
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
const browser = await connectCdp(endpoint, BROWSER_LAUNCH_TIMEOUT_MS);
|
|
159
|
+
if (signal.aborted) {
|
|
160
|
+
await browser.close().catch(() => undefined);
|
|
161
|
+
throw cancelled('browser connect cancelled');
|
|
162
|
+
}
|
|
163
|
+
return browser;
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Where the shared browser's CDP endpoint comes from: the `connect`
|
|
168
|
+
* resolver, or the lease the worker holds from a provider; undefined for a
|
|
169
|
+
* local launch.
|
|
170
|
+
*/
|
|
171
|
+
endpointSource() {
|
|
172
|
+
if (this.connect !== undefined)
|
|
173
|
+
return { name: 'connect.cdpEndpoint', resolve: this.connect.cdpEndpoint };
|
|
174
|
+
if (this.leases === undefined)
|
|
175
|
+
return undefined;
|
|
176
|
+
return { name: 'the browser provider', resolve: (signal) => this.leaseEndpoint(signal) };
|
|
177
|
+
}
|
|
178
|
+
/** The endpoint of the lease the worker holds; only reached with a provider. */
|
|
179
|
+
leaseEndpoint(signal) {
|
|
180
|
+
if (this.leases === undefined)
|
|
181
|
+
throw invalidState('no browser provider is configured');
|
|
182
|
+
return this.leases.endpoint(signal);
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* The persistent remote context this attempt rides, when it does: the
|
|
186
|
+
* `connect` resolvers, or a browser leased for this attempt alone, which
|
|
187
|
+
* reconnects through the lease's own endpoint. Undefined for isolated
|
|
188
|
+
* contexts on the shared browser.
|
|
189
|
+
*/
|
|
190
|
+
async persistentBinding(context) {
|
|
191
|
+
const { connect, usedContexts } = this;
|
|
192
|
+
if (connect?.reconnectEndpoint !== undefined) {
|
|
193
|
+
return { provision: connect.cdpEndpoint, reconnect: connect.reconnectEndpoint, usedContexts };
|
|
194
|
+
}
|
|
195
|
+
if (this.leases?.scope !== 'attempt')
|
|
196
|
+
return undefined;
|
|
197
|
+
const lease = await this.leases.startAttempt(context);
|
|
198
|
+
return { provision: () => lease.cdpEndpoint, reconnect: () => lease.reconnectEndpoint ?? lease.cdpEndpoint, usedContexts };
|
|
199
|
+
}
|
|
200
|
+
/** Opens one attempt owner before setup starts, so cleanup can cancel pending attachment. */
|
|
201
|
+
async startAttempt(context) {
|
|
202
|
+
if (this.session !== undefined)
|
|
203
|
+
throw invalidState('an attempt is already running');
|
|
204
|
+
const persistent = await this.persistentBinding(context);
|
|
205
|
+
this.artifactsDir = context.artifactsDir;
|
|
206
|
+
this.artifactCounter = 0;
|
|
207
|
+
const routes = [];
|
|
208
|
+
this.latch = new ErrorLatch();
|
|
209
|
+
const dialogs = new DialogRouter(this.latch);
|
|
210
|
+
this.routes = routes;
|
|
211
|
+
this.dialogs = dialogs;
|
|
212
|
+
const credentials = httpCredentials(this.basicAuth);
|
|
213
|
+
const session = new AttemptSession({
|
|
214
|
+
artifactsDir: context.artifactsDir,
|
|
215
|
+
viewport: this.viewport,
|
|
216
|
+
acquire: (signal) => this.acquireBrowser(signal),
|
|
217
|
+
contextOptions: {
|
|
218
|
+
viewport: this.viewport,
|
|
219
|
+
acceptDownloads: true,
|
|
220
|
+
...(credentials === undefined ? {} : { httpCredentials: credentials }),
|
|
221
|
+
...(this.headers === undefined ? {} : { serviceWorkers: 'block' }),
|
|
222
|
+
},
|
|
223
|
+
configure: async (target) => {
|
|
224
|
+
await target.addInitScript(CLOSED_SHADOW_ROOTS_INIT_SCRIPT);
|
|
225
|
+
target.setDefaultTimeout(CONTEXT_DEFAULT_TIMEOUT_MS);
|
|
226
|
+
target.on('dialog', (dialog) => { void dialogs.dispatch(dialog); });
|
|
227
|
+
await installSiteHeaders(target, this.app.site, this.headers);
|
|
228
|
+
for (const stored of routes)
|
|
229
|
+
await target.route(stored.predicate, stored.handler);
|
|
230
|
+
},
|
|
231
|
+
...(persistent === undefined ? {} : { persistent }),
|
|
232
|
+
});
|
|
233
|
+
this.session = session;
|
|
234
|
+
await session.start(context.signal);
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Waits for a route or dialog handler still running, then rethrows the
|
|
238
|
+
* error one of them latched after the last step, so it fails this attempt
|
|
239
|
+
* instead of the next one's first operation. The latch itself is replaced
|
|
240
|
+
* by `startAttempt`, after this ran.
|
|
241
|
+
*/
|
|
242
|
+
settleAttempt(context) {
|
|
243
|
+
return this.latch.settle(context);
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Retires the owner before awaiting cleanup; late work cannot reach the
|
|
247
|
+
* next attempt. A browser leased for the attempt is released after its
|
|
248
|
+
* connection closes, whether or not the close succeeded.
|
|
249
|
+
*/
|
|
250
|
+
async endAttempt(context) {
|
|
251
|
+
const session = this.session;
|
|
252
|
+
this.session = undefined;
|
|
253
|
+
try {
|
|
254
|
+
if (session !== undefined)
|
|
255
|
+
await session.close(context);
|
|
256
|
+
}
|
|
257
|
+
finally {
|
|
258
|
+
await this.leases?.endAttempt(context);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Releases attempt resources, the worker's shared browser process, and a
|
|
263
|
+
* lease the worker acquired for itself: three independent tasks, in that
|
|
264
|
+
* order, every one attempted whatever the earlier ones did, and the first
|
|
265
|
+
* failure reported once all ran. A billed browser outlives a failed trace
|
|
266
|
+
* flush otherwise.
|
|
267
|
+
*/
|
|
268
|
+
async dispose(context) {
|
|
269
|
+
const tasks = [
|
|
270
|
+
() => this.endAttempt(context),
|
|
271
|
+
() => withinCleanupBudget(this.connection.dispose(), context),
|
|
272
|
+
async () => this.leases?.dispose(context),
|
|
273
|
+
];
|
|
274
|
+
let failure;
|
|
275
|
+
for (const task of tasks) {
|
|
276
|
+
try {
|
|
277
|
+
await task();
|
|
278
|
+
}
|
|
279
|
+
catch (cause) {
|
|
280
|
+
failure ??= { cause };
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
if (failure !== undefined)
|
|
284
|
+
throw translatePwError(failure.cause, 'dispose');
|
|
285
|
+
}
|
|
286
|
+
/** Returns the active attempt, including its connection generation and references. */
|
|
287
|
+
requireSession() {
|
|
288
|
+
if (this.session === undefined)
|
|
289
|
+
throw invalidState('no attempt is running');
|
|
290
|
+
return this.session;
|
|
291
|
+
}
|
|
292
|
+
// --- network routes shared with the web fixture ---
|
|
293
|
+
/** Registers one attempt-scoped route on the current context. */
|
|
294
|
+
async route(predicate, handler) {
|
|
295
|
+
const context = this.requireContext();
|
|
296
|
+
this.routes.push({ predicate, handler });
|
|
297
|
+
await context.route(predicate, handler);
|
|
298
|
+
}
|
|
299
|
+
/** Removes one registered route from the attempt and the current context. */
|
|
300
|
+
async unroute(predicate, handler) {
|
|
301
|
+
const context = this.requireContext();
|
|
302
|
+
const index = this.routes.findIndex((stored) => stored.predicate === predicate && stored.handler === handler);
|
|
303
|
+
if (index !== -1)
|
|
304
|
+
this.routes.splice(index, 1);
|
|
305
|
+
await context.unroute(predicate, handler);
|
|
306
|
+
}
|
|
307
|
+
// --- page access shared with the web fixture ---
|
|
308
|
+
requirePage() {
|
|
309
|
+
this.latch.throwPending();
|
|
310
|
+
const page = this.requireSession().current().page;
|
|
311
|
+
if (page === null || page.isClosed())
|
|
312
|
+
throw invalidState('no app page is open; call app.open() or web.goto() first');
|
|
313
|
+
return page;
|
|
314
|
+
}
|
|
315
|
+
requireContext() {
|
|
316
|
+
this.latch.throwPending();
|
|
317
|
+
return this.requireSession().current().context;
|
|
318
|
+
}
|
|
319
|
+
/** Creates the active page through the attempt's sole binding owner. */
|
|
320
|
+
ensurePage() {
|
|
321
|
+
return this.requireSession().ensurePage();
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* The single entry of every operation: rethrows an error latched on an
|
|
325
|
+
* unawaited path, refuses a cancelled operation, races `fn` against the
|
|
326
|
+
* operation signal so an abort mid-call surfaces as `CANCELLED` instead of
|
|
327
|
+
* waiting out Playwright, and translates raw errors at the contract
|
|
328
|
+
* boundary. `translate` overrides the default translation for operations
|
|
329
|
+
* with a documented retryable failure mode.
|
|
330
|
+
*/
|
|
331
|
+
async guard(operation, label, fn, translate = translatePwError) {
|
|
332
|
+
this.latch.throwPending();
|
|
333
|
+
try {
|
|
334
|
+
return this.session === undefined
|
|
335
|
+
? await raceAbort(() => fn(operation), operation.signal, label)
|
|
336
|
+
: await this.session.run(operation, label, fn);
|
|
337
|
+
}
|
|
338
|
+
catch (cause) {
|
|
339
|
+
throw translate(cause, label);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
// --- steering: the session hooks ---
|
|
343
|
+
/** Opens one URL the harness resolved; the attempt's page is created on first use. */
|
|
344
|
+
open(url, operation) {
|
|
345
|
+
return this.guard(operation, 'navigation', async (currentOperation) => {
|
|
346
|
+
const page = await this.ensurePage();
|
|
347
|
+
await page.goto(url, { waitUntil: 'load', timeout: currentOperation.timeoutMs });
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
back(operation) {
|
|
351
|
+
return this.guard(operation, 'navigation', async (currentOperation) => {
|
|
352
|
+
await this.requirePage().goBack({ waitUntil: 'load', timeout: currentOperation.timeoutMs });
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
/** Restarts the document while retaining this attempt's context and storage. */
|
|
356
|
+
restart(operation) {
|
|
357
|
+
return this.guard(operation, 'restart', () => this.requireSession().restart());
|
|
358
|
+
}
|
|
359
|
+
/** Replaces the context with a clean one and opens its blank page. */
|
|
360
|
+
reset(operation) {
|
|
361
|
+
return this.guard(operation, 'state reset', async (currentOperation) => {
|
|
362
|
+
const session = this.requireSession();
|
|
363
|
+
await session.replace(undefined, currentOperation);
|
|
364
|
+
await session.ensurePage();
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
// --- location tier ---
|
|
368
|
+
/**
|
|
369
|
+
* Resolves one expression to every node it currently matches, fully read,
|
|
370
|
+
* in one in-page round trip. A `displayValue` query is filtered here by the
|
|
371
|
+
* value each element reported, so no per-node calls are needed; any
|
|
372
|
+
* `first`/`last`/`nth` on such a query then selects among those matches, and
|
|
373
|
+
* a filter placed after a position is checked on the selected element. A
|
|
374
|
+
* `visible` query drops the candidates whose hidden state the same read
|
|
375
|
+
* reported before either of those, so a position is among shown matches.
|
|
376
|
+
*/
|
|
377
|
+
locate(expression, operation) {
|
|
378
|
+
return this.guard(operation, 'locate', async (currentOperation) => {
|
|
379
|
+
const session = this.requireSession();
|
|
380
|
+
const token = session.token();
|
|
381
|
+
const refs = session.refs;
|
|
382
|
+
const page = this.requirePage();
|
|
383
|
+
await this.validateFrames(expression);
|
|
384
|
+
const projected = projectExpression(page, expression, this.testIdAttribute);
|
|
385
|
+
const { displayValue, name, steps } = projected;
|
|
386
|
+
const readOptions = {
|
|
387
|
+
testIdAttribute: this.testIdAttribute,
|
|
388
|
+
secureFieldSelector: SECURE_FIELD_SELECTOR,
|
|
389
|
+
mode: { kind: 'node' },
|
|
390
|
+
};
|
|
391
|
+
// A predicate-filtered match is one element among many candidates (every input with a
|
|
392
|
+
// value, every control the label engine kept). Re-resolving it by position at action
|
|
393
|
+
// time would act on a neighbor whenever the page inserted or removed an element in
|
|
394
|
+
// between, so such matches are pinned to element handles: the handles are taken first
|
|
395
|
+
// and the semantics are read from those very handles, so what was read and what is
|
|
396
|
+
// acted on are one set of elements by construction.
|
|
397
|
+
const handles = displayValue !== null || name !== null
|
|
398
|
+
? (await projected.locator.elementHandles())
|
|
399
|
+
: null;
|
|
400
|
+
/** Disposes every handle this locate took, on the paths that hand none of them out. */
|
|
401
|
+
const releaseHandles = () => {
|
|
402
|
+
for (const handle of handles ?? [])
|
|
403
|
+
void handle.dispose().catch(() => undefined);
|
|
404
|
+
};
|
|
405
|
+
const first = handles?.[0];
|
|
406
|
+
const reads = handles === null
|
|
407
|
+
? await projected.locator.evaluateAll(readManySemanticsFunction, readOptions)
|
|
408
|
+
: first === undefined
|
|
409
|
+
? []
|
|
410
|
+
: await first.evaluate(readHandlesSemanticsFunction, { elements: handles, options: readOptions });
|
|
411
|
+
// The page can replace a queried element before the read reaches it. Every element the
|
|
412
|
+
// query returned is a match, except a display-value candidate, whose held value says
|
|
413
|
+
// whether it was one. A match that left re-resolves the set, so a count or a single
|
|
414
|
+
// match is never taken from what remains; a non-match that left drops out, so churn in
|
|
415
|
+
// unrelated controls never holds up a query for a stable one.
|
|
416
|
+
if (reads.some((read) => 'detached' in read && (displayValue === null || matchesText(read.value ?? '', displayValue)))) {
|
|
417
|
+
releaseHandles();
|
|
418
|
+
throw new EngineError('NODE_STALE', 'a match left the document while it was read', { retryable: true });
|
|
419
|
+
}
|
|
420
|
+
const candidates = reads.flatMap((raw, index) => 'detached' in raw || (projected.visible && raw.states.hidden) ? [] : [{ raw, index }]);
|
|
421
|
+
// An exact label query matches any of the control's labels as the engine's reader names
|
|
422
|
+
// them, so text a label marks aria-hidden (a required-field marker) never hides a field,
|
|
423
|
+
// and an aria-label override or a second label does not either.
|
|
424
|
+
const predicate = displayValue !== null
|
|
425
|
+
? (raw) => matchesText(raw.value ?? '', displayValue)
|
|
426
|
+
: name !== null
|
|
427
|
+
? (raw) => raw.labels !== null && raw.labels.some((label) => matchesText(label, name))
|
|
428
|
+
: null;
|
|
429
|
+
const matches = predicate === null
|
|
430
|
+
? candidates
|
|
431
|
+
: await applyPostSteps(candidates.filter(({ raw }) => predicate(raw)), steps,
|
|
432
|
+
// A filter after a position runs on that one element alone.
|
|
433
|
+
async ({ index }, options) => (await projected.locator.nth(index).filter(options).count()) > 0);
|
|
434
|
+
if (currentOperation.signal.aborted) {
|
|
435
|
+
releaseHandles();
|
|
436
|
+
throw cancelled('locate cancelled');
|
|
437
|
+
}
|
|
438
|
+
try {
|
|
439
|
+
session.check(token);
|
|
440
|
+
}
|
|
441
|
+
catch (cause) {
|
|
442
|
+
releaseHandles();
|
|
443
|
+
throw cause;
|
|
444
|
+
}
|
|
445
|
+
if (handles !== null) {
|
|
446
|
+
// Only the matches keep their handles; the rest would otherwise live until the page goes.
|
|
447
|
+
const kept = new Set(matches.map(({ index }) => index));
|
|
448
|
+
for (const [index, handle] of handles.entries()) {
|
|
449
|
+
if (!kept.has(index))
|
|
450
|
+
void handle.dispose().catch(() => undefined);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
return matches.map(({ raw, index }) => {
|
|
454
|
+
const pinned = handles?.[index];
|
|
455
|
+
// A single match keeps the strict locator, so a ref that turns
|
|
456
|
+
// ambiguous between locate and perform fails loud instead of acting
|
|
457
|
+
// on whichever element is first.
|
|
458
|
+
const locator = reads.length === 1 ? projected.locator : projected.locator.nth(index);
|
|
459
|
+
const id = refs.storeLocated(pinned === undefined ? { kind: 'locator', locator } : { kind: 'element', element: pinned });
|
|
460
|
+
return toSemanticNode({ id, revision: '' }, raw);
|
|
461
|
+
});
|
|
462
|
+
}, staleOr);
|
|
463
|
+
}
|
|
464
|
+
/**
|
|
465
|
+
* One action on a located or observed node. A `swipe` on the observation
|
|
466
|
+
* root is the viewport swipe: a wheel gesture sized by the viewport, with no
|
|
467
|
+
* element resolved behind it, so it needs only the page. Every other action
|
|
468
|
+
* on the root acts on the document element the root stands for.
|
|
469
|
+
*/
|
|
470
|
+
perform(ref, action, operation) {
|
|
471
|
+
return this.guard(operation, action.kind, (currentOperation) => {
|
|
472
|
+
const page = this.requirePage();
|
|
473
|
+
if (action.kind === 'swipe' && ref.id === ROOT_NODE_ID) {
|
|
474
|
+
this.requireSession().requireObservation();
|
|
475
|
+
return performViewportSwipe(page, action.direction, action.momentum ?? 'none');
|
|
476
|
+
}
|
|
477
|
+
return dispatchLocatorAction(this.requireSession().refs.lookup(ref), action, currentOperation.timeoutMs, (other) => this.requireSession().refs.lookup(other));
|
|
478
|
+
}, (cause) => classifyActionError(cause, action));
|
|
479
|
+
}
|
|
480
|
+
/** One pointer action at a viewport point in CSS pixels, with nothing resolved behind it; see `dispatchPointerAction`. */
|
|
481
|
+
performAt(point, action, operation) {
|
|
482
|
+
return this.guard(operation, `${action.kind} at point`, () => {
|
|
483
|
+
this.requireSession().requireObservation();
|
|
484
|
+
return dispatchPointerAction(this.requirePage(), point, action);
|
|
485
|
+
});
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Types into whatever holds focus. Keystrokes into a document body are
|
|
489
|
+
* accepted by the browser and lost, so the focused element is checked for
|
|
490
|
+
* editability first and the call refuses rather than "typing" into nothing.
|
|
491
|
+
* `replace` clears with select-all and delete: the only locator-free clear,
|
|
492
|
+
* scoped by the browser to the whole editing host, so it is opt-in.
|
|
493
|
+
*/
|
|
494
|
+
typeText(text, options, operation) {
|
|
495
|
+
return this.guard(operation, 'keyboard.type', async (currentOperation) => {
|
|
496
|
+
const session = this.requireSession();
|
|
497
|
+
session.requireObservation();
|
|
498
|
+
const token = session.token();
|
|
499
|
+
const page = this.requirePage();
|
|
500
|
+
/** A delayed focus read or key must not continue input into a retired connection. */
|
|
501
|
+
const checkpoint = () => {
|
|
502
|
+
if (currentOperation.signal.aborted)
|
|
503
|
+
throw connectionAbort(currentOperation.signal, 'keyboard.type');
|
|
504
|
+
session.check(token);
|
|
505
|
+
};
|
|
506
|
+
await this.requireEditableFocus(page);
|
|
507
|
+
checkpoint();
|
|
508
|
+
if (options.replace) {
|
|
509
|
+
await page.keyboard.press('ControlOrMeta+A');
|
|
510
|
+
checkpoint();
|
|
511
|
+
await page.keyboard.press('Delete');
|
|
512
|
+
checkpoint();
|
|
513
|
+
}
|
|
514
|
+
await page.keyboard.type(text);
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
/** Sends one key to whatever holds focus, in the contract's key grammar Playwright shares. */
|
|
518
|
+
pressKey(key, operation) {
|
|
519
|
+
return this.guard(operation, 'keyboard.press', () => {
|
|
520
|
+
this.requireSession().requireObservation();
|
|
521
|
+
return this.requirePage().keyboard.press(key);
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* Refuses focused typing when nothing that takes keystrokes has focus, in
|
|
526
|
+
* any frame of the page. Text fields and contenteditable hosts take them;
|
|
527
|
+
* so does any other focusable element the app made focusable (a canvas, a
|
|
528
|
+
* widget with a tabindex and its own key handling), because focusing it is
|
|
529
|
+
* how the app opted into keys. Focus on the body, a button, a link, a
|
|
530
|
+
* select, or a non-text input means the keystrokes would be discarded.
|
|
531
|
+
*/
|
|
532
|
+
async requireEditableFocus(page) {
|
|
533
|
+
const editable = await Promise.all(page.frames().map((frame) => frame
|
|
534
|
+
.evaluate(() => {
|
|
535
|
+
const active = document.activeElement;
|
|
536
|
+
if (active === null || active === document.body || active === document.documentElement)
|
|
537
|
+
return false;
|
|
538
|
+
if (active instanceof HTMLInputElement) {
|
|
539
|
+
return !active.disabled && !active.readOnly && !['button', 'submit', 'reset', 'checkbox', 'radio', 'file', 'image', 'range', 'color'].includes(active.type);
|
|
540
|
+
}
|
|
541
|
+
if (active instanceof HTMLTextAreaElement)
|
|
542
|
+
return !active.disabled && !active.readOnly;
|
|
543
|
+
if (active instanceof HTMLSelectElement || active instanceof HTMLButtonElement || active instanceof HTMLAnchorElement) {
|
|
544
|
+
return false;
|
|
545
|
+
}
|
|
546
|
+
return true;
|
|
547
|
+
})
|
|
548
|
+
.catch(() => false)));
|
|
549
|
+
if (!editable.some(Boolean)) {
|
|
550
|
+
throw new EngineError('NOT_ACTIONABLE', 'nothing that takes keystrokes has focus: the typed text would reach no field. Tap the field first, or type into a listed input by id.', { retryable: false });
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
/**
|
|
554
|
+
* Checks that every frame selector along the expression matches exactly one
|
|
555
|
+
* element, each counted inside the frame before it, the way `project` walks
|
|
556
|
+
* the same chain; a frame-scoped `count` is 0 until that frame's document
|
|
557
|
+
* has loaded, which is what makes `FRAME_NOT_FOUND` worth retrying.
|
|
558
|
+
*/
|
|
559
|
+
async validateFrames(expression) {
|
|
560
|
+
let scope = this.requirePage();
|
|
561
|
+
for (const selector of frameSelectors(expression)) {
|
|
562
|
+
let count;
|
|
563
|
+
try {
|
|
564
|
+
count = await scope.locator(selector).count();
|
|
565
|
+
}
|
|
566
|
+
catch (cause) {
|
|
567
|
+
throw translatePwError(cause, 'frame resolution');
|
|
568
|
+
}
|
|
569
|
+
if (count === 0) {
|
|
570
|
+
throw new EngineError('FRAME_NOT_FOUND', `no frame matches ${selector}`, {
|
|
571
|
+
retryable: true,
|
|
572
|
+
});
|
|
573
|
+
}
|
|
574
|
+
if (count > 1) {
|
|
575
|
+
throw new EngineError('FRAME_AMBIGUOUS', `${count} frames match ${selector}`, {
|
|
576
|
+
retryable: false,
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
scope = scope.frameLocator(selector);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
// --- artifacts ---
|
|
583
|
+
/**
|
|
584
|
+
* Reserves one artifact path under the attempt directory: a per-attempt
|
|
585
|
+
* counter keeps names unique, the label keeps them readable.
|
|
586
|
+
*/
|
|
587
|
+
artifactPath(folder, label, extension) {
|
|
588
|
+
this.artifactCounter += 1;
|
|
589
|
+
const name = `${String(this.artifactCounter).padStart(3, '0')}${label === undefined ? '' : `-${sanitizeFilename(label)}`}${extension}`;
|
|
590
|
+
const relative = path.posix.join(folder, name);
|
|
591
|
+
const absolute = path.join(this.artifactsDir, relative);
|
|
592
|
+
mkdirSync(path.dirname(absolute), { recursive: true });
|
|
593
|
+
return { relative, absolute };
|
|
594
|
+
}
|
|
595
|
+
/** Redacted at the source: secure fields in every frame are masked, as in observation pixels. */
|
|
596
|
+
screenshot(label, operation) {
|
|
597
|
+
return this.guard(operation, 'screenshot', async (currentOperation) => {
|
|
598
|
+
const page = this.requirePage();
|
|
599
|
+
const { relative, absolute } = this.artifactPath('screenshots', label, '.png');
|
|
600
|
+
await page.screenshot({
|
|
601
|
+
path: absolute,
|
|
602
|
+
timeout: currentOperation.timeoutMs,
|
|
603
|
+
...maskOptions(secureFieldMasks(page)),
|
|
604
|
+
});
|
|
605
|
+
return relative;
|
|
606
|
+
});
|
|
607
|
+
}
|
|
608
|
+
/** Starts tracing the current attempt. */
|
|
609
|
+
startTrace(operation) {
|
|
610
|
+
return this.guard(operation, 'trace', () => this.requireSession().startTrace());
|
|
611
|
+
}
|
|
612
|
+
/** Returns every trace segment finalized by the current attempt. */
|
|
613
|
+
stopTrace(operation) {
|
|
614
|
+
return this.requireSession().collectTrace(operation);
|
|
615
|
+
}
|
|
616
|
+
/** Starts the attempt's video before a trace chooses its screencast dimensions. */
|
|
617
|
+
startVideo(operation) {
|
|
618
|
+
return this.guard(operation, 'video', () => this.requireSession().startVideo());
|
|
619
|
+
}
|
|
620
|
+
/** Finishes the attempt's recording and returns its finalized segments. */
|
|
621
|
+
stopVideo(operation) {
|
|
622
|
+
return this.requireSession().collectVideo(operation);
|
|
623
|
+
}
|
|
624
|
+
// --- state ---
|
|
625
|
+
captureState(operation) {
|
|
626
|
+
return this.guard(operation, 'state capture', async () => {
|
|
627
|
+
const storageState = await this.requireContext().storageState({ indexedDB: true });
|
|
628
|
+
return { format: STATE_FORMAT, version: 1, data: storageState };
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
/** Replaces the attempt's context with one seeded from the snapshot. */
|
|
632
|
+
restoreState(state, operation) {
|
|
633
|
+
return this.guard(operation, 'state restore', async (currentOperation) => {
|
|
634
|
+
if (state.format !== STATE_FORMAT || state.version !== 1) {
|
|
635
|
+
throw new EngineError('INVALID_STATE', `unsupported state format ${state.format}@${String(state.version)}`, { retryable: false });
|
|
636
|
+
}
|
|
637
|
+
// A string here would be read by Playwright as a file path; a session
|
|
638
|
+
// envelope must never be able to point the browser at the filesystem.
|
|
639
|
+
if (!isStorageState(state.data)) {
|
|
640
|
+
throw new EngineError('INVALID_STATE', 'state data must be a storage-state object', {
|
|
641
|
+
retryable: false,
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
await this.requireSession().replace(state.data, currentOperation);
|
|
645
|
+
});
|
|
646
|
+
}
|
|
647
|
+
// --- observation ---
|
|
648
|
+
/**
|
|
649
|
+
* Captures one atomic semantic observation. Secure fields are masked in the
|
|
650
|
+
* page before the tree leaves the engine, and every node keeps a live
|
|
651
|
+
* element handle valid until the next observation replaces the generation.
|
|
652
|
+
*
|
|
653
|
+
* With `options.pixels`, masked viewport pixels are captured alongside the
|
|
654
|
+
* tree rather than after it, so the image and the node geometry describe the
|
|
655
|
+
* page as closely in time as two engine calls can.
|
|
656
|
+
*/
|
|
657
|
+
observe(operation, options) {
|
|
658
|
+
// A capture that lost its document to a navigation reads as a stale node:
|
|
659
|
+
// nothing was dispatched, so the runner re-observes the new document
|
|
660
|
+
// within the same deadline instead of failing the call.
|
|
661
|
+
return this.guard(operation, 'observe', (currentOperation) => this.captureObservation(currentOperation, options), navigationStaleOr);
|
|
662
|
+
}
|
|
663
|
+
/** Captures privately, then publishes only into the page and ref generation that requested it. */
|
|
664
|
+
async captureObservation(operation, options) {
|
|
665
|
+
const session = this.requireSession();
|
|
666
|
+
const token = session.token();
|
|
667
|
+
const refs = session.refs;
|
|
668
|
+
const page = this.requirePage();
|
|
669
|
+
const capture = refs.beginCapture();
|
|
670
|
+
const captured = await captureObservation(page, refs, {
|
|
671
|
+
testIdAttribute: this.testIdAttribute, site: this.app.site,
|
|
672
|
+
}, operation, options);
|
|
673
|
+
const { snapshot, generation } = captured;
|
|
674
|
+
try {
|
|
675
|
+
if (operation.signal.aborted)
|
|
676
|
+
throw cancelled('observe cancelled');
|
|
677
|
+
session.check(token);
|
|
678
|
+
if (this.requirePage() !== page) {
|
|
679
|
+
throw new EngineError('NODE_STALE', 'observation page was replaced', { retryable: true });
|
|
680
|
+
}
|
|
681
|
+
refs.publish(capture, captured);
|
|
682
|
+
session.observedGeneration(token);
|
|
683
|
+
return snapshot;
|
|
684
|
+
}
|
|
685
|
+
catch (cause) {
|
|
686
|
+
RefRegistry.dispose(generation);
|
|
687
|
+
throw cause;
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
//# sourceMappingURL=surface.js.map
|