@dream_engine/browser 0.0.0-stage → 0.1.1

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 (100) hide show
  1. package/LICENSE +21 -0
  2. package/dist/.tsbuildinfo +1 -0
  3. package/dist/adapter/playwright.d.ts +27 -0
  4. package/dist/adapter/playwright.d.ts.map +1 -0
  5. package/dist/adapter/playwright.js +1087 -0
  6. package/dist/adapter/playwright.js.map +1 -0
  7. package/dist/adapter/types.d.ts +833 -0
  8. package/dist/adapter/types.d.ts.map +1 -0
  9. package/dist/adapter/types.js +9 -0
  10. package/dist/adapter/types.js.map +1 -0
  11. package/dist/api-request.d.ts +93 -0
  12. package/dist/api-request.d.ts.map +1 -0
  13. package/dist/api-request.js +284 -0
  14. package/dist/api-request.js.map +1 -0
  15. package/dist/artifacts.d.ts +99 -0
  16. package/dist/artifacts.d.ts.map +1 -0
  17. package/dist/artifacts.js +211 -0
  18. package/dist/artifacts.js.map +1 -0
  19. package/dist/browser.d.ts +79 -0
  20. package/dist/browser.d.ts.map +1 -0
  21. package/dist/browser.js +186 -0
  22. package/dist/browser.js.map +1 -0
  23. package/dist/code-execution.d.ts +12 -0
  24. package/dist/code-execution.d.ts.map +1 -0
  25. package/dist/code-execution.js +15 -0
  26. package/dist/code-execution.js.map +1 -0
  27. package/dist/context.d.ts +174 -0
  28. package/dist/context.d.ts.map +1 -0
  29. package/dist/context.js +474 -0
  30. package/dist/context.js.map +1 -0
  31. package/dist/events.d.ts +66 -0
  32. package/dist/events.d.ts.map +1 -0
  33. package/dist/events.js +87 -0
  34. package/dist/events.js.map +1 -0
  35. package/dist/index.d.ts +24 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +23 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/locator.d.ts +208 -0
  40. package/dist/locator.d.ts.map +1 -0
  41. package/dist/locator.js +402 -0
  42. package/dist/locator.js.map +1 -0
  43. package/dist/login.d.ts +76 -0
  44. package/dist/login.d.ts.map +1 -0
  45. package/dist/login.js +176 -0
  46. package/dist/login.js.map +1 -0
  47. package/dist/manager.d.ts +109 -0
  48. package/dist/manager.d.ts.map +1 -0
  49. package/dist/manager.js +320 -0
  50. package/dist/manager.js.map +1 -0
  51. package/dist/navigation.d.ts +74 -0
  52. package/dist/navigation.d.ts.map +1 -0
  53. package/dist/navigation.js +234 -0
  54. package/dist/navigation.js.map +1 -0
  55. package/dist/network.d.ts +260 -0
  56. package/dist/network.d.ts.map +1 -0
  57. package/dist/network.js +582 -0
  58. package/dist/network.js.map +1 -0
  59. package/dist/page.d.ts +512 -0
  60. package/dist/page.d.ts.map +1 -0
  61. package/dist/page.js +1493 -0
  62. package/dist/page.js.map +1 -0
  63. package/dist/selectors.d.ts +67 -0
  64. package/dist/selectors.d.ts.map +1 -0
  65. package/dist/selectors.js +137 -0
  66. package/dist/selectors.js.map +1 -0
  67. package/dist/sessions.d.ts +114 -0
  68. package/dist/sessions.d.ts.map +1 -0
  69. package/dist/sessions.js +285 -0
  70. package/dist/sessions.js.map +1 -0
  71. package/dist/smart/dom-scan.d.ts +104 -0
  72. package/dist/smart/dom-scan.d.ts.map +1 -0
  73. package/dist/smart/dom-scan.js +491 -0
  74. package/dist/smart/dom-scan.js.map +1 -0
  75. package/dist/smart/ranking.d.ts +63 -0
  76. package/dist/smart/ranking.d.ts.map +1 -0
  77. package/dist/smart/ranking.js +318 -0
  78. package/dist/smart/ranking.js.map +1 -0
  79. package/dist/smart/recovery.d.ts +106 -0
  80. package/dist/smart/recovery.d.ts.map +1 -0
  81. package/dist/smart/recovery.js +197 -0
  82. package/dist/smart/recovery.js.map +1 -0
  83. package/dist/smart/smart.d.ts +249 -0
  84. package/dist/smart/smart.d.ts.map +1 -0
  85. package/dist/smart/smart.js +840 -0
  86. package/dist/smart/smart.js.map +1 -0
  87. package/dist/trace-parser.d.ts +70 -0
  88. package/dist/trace-parser.d.ts.map +1 -0
  89. package/dist/trace-parser.js +203 -0
  90. package/dist/trace-parser.js.map +1 -0
  91. package/dist/types.d.ts +57 -0
  92. package/dist/types.d.ts.map +1 -0
  93. package/dist/types.js +2 -0
  94. package/dist/types.js.map +1 -0
  95. package/dist/visual.d.ts +185 -0
  96. package/dist/visual.d.ts.map +1 -0
  97. package/dist/visual.js +384 -0
  98. package/dist/visual.js.map +1 -0
  99. package/package.json +37 -3
  100. package/README.md +0 -3
package/dist/page.js ADDED
@@ -0,0 +1,1493 @@
1
+ import { copyFileSync, mkdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { AmbiguousElementError, ElementNotFoundError, InteractionError, SessionError, TimeoutError, ValidationError, createId, redactUrl, toBashirWebError, } from '@dream_engine/core';
4
+ import { extractDocument } from '@dream_engine/extraction';
5
+ import { checkDownload, sanitizeFilename, validateUploadPath } from '@dream_engine/security';
6
+ import { confineOutput, noteArtifact } from './artifacts.js';
7
+ import { assertCodeExecution } from './code-execution.js';
8
+ import { scriptSource } from './context.js';
9
+ import { NavigationManager } from './navigation.js';
10
+ import { NetworkMonitor, urlMatches } from './network.js';
11
+ import { scanDocument } from './smart/dom-scan.js';
12
+ import { fingerprintOf } from './smart/recovery.js';
13
+ import { SmartInteraction } from './smart/smart.js';
14
+ import { TypedEmitter } from './events.js';
15
+ import { BashirFrameLocator, BashirLocator, testIdSelector } from './locator.js';
16
+ import { by, getTestIdAttribute } from './selectors.js';
17
+ import { VisualInspector } from './visual.js';
18
+ const GUARDED_ACTIONS = new Set(['click', 'doubleClick', 'rightClick', 'tap', 'press', 'check', 'uncheck', 'dispatchEvent']);
19
+ /** Keys that activate the focused element or submit its form. */
20
+ const ACTIVATION_KEY = /(^|\+)(Enter|NumpadEnter| |Space)$/;
21
+ const isEnterKey = (key) => /(^|\+)(Enter|NumpadEnter)$/.test(key);
22
+ /**
23
+ * Runs in the page: describes what activating `el` (or the focused element) would do — its accessible
24
+ * text and, for Enter inside a form, the form's submit controls. Self-contained (no closures).
25
+ */
26
+ function describeActivation(first, second) {
27
+ // Called as locator.evaluate(fn, opts) → (element, opts), or page.evaluate(fn, opts) → (opts): focused element.
28
+ const isElement = typeof Element !== 'undefined' && first instanceof Element;
29
+ const enter = isElement ? second?.enter === true : first.enter === true;
30
+ const el = (isElement ? first : document.activeElement);
31
+ if (!el || el === document.body || el === document.documentElement)
32
+ return null;
33
+ const parts = [];
34
+ const add = (e) => {
35
+ const h = e;
36
+ const labels = h.labels ? Array.from(h.labels, (l) => l.textContent ?? '').join(' ') : '';
37
+ const value = h.type === 'submit' || h.type === 'button' ? (h.value ?? '') : '';
38
+ parts.push(e.getAttribute('aria-label') ?? '', e.getAttribute('title') ?? '', labels, value);
39
+ if (h.tagName === 'BUTTON' || h.tagName === 'A' || e.getAttribute('role') === 'button')
40
+ parts.push((h.innerText || h.textContent || '').slice(0, 300));
41
+ };
42
+ add(el);
43
+ const form = el.form ?? el.closest('form');
44
+ if (enter && form && el.tagName !== 'TEXTAREA') {
45
+ for (const b of Array.from(form.querySelectorAll('button:not([type=button]):not([type=reset]), input[type=submit], input[type=image]')))
46
+ add(b);
47
+ parts.push(form.getAttribute('aria-label') ?? '', form.getAttribute('name') ?? '');
48
+ }
49
+ const text = parts.filter(Boolean).join(' ').replace(/\s+/g, ' ').trim();
50
+ return text || null;
51
+ }
52
+ function normalizeSelector(selector) {
53
+ if (typeof selector !== 'string' || !selector.trim())
54
+ throw new ValidationError('Selector must be a non-empty string');
55
+ const s = selector.trim();
56
+ return s.startsWith('//') || s.startsWith('(//') ? `xpath=${s}` : s;
57
+ }
58
+ /** A frame inside a page (main frame or iframe). */
59
+ export class BashirFrame {
60
+ frame;
61
+ timeout;
62
+ host;
63
+ wrap;
64
+ constructor(frame, timeout, host = detachedHost(timeout), wrap) {
65
+ this.frame = frame;
66
+ this.timeout = timeout;
67
+ this.host = host;
68
+ this.wrap = wrap;
69
+ }
70
+ get id() {
71
+ return this.frame.id;
72
+ }
73
+ name() {
74
+ return this.frame.name();
75
+ }
76
+ url() {
77
+ return this.frame.url();
78
+ }
79
+ isMain() {
80
+ return this.frame.isMain();
81
+ }
82
+ isDetached() {
83
+ return this.frame.isDetached();
84
+ }
85
+ /** The parent frame (null for the main frame). */
86
+ parentFrame() {
87
+ const p = this.frame.parent();
88
+ return p ? this.make(p) : null;
89
+ }
90
+ /** Direct child frames. */
91
+ childFrames() {
92
+ return this.frame.children().map((f) => this.make(f));
93
+ }
94
+ make(f) {
95
+ return this.wrap ? this.wrap(f) : new BashirFrame(f, this.timeout, this.host);
96
+ }
97
+ async title() {
98
+ return this.frame.title();
99
+ }
100
+ async content() {
101
+ return this.frame.content();
102
+ }
103
+ /** Locator scoped to this frame (see `BashirLocator`). */
104
+ locator(selector, options = {}) {
105
+ const loc = new BashirLocator(this.frame, normalizeSelector(selector), this.host);
106
+ return Object.keys(options).length ? loc.filter(options) : loc;
107
+ }
108
+ getByRole(role, options = {}) {
109
+ return this.locator(by.role(role, options));
110
+ }
111
+ getByText(text, options = {}) {
112
+ return this.locator(by.text(text, options));
113
+ }
114
+ getByLabel(text, options = {}) {
115
+ return this.locator(by.label(text, options));
116
+ }
117
+ getByPlaceholder(text, options = {}) {
118
+ return this.locator(by.placeholder(text, options));
119
+ }
120
+ getByAltText(text, options = {}) {
121
+ return this.locator(by.altText(text, options));
122
+ }
123
+ getByTitle(text, options = {}) {
124
+ return this.locator(by.title(text, options));
125
+ }
126
+ getByTestId(id) {
127
+ return this.locator(testIdSelector(id, this.host.testIdAttribute()));
128
+ }
129
+ frameLocator(selector) {
130
+ return new BashirFrameLocator(this.frame, normalizeSelector(selector), this.host);
131
+ }
132
+ async click(selector, options = {}) {
133
+ await this.locator(selector).click({ ...options, timeout: options.timeout ?? this.timeout });
134
+ }
135
+ async fill(selector, value, options = {}) {
136
+ await this.locator(selector).fill(value, { timeout: options.timeout ?? this.timeout });
137
+ }
138
+ async textContent(selector) {
139
+ return this.locator(selector).textContent({ timeout: this.timeout });
140
+ }
141
+ // Selector shorthands (Playwright's frame.<action>(selector)); all go through the strict, guarded BashirLocator.
142
+ async dblclick(selector, options = {}) {
143
+ await this.locator(selector).dblclick(options);
144
+ }
145
+ async hover(selector, options = {}) {
146
+ await this.locator(selector).hover(options);
147
+ }
148
+ async tap(selector, options = {}) {
149
+ await this.locator(selector).tap(options);
150
+ }
151
+ async focus(selector, options = {}) {
152
+ await this.locator(selector).focus(options);
153
+ }
154
+ async press(selector, key, options = {}) {
155
+ await this.locator(selector).press(key, options);
156
+ }
157
+ async type(selector, text, options = {}) {
158
+ await this.locator(selector).pressSequentially(text, options);
159
+ }
160
+ async check(selector, options = {}) {
161
+ await this.locator(selector).check(options);
162
+ }
163
+ async uncheck(selector, options = {}) {
164
+ await this.locator(selector).uncheck(options);
165
+ }
166
+ async setChecked(selector, checked, options = {}) {
167
+ await this.locator(selector).setChecked(checked, options);
168
+ }
169
+ async selectOption(selector, values, options = {}) {
170
+ return this.locator(selector).selectOption(values, options);
171
+ }
172
+ async setInputFiles(selector, files, options = {}) {
173
+ await this.locator(selector).setInputFiles(files, options);
174
+ }
175
+ async dispatchEvent(selector, type, eventInit = {}, options = {}) {
176
+ await this.locator(selector).dispatchEvent(type, eventInit, options);
177
+ }
178
+ async dragAndDrop(source, target, options = {}) {
179
+ await this.locator(source).dragTo(this.locator(target), options);
180
+ }
181
+ async getAttribute(selector, name, options = {}) {
182
+ return this.locator(selector).getAttribute(name, options);
183
+ }
184
+ async innerHTML(selector, options = {}) {
185
+ return this.locator(selector).innerHTML(options);
186
+ }
187
+ async innerText(selector, options = {}) {
188
+ return this.locator(selector).innerText(options);
189
+ }
190
+ async inputValue(selector, options = {}) {
191
+ return this.locator(selector).inputValue(options);
192
+ }
193
+ async isVisible(selector) {
194
+ return this.locator(selector).isVisible();
195
+ }
196
+ async isHidden(selector) {
197
+ return this.locator(selector).isHidden();
198
+ }
199
+ async isEnabled(selector, options = {}) {
200
+ return this.locator(selector).isEnabled(options);
201
+ }
202
+ async isDisabled(selector, options = {}) {
203
+ return this.locator(selector).isDisabled(options);
204
+ }
205
+ async isEditable(selector, options = {}) {
206
+ return this.locator(selector).isEditable(options);
207
+ }
208
+ async isChecked(selector, options = {}) {
209
+ return this.locator(selector).isChecked(options);
210
+ }
211
+ /** Waits for an element state (Playwright's `frame.waitForSelector`, without returning a handle). */
212
+ async waitForSelector(selector, options = {}) {
213
+ await this.locator(selector).waitFor(options);
214
+ }
215
+ async waitForTimeout(ms) {
216
+ if (!Number.isFinite(ms) || ms < 0)
217
+ throw new ValidationError('waitForTimeout needs a non-negative number of milliseconds');
218
+ await new Promise((r) => setTimeout(r, ms));
219
+ }
220
+ /** Waits for the frame to reach a load state (default `load`). */
221
+ async waitForLoadState(state = 'load', options = {}) {
222
+ return this.frame.waitForLoadState(state, { timeout: options.timeout ?? this.timeout });
223
+ }
224
+ /** Runs a function in the frame (local only, like `page.evaluate`). */
225
+ async evaluate(fn, arg) {
226
+ this.host.assertCodeExecution?.('frame.evaluate');
227
+ return this.frame.evaluate(fn, arg);
228
+ }
229
+ async extract(options = {}) {
230
+ return extractDocument(await this.frame.content(), { ...options, url: this.frame.url() });
231
+ }
232
+ }
233
+ /** Host for frames built without a page (keeps the two-argument constructor working). */
234
+ function detachedHost(timeout) {
235
+ return {
236
+ pageId: '',
237
+ defaultTimeout: () => timeout,
238
+ assertUsable: () => undefined,
239
+ guard: () => Promise.reject(new ValidationError('guardConsequential needs a frame obtained from a page')),
240
+ guardByDefault: () => false,
241
+ emit: () => undefined,
242
+ emitFailure: () => undefined,
243
+ validateUploads: () => {
244
+ throw new ValidationError('File uploads need a frame obtained from a page');
245
+ },
246
+ testIdAttribute: () => getTestIdAttribute(),
247
+ };
248
+ }
249
+ /**
250
+ * A browser tab. Provides navigation, content access, extraction, low-level and smart interaction,
251
+ * visual inspection, network monitoring, dialogs, downloads and frames.
252
+ */
253
+ export class BashirPage {
254
+ adapter;
255
+ context;
256
+ services;
257
+ id = createId('page');
258
+ smart;
259
+ visual;
260
+ network;
261
+ navigation;
262
+ dialogs;
263
+ downloads;
264
+ consoleBuffer = [];
265
+ downloadRecords = [];
266
+ pendingDownloads = new Set();
267
+ nextDialog = null;
268
+ disposers = [];
269
+ closed = false;
270
+ /** @internal Hooks that make `BashirLocator` actions behave like page actions. */
271
+ locatorHost;
272
+ emitter;
273
+ constructor(adapter, context, services) {
274
+ this.adapter = adapter;
275
+ this.context = context;
276
+ this.services = services;
277
+ const cfg = services.config;
278
+ adapter.setDefaultTimeout(cfg.browser.timeout);
279
+ this.locatorHost = {
280
+ pageId: this.id,
281
+ defaultTimeout: () => this.services.config.browser.timeout,
282
+ assertUsable: () => this.assertUsable(),
283
+ guard: (action, selector, locator, activationKey) => activationKey !== undefined ? this.guardActivation(action, locator, activationKey) : this.guardElement(action, selector, locator),
284
+ guardByDefault: () => this.services.config.security.approval.guardSelectors === true,
285
+ emit: (event, target) => this.services.events.emit(event, { pageId: this.id, target }),
286
+ emitFailure: (action, target, error) => this.services.events.emit('interaction:failed', { pageId: this.id, action, target, error }),
287
+ validateUploads: (files) => files.map((f) => validateUploadPath(f, this.services.config.security.uploads.allowedDirs)),
288
+ assertCodeExecution: (api) => assertCodeExecution(this.services, api),
289
+ // An explicit config value wins; otherwise follow the process-wide selectors.setTestIdAttribute().
290
+ testIdAttribute: () => this.services.config.browser.testIdAttribute !== 'data-testid' ? this.services.config.browser.testIdAttribute : getTestIdAttribute(),
291
+ };
292
+ this.emitter = new TypedEmitter((event) => this.subscribe(event), (event, error) => this.services.logger.warn('page event listener failed', { event: String(event), error: error?.message }));
293
+ this.smart = new SmartInteraction(this);
294
+ this.visual = new VisualInspector(adapter, {
295
+ confine: (path) => confineOutput(services, path),
296
+ note: (path) => noteArtifact(services, 'screenshots', path),
297
+ });
298
+ this.network = new NetworkMonitor(adapter, this.id, services.events);
299
+ this.navigation = new NavigationManager(adapter, this.id, services.events, { timeout: cfg.browser.navigationTimeout, maxRedirects: cfg.network.maxRedirects }, services.policy);
300
+ const dialogHistory = [];
301
+ this.dialogs = {
302
+ history: dialogHistory,
303
+ handleNext: (response) => {
304
+ this.nextDialog = response;
305
+ },
306
+ };
307
+ const findDownload = (id) => {
308
+ const rec = this.downloadRecords.find((d) => d.id === id);
309
+ if (!rec)
310
+ throw new ValidationError(`Unknown download "${id}"`);
311
+ if (rec.status !== 'completed' || !rec.path)
312
+ throw new ValidationError(`Download "${id}" is ${rec.status === 'completed' ? 'deleted' : rec.status}`);
313
+ return { rec, path: rec.path };
314
+ };
315
+ this.downloads = {
316
+ list: () => this.downloadRecords.map((d) => ({ ...d })),
317
+ saveAs: async (id, path) => {
318
+ const { path: source } = findDownload(id);
319
+ if (typeof path !== 'string' || !path)
320
+ throw new ValidationError('saveAs needs a destination path');
321
+ const out = confineOutput(this.services, path);
322
+ mkdirSync(dirname(out), { recursive: true });
323
+ copyFileSync(source, out);
324
+ return out;
325
+ },
326
+ delete: async (id) => {
327
+ const { rec, path } = findDownload(id);
328
+ rmSync(path, { force: true });
329
+ rec.path = null;
330
+ },
331
+ };
332
+ this.disposers.push(adapter.on('dialog', (d) => void this.onDialog(d, dialogHistory)), adapter.on('download', (d) => {
333
+ const p = this.onDownload(d);
334
+ this.pendingDownloads.add(p);
335
+ void p.finally(() => this.pendingDownloads.delete(p));
336
+ }), adapter.on('console', (m) => {
337
+ this.consoleBuffer.push(m);
338
+ if (this.consoleBuffer.length > 500)
339
+ this.consoleBuffer.shift();
340
+ }), adapter.on('pageerror', (e) => {
341
+ this.consoleBuffer.push({ type: 'pageerror', text: e.message, location: null });
342
+ if (this.consoleBuffer.length > 500)
343
+ this.consoleBuffer.shift();
344
+ }), adapter.on('close', () => this.markClosed()));
345
+ // Browsers outside the egress proxy (connected ones) still get request-level policy enforcement.
346
+ if (!context.browser.proxied && services.policy)
347
+ void this.network.enforcePolicy(services.policy);
348
+ if (cfg.network.blockResources.length)
349
+ void this.network.block({ resourceTypes: cfg.network.blockResources, reason: 'blocked by network.blockResources' });
350
+ }
351
+ async onDialog(d, history) {
352
+ if (this.emitter.listenerCount('dialog') > 0 && !this.nextDialog) {
353
+ // Playwright semantics: with a listener attached, the listener decides.
354
+ let decision = null;
355
+ const event = {
356
+ type: d.type,
357
+ message: d.message,
358
+ defaultValue: d.defaultValue,
359
+ accept: async (promptText) => {
360
+ if (decision)
361
+ throw new ValidationError('Dialog was already handled');
362
+ decision = 'accepted';
363
+ await d.accept(promptText);
364
+ },
365
+ dismiss: async () => {
366
+ if (decision)
367
+ throw new ValidationError('Dialog was already handled');
368
+ decision = 'dismissed';
369
+ await d.dismiss();
370
+ },
371
+ get handled() {
372
+ return decision !== null;
373
+ },
374
+ };
375
+ await this.emitter.emit('dialog', event);
376
+ // waitForEvent('dialog') callers handle the dialog after their promise resolves: give them a tick.
377
+ if (!decision)
378
+ await new Promise((r) => setTimeout(r, 50));
379
+ if (!decision) {
380
+ // No listener handled it: fall back to the safe default instead of hanging the page.
381
+ decision = d.type === 'alert' || d.type === 'beforeunload' ? 'accepted' : 'dismissed';
382
+ await (decision === 'accepted' ? d.accept() : d.dismiss()).catch(() => undefined);
383
+ }
384
+ history.push({ type: d.type, message: d.message.slice(0, 500), action: decision, time: new Date().toISOString() });
385
+ if (history.length > 200)
386
+ history.shift();
387
+ return;
388
+ }
389
+ const override = this.nextDialog;
390
+ this.nextDialog = null;
391
+ // Safe defaults: acknowledge alerts, dismiss confirmations and prompts unless explicitly told otherwise.
392
+ const accept = override ? override.accept : d.type === 'alert' || d.type === 'beforeunload';
393
+ try {
394
+ if (accept)
395
+ await d.accept(override?.promptText);
396
+ else
397
+ await d.dismiss();
398
+ }
399
+ catch (error) {
400
+ this.services.logger.debug('dialog handling failed', { error: error.message });
401
+ }
402
+ history.push({ type: d.type, message: d.message.slice(0, 500), action: accept ? 'accepted' : 'dismissed', time: new Date().toISOString() });
403
+ if (history.length > 200)
404
+ history.shift();
405
+ }
406
+ async onDownload(d) {
407
+ const policy = this.services.config.security.downloads;
408
+ const name = sanitizeFilename(d.suggestedFilename());
409
+ const record = {
410
+ id: createId('dl'),
411
+ url: redactUrl(d.url()),
412
+ suggestedFilename: name,
413
+ path: null,
414
+ size: null,
415
+ status: 'completed',
416
+ reason: null,
417
+ time: new Date().toISOString(),
418
+ };
419
+ this.services.events.emit('download:started', { pageId: this.id, url: record.url, suggestedFilename: name });
420
+ const pre = checkDownload(name, null, policy);
421
+ if (!pre.allowed) {
422
+ record.status = 'blocked';
423
+ record.reason = pre.reason ?? 'blocked';
424
+ await d.cancel().catch(() => undefined);
425
+ await d.delete().catch(() => undefined);
426
+ }
427
+ else {
428
+ try {
429
+ mkdirSync(this.services.downloadsDir, { recursive: true });
430
+ const path = join(this.services.downloadsDir, `${record.id}-${name}`);
431
+ await d.saveAs(path);
432
+ const size = statSync(path).size;
433
+ const post = checkDownload(name, size, policy);
434
+ if (!post.allowed) {
435
+ rmSync(path, { force: true });
436
+ record.status = 'blocked';
437
+ record.reason = post.reason ?? 'blocked';
438
+ }
439
+ else {
440
+ record.path = path;
441
+ record.size = size;
442
+ noteArtifact(this.services, 'downloads', path);
443
+ }
444
+ }
445
+ catch (error) {
446
+ record.status = 'failed';
447
+ record.reason = (await d.failure().catch(() => null)) ?? error.message;
448
+ }
449
+ }
450
+ this.downloadRecords.push(record);
451
+ this.services.events.emit('download:completed', { pageId: this.id, url: record.url, path: record.path, size: record.size });
452
+ void this.emitter.emit('download', { ...record });
453
+ return record;
454
+ }
455
+ // ---------------------------------------------------------------- events
456
+ /**
457
+ * Subscribes to a page event (Playwright's `page.on`). Returns an unsubscribe function.
458
+ * Frames, popups and downloads are delivered as BashirWeb objects. With a `dialog` listener the
459
+ * listener must accept or dismiss; unhandled dialogs fall back to the safe default.
460
+ */
461
+ on(event, listener) {
462
+ return this.emitter.on(event, listener);
463
+ }
464
+ once(event, listener) {
465
+ return this.emitter.once(event, listener);
466
+ }
467
+ off(event, listener) {
468
+ this.emitter.off(event, listener);
469
+ }
470
+ /** Resolves with the next matching event (Playwright's `page.waitForEvent`). */
471
+ waitForEvent(event, options = {}) {
472
+ this.assertUsable();
473
+ return this.emitter.waitFor(event, {
474
+ timeout: options.timeout ?? this.services.config.browser.timeout,
475
+ ...(options.predicate ? { predicate: options.predicate } : {}),
476
+ });
477
+ }
478
+ subscribe(event) {
479
+ const fire = (name, payload) => void this.emitter.emit(name, payload);
480
+ const a = this.adapter;
481
+ let off = null;
482
+ switch (event) {
483
+ case 'request':
484
+ case 'response':
485
+ case 'requestfailed':
486
+ case 'requestfinished':
487
+ case 'console':
488
+ case 'pageerror':
489
+ off = a.on(event, (p) => fire(event, p));
490
+ break;
491
+ case 'popup':
492
+ off = a.on('popup', (p) => fire('popup', this.context.wrapExistingPage(p)));
493
+ break;
494
+ case 'framenavigated':
495
+ off = a.on('framenavigated', (p) => {
496
+ if (p.frame)
497
+ fire('framenavigated', this.wrapFrame(p.frame));
498
+ });
499
+ break;
500
+ case 'frameattached':
501
+ case 'framedetached':
502
+ off = a.on(event, (p) => fire(event, this.wrapFrame(p.frame)));
503
+ break;
504
+ case 'load':
505
+ case 'domcontentloaded':
506
+ case 'crash':
507
+ off = a.on(event, () => fire(event, undefined));
508
+ break;
509
+ case 'websocket':
510
+ off = a.on('websocket', (ws) => fire('websocket', { url: ws.url() }));
511
+ break;
512
+ case 'worker':
513
+ off = a.on('worker', (w) => fire('worker', { url: w.url }));
514
+ break;
515
+ default:
516
+ break; // dialog, download, close are emitted by the page itself
517
+ }
518
+ if (off)
519
+ this.disposers.push(off);
520
+ }
521
+ markClosed() {
522
+ if (this.closed)
523
+ return;
524
+ this.closed = true;
525
+ void this.emitter.emit('close', undefined).finally(() => this.emitter.clear());
526
+ for (const d of this.disposers.splice(0))
527
+ d();
528
+ this.network.dispose();
529
+ this.navigation.dispose();
530
+ this.context.forgetPage(this);
531
+ this.services.events.emit('page:closed', { pageId: this.id });
532
+ }
533
+ assertUsable() {
534
+ if (this.closed)
535
+ throw new SessionError('Page is closed', { details: { pageId: this.id } });
536
+ this.context.assertActive();
537
+ }
538
+ get isClosed() {
539
+ return this.closed;
540
+ }
541
+ // ---------------------------------------------------------------- navigation
542
+ /** Navigates to a URL. Returns status, redirects, timing and download detection. */
543
+ async goto(url, policy = {}) {
544
+ this.assertUsable();
545
+ return this.navigation.goto(url, policy);
546
+ }
547
+ url() {
548
+ return this.adapter.url();
549
+ }
550
+ async title() {
551
+ return this.adapter.title();
552
+ }
553
+ /** Full HTML of the current document. */
554
+ async content() {
555
+ return this.adapter.content();
556
+ }
557
+ /** Replaces the document with the given HTML (useful for tests and rendering local content). */
558
+ async setContent(html, options = {}) {
559
+ this.assertUsable();
560
+ await this.adapter.setContent(html, { waitUntil: options.waitUntil ?? 'load', timeout: this.services.config.browser.navigationTimeout });
561
+ }
562
+ async reload(policy = {}) {
563
+ this.assertUsable();
564
+ return this.navigation.reload(policy);
565
+ }
566
+ async back(policy = {}) {
567
+ this.assertUsable();
568
+ return this.navigation.back(policy);
569
+ }
570
+ async forward(policy = {}) {
571
+ this.assertUsable();
572
+ return this.navigation.forward(policy);
573
+ }
574
+ /** Closes the tab. */
575
+ async close() {
576
+ if (this.closed)
577
+ return;
578
+ await this.adapter.close().catch(() => undefined);
579
+ this.markClosed();
580
+ }
581
+ async bringToFront() {
582
+ await this.adapter.bringToFront();
583
+ }
584
+ // ---------------------------------------------------------------- content
585
+ /** Captures a screenshot (viewport by default). */
586
+ async screenshot(options = {}) {
587
+ this.assertUsable();
588
+ return this.visual.screenshot(options);
589
+ }
590
+ /** Evaluates a function in the page. */
591
+ async evaluate(fn, arg) {
592
+ this.assertUsable();
593
+ assertCodeExecution(this.services, 'page.evaluate');
594
+ return this.adapter.evaluate(fn, arg);
595
+ }
596
+ /** Extracts content from the rendered page (after JavaScript execution). */
597
+ async extract(options = {}) {
598
+ this.assertUsable();
599
+ const doc = extractDocument(await this.adapter.content(), { ...options, url: this.adapter.url() });
600
+ switch (options.format) {
601
+ case 'text':
602
+ return doc.text;
603
+ case 'markdown':
604
+ return doc.markdown;
605
+ case 'html':
606
+ return doc.html;
607
+ default:
608
+ return doc;
609
+ }
610
+ }
611
+ /** Structured summary of the page (interactive elements, headings, landmarks, forms). */
612
+ async inspect(options = {}) {
613
+ this.assertUsable();
614
+ return this.smart.inspect(options);
615
+ }
616
+ /** Recent console messages and page errors. */
617
+ consoleMessages(limit = 100) {
618
+ return this.consoleBuffer.slice(-limit);
619
+ }
620
+ /** Lists frames (main frame first). */
621
+ frames() {
622
+ return this.adapter.frames().map((f) => this.wrapFrame(f));
623
+ }
624
+ /** @internal */
625
+ wrapFrame(f) {
626
+ return new BashirFrame(f, this.services.config.browser.timeout, this.locatorHost, (x) => this.wrapFrame(x));
627
+ }
628
+ /** Finds a frame by name, URL substring, or the selector of its <iframe> element. */
629
+ async frame(match) {
630
+ const frames = this.adapter.frames();
631
+ const byName = frames.find((f) => f.name() === match) ?? frames.find((f) => !f.isMain() && f.url().includes(match));
632
+ if (byName)
633
+ return this.wrapFrame(byName);
634
+ // Resolve by iframe selector: compare the iframe's src with frame URLs.
635
+ const src = await this.adapter
636
+ .locator(normalizeSelector(match))
637
+ .evaluate((el) => el.src || '', null)
638
+ .catch(() => '');
639
+ const bySrc = src ? frames.find((f) => !f.isMain() && f.url() === src) : undefined;
640
+ if (!bySrc)
641
+ throw new ElementNotFoundError(`Frame "${match}" not found`, { details: { frames: frames.map((f) => ({ name: f.name(), url: redactUrl(f.url()) })) } });
642
+ return this.wrapFrame(bySrc);
643
+ }
644
+ /** Text content of the first element matching `selector` in the main frame (null when absent). */
645
+ async textContent(selector) {
646
+ this.assertUsable();
647
+ const loc = this.adapter.locator(normalizeSelector(selector));
648
+ if ((await loc.count()) === 0)
649
+ return null;
650
+ return loc.nth(0).textContent({ timeout: this.services.config.browser.timeout });
651
+ }
652
+ // ---------------------------------------------------------------- interaction (selectors)
653
+ /**
654
+ * A Playwright-style locator (CSS, `xpath=`/`//...`, `text=`, `by.*` selectors or `[ref=eN]`):
655
+ * strict, auto-waiting and composable (`filter`, `and`, `or`, `nth`, `getBy*`, `frameLocator`).
656
+ * Actions are not approval-guarded unless `guardConsequential` (or
657
+ * `security.approval.guardSelectors`) is set.
658
+ */
659
+ locator(selector, options = {}) {
660
+ const loc = new BashirLocator(this.adapter, normalizeSelector(selector), this.locatorHost);
661
+ return Object.keys(options).length ? loc.filter(options) : loc;
662
+ }
663
+ getByRole(role, options = {}) {
664
+ return this.locator(by.role(role, options));
665
+ }
666
+ getByText(text, options = {}) {
667
+ return this.locator(by.text(text, options));
668
+ }
669
+ getByLabel(text, options = {}) {
670
+ return this.locator(by.label(text, options));
671
+ }
672
+ getByPlaceholder(text, options = {}) {
673
+ return this.locator(by.placeholder(text, options));
674
+ }
675
+ getByAltText(text, options = {}) {
676
+ return this.locator(by.altText(text, options));
677
+ }
678
+ getByTitle(text, options = {}) {
679
+ return this.locator(by.title(text, options));
680
+ }
681
+ /** Element by test id (attribute from `browser.testIdAttribute`, default `data-testid`). */
682
+ getByTestId(id) {
683
+ return this.locator(testIdSelector(id, this.locatorHost.testIdAttribute()));
684
+ }
685
+ /** Element by the `[ref=eN]` marker of an AI-mode aria snapshot. */
686
+ getByRef(ref) {
687
+ return this.locator(by.ref(ref));
688
+ }
689
+ /** Locates inside the iframe matched by `selector`. */
690
+ frameLocator(selector) {
691
+ return new BashirFrameLocator(this.adapter, normalizeSelector(selector), this.locatorHost);
692
+ }
693
+ /** Waits for the main frame to reach a load state (Playwright's `page.waitForLoadState`). */
694
+ async waitForLoadState(state = 'load', options = {}) {
695
+ this.assertUsable();
696
+ await this.adapter.waitForLoadState(state, { timeout: options.timeout ?? this.services.config.browser.navigationTimeout });
697
+ }
698
+ /** API client sharing this page's context cookies (Playwright's `page.request`). */
699
+ async request() {
700
+ return this.context.request();
701
+ }
702
+ /** The top-level frame. */
703
+ mainFrame() {
704
+ return this.wrapFrame(this.adapter.mainFrame());
705
+ }
706
+ async resolve(selector, action, options) {
707
+ this.assertUsable();
708
+ const sel = normalizeSelector(selector);
709
+ const timeout = options.timeout ?? this.services.config.browser.timeout;
710
+ const recoverEnabled = (options.recover ?? this.services.config.recovery.enabled) && !this.services.recovery.isCancelled;
711
+ const loc = this.adapter.locator(sel);
712
+ let count = await loc.count();
713
+ if (count === 0) {
714
+ const fp = recoverEnabled ? this.services.memory.recallAnyPath(this.adapter.url(), sel) : undefined;
715
+ try {
716
+ await loc.waitFor({ state: 'attached', timeout: fp ? Math.min(timeout, 1500) : timeout });
717
+ count = await loc.count();
718
+ }
719
+ catch {
720
+ if (!fp) {
721
+ throw new ElementNotFoundError(`No element matches selector "${selector}"`, {
722
+ details: { selector, timeout },
723
+ hint: 'Check the selector, or use page.smart.* to locate elements by their accessible name.',
724
+ });
725
+ }
726
+ const snapshot = await this.smart.scan();
727
+ const decision = this.services.recovery.decide({
728
+ target: selector,
729
+ action,
730
+ url: redactUrl(this.adapter.url()),
731
+ fingerprint: fp,
732
+ candidates: snapshot.elements,
733
+ consequential: false,
734
+ });
735
+ if (!decision.accepted || !decision.element) {
736
+ throw new ElementNotFoundError(`No element matches selector "${selector}" and recovery was not confident: ${decision.reason}`, {
737
+ details: { selector, recovery: decision.record },
738
+ });
739
+ }
740
+ this.services.events.emit('locator:recovered', { pageId: this.id, target: selector, confidence: decision.confidence, strategy: 'fingerprint' });
741
+ const frame = snapshot.frames.get(decision.element.frameIndex) ?? this.adapter.mainFrame();
742
+ return { locator: frame.locator(`[data-bw-ref="${decision.element.ref}"]`), recovered: true, confidence: decision.confidence };
743
+ }
744
+ }
745
+ if (count > 1 && options.index === undefined) {
746
+ throw new AmbiguousElementError(`Selector "${selector}" matches ${count} elements`, {
747
+ details: { selector, count },
748
+ hint: 'Pass { index } or use a more specific selector.',
749
+ });
750
+ }
751
+ const target = count > 1 ? loc.nth(options.index ?? 0) : loc;
752
+ if (recoverEnabled)
753
+ await this.rememberFingerprint(target, sel).catch(() => undefined);
754
+ return { locator: target, recovered: false };
755
+ }
756
+ async rememberFingerprint(locator, selector) {
757
+ await locator.evaluate((el) => el.setAttribute('data-bw-probe', '1'), null);
758
+ try {
759
+ const result = await this.adapter.evaluate(scanDocument, {
760
+ scanId: 'probe',
761
+ includeHidden: true,
762
+ includeNonInteractive: true,
763
+ near: null,
764
+ maxElements: 1,
765
+ only: '[data-bw-probe]',
766
+ });
767
+ const el = result.elements[0];
768
+ if (el)
769
+ this.services.memory.remember(this.adapter.url(), selector, fingerprintOf(el, this.adapter.url()));
770
+ }
771
+ finally {
772
+ await locator.evaluate((el) => el.removeAttribute('data-bw-probe'), null).catch(() => undefined);
773
+ }
774
+ }
775
+ async guardElement(action, selector, locator) {
776
+ const d = await locator.evaluate((el) => {
777
+ const h = el;
778
+ const labelled = el.getAttribute('aria-labelledby');
779
+ const byId = labelled
780
+ ? labelled
781
+ .split(/\s+/)
782
+ .map((id) => document.getElementById(id)?.textContent ?? '')
783
+ .join(' ')
784
+ : '';
785
+ const labels = h.labels ? [...h.labels].map((l) => l.textContent ?? '').join(' ') : '';
786
+ const hint = el.getAttribute('data-bw-consequential') !== null;
787
+ return {
788
+ name: [el.getAttribute('aria-label'), byId, labels, el.getAttribute('title'), el.getAttribute('alt')].filter(Boolean).join(' '),
789
+ text: (h.innerText || el.textContent || '').slice(0, 300),
790
+ value: h.type === 'submit' || h.type === 'button' ? (h.value ?? '') : '',
791
+ hint,
792
+ };
793
+ }, null);
794
+ const cls = this.services.policyEngine.classify([d.name, d.text, d.value], {
795
+ url: redactUrl(this.adapter.url()),
796
+ hint: d.hint,
797
+ });
798
+ if (!cls.consequential)
799
+ return;
800
+ await this.services.approvals.require({
801
+ action,
802
+ target: (d.name || d.text || selector).slice(0, 200),
803
+ url: redactUrl(this.adapter.url()),
804
+ categories: cls.categories,
805
+ reasons: cls.reasons,
806
+ });
807
+ }
808
+ /**
809
+ * Classifies what an activation key (Enter/Space) pressed without a selector would trigger: the focused
810
+ * element and, for Enter inside a form, the form's submit controls.
811
+ */
812
+ async guardFocused(action, key) {
813
+ const text = await this.adapter.evaluate(describeActivation, { enter: isEnterKey(key) });
814
+ await this.requireIfConsequential(action, `${key} on`, text);
815
+ }
816
+ /** Keyboard activation on an element: Enter on a field submits its form, so its submit controls count too. */
817
+ async guardActivation(action, locator, key) {
818
+ if (!ACTIVATION_KEY.test(key))
819
+ return;
820
+ const text = await locator.evaluate(describeActivation, { enter: isEnterKey(key) });
821
+ await this.requireIfConsequential(action, `${key} on`, text);
822
+ }
823
+ async requireIfConsequential(action, prefix, text) {
824
+ if (!text)
825
+ return;
826
+ const cls = this.services.policyEngine.classify([text], { url: redactUrl(this.adapter.url()) });
827
+ if (!cls.consequential)
828
+ return;
829
+ await this.services.approvals.require({
830
+ action,
831
+ target: `${prefix} ${text}`.trim().slice(0, 200),
832
+ url: redactUrl(this.adapter.url()),
833
+ categories: cls.categories,
834
+ reasons: cls.reasons,
835
+ });
836
+ }
837
+ async act(action, selector, options, run) {
838
+ const started = Date.now();
839
+ const timeout = options.timeout ?? this.services.config.browser.timeout;
840
+ try {
841
+ const { locator, recovered, confidence } = await this.resolve(selector, action, options);
842
+ if (options.guardConsequential && options.activationKey !== undefined)
843
+ await this.guardActivation(action, locator, options.activationKey);
844
+ else if (options.guardConsequential && GUARDED_ACTIONS.has(action))
845
+ await this.guardElement(action, selector, locator);
846
+ const details = (await run(locator, timeout)) ?? {};
847
+ const result = {
848
+ success: true,
849
+ action,
850
+ target: selector,
851
+ url: redactUrl(this.adapter.url()),
852
+ duration: Date.now() - started,
853
+ error: null,
854
+ recovered,
855
+ };
856
+ if (confidence !== undefined)
857
+ details.recoveryConfidence = confidence;
858
+ if (Object.keys(details).length)
859
+ result.details = details;
860
+ if (action === 'click')
861
+ this.services.events.emit('element:clicked', { pageId: this.id, target: selector });
862
+ if (action === 'fill' || action === 'type')
863
+ this.services.events.emit('element:filled', { pageId: this.id, target: selector });
864
+ return result;
865
+ }
866
+ catch (error) {
867
+ const e = toBashirWebError(error, 'INTERACTION');
868
+ this.services.events.emit('interaction:failed', { pageId: this.id, action, target: selector, error: e.message });
869
+ if (e.code === 'RUNTIME')
870
+ throw new InteractionError(`${action} on "${selector}" failed: ${e.message}`, { cause: error, details: { selector } });
871
+ throw e;
872
+ }
873
+ }
874
+ click(selector, options = {}) {
875
+ return this.act('click', selector, options, async (loc, timeout) => {
876
+ const o = { timeout };
877
+ if (options.button)
878
+ o.button = options.button;
879
+ if (options.position)
880
+ o.position = options.position;
881
+ if (options.force)
882
+ o.force = true;
883
+ await loc.click(o);
884
+ });
885
+ }
886
+ async doubleClick(selector, options = {}) {
887
+ return this.act('doubleClick', selector, options, (loc, timeout) => loc.dblclick({ timeout }));
888
+ }
889
+ async rightClick(selector, options = {}) {
890
+ return this.act('rightClick', selector, options, (loc, timeout) => loc.click({ button: 'right', timeout }));
891
+ }
892
+ async hover(selector, options = {}) {
893
+ return this.act('hover', selector, options, (loc, timeout) => loc.hover({ timeout }));
894
+ }
895
+ async tap(selector, options = {}) {
896
+ return this.act('tap', selector, options, (loc, timeout) => loc.tap({ timeout }));
897
+ }
898
+ async focus(selector, options = {}) {
899
+ return this.act('focus', selector, options, (loc, timeout) => loc.focus({ timeout }));
900
+ }
901
+ /** Types text key by key (appends to existing content). */
902
+ async type(selector, text, options = {}) {
903
+ return this.act('type', selector, options, (loc, timeout) => loc.type(text, { delay: options.delay ?? 0, timeout }));
904
+ }
905
+ /** Replaces the value of an input, textarea or contenteditable element. */
906
+ async fill(selector, value, options = {}) {
907
+ if (typeof value !== 'string')
908
+ return Promise.reject(new ValidationError('fill value must be a string'));
909
+ return this.act('fill', selector, options, (loc, timeout) => loc.fill(value, { timeout }));
910
+ }
911
+ /** Selects options in a <select> by value or label. */
912
+ async select(selector, values, options = {}) {
913
+ const list = Array.isArray(values) ? values : [values];
914
+ return this.act('select', selector, options, async (loc, timeout) => {
915
+ let selected;
916
+ try {
917
+ selected = await loc.selectOption(list.map((v) => ({ value: v })), { timeout: Math.min(timeout, 2000) });
918
+ }
919
+ catch {
920
+ selected = await loc.selectOption(list.map((v) => ({ label: v })), { timeout });
921
+ }
922
+ return { selected };
923
+ });
924
+ }
925
+ async check(selector, options = {}) {
926
+ return this.act('check', selector, options, (loc, timeout) => loc.check({ timeout }));
927
+ }
928
+ async uncheck(selector, options = {}) {
929
+ return this.act('uncheck', selector, options, (loc, timeout) => loc.uncheck({ timeout }));
930
+ }
931
+ /** Presses a key (e.g. "Enter", "Control+A"), optionally focusing a selector first. */
932
+ async press(key, options = {}) {
933
+ if (options.selector)
934
+ return this.act('press', options.selector, { ...options, activationKey: key }, (loc, timeout) => loc.press(key, { timeout }));
935
+ this.assertUsable();
936
+ const started = Date.now();
937
+ if (options.guardConsequential && ACTIVATION_KEY.test(key))
938
+ await this.guardFocused('press', key);
939
+ await this.adapter.keyboard.press(key);
940
+ return { success: true, action: 'press', target: key, url: redactUrl(this.adapter.url()), duration: Date.now() - started, error: null };
941
+ }
942
+ /** Uploads files into a file input. Files must be inside security.uploads.allowedDirs. */
943
+ async uploadFile(selector, files, options = {}) {
944
+ let list;
945
+ try {
946
+ list = (Array.isArray(files) ? files : [files]).map((f) => validateUploadPath(f, this.services.config.security.uploads.allowedDirs));
947
+ }
948
+ catch (error) {
949
+ return Promise.reject(error);
950
+ }
951
+ return this.act('upload', selector, options, async (loc, timeout) => {
952
+ await loc.setInputFiles(list, { timeout });
953
+ return { files: list.length };
954
+ });
955
+ }
956
+ /** Drags one element onto another. */
957
+ async dragAndDrop(source, target, options = {}) {
958
+ const { locator: dest } = await this.resolve(target, 'drop', options);
959
+ return this.act('dragAndDrop', source, options, (loc, timeout) => loc.dragTo(dest, { timeout }));
960
+ }
961
+ /** Scrolls the page or an element into view. Returns the resulting scroll position. */
962
+ async scroll(options = {}) {
963
+ this.assertUsable();
964
+ const started = Date.now();
965
+ if (options.selector) {
966
+ await this.act('scrollIntoView', options.selector, {}, (loc, timeout) => loc.scrollIntoView({ timeout }));
967
+ }
968
+ else {
969
+ await this.adapter.evaluate((o) => {
970
+ if (o.to === 'top')
971
+ window.scrollTo(0, 0);
972
+ else if (o.to === 'bottom')
973
+ window.scrollTo(window.scrollX, document.documentElement.scrollHeight);
974
+ else if (o.to)
975
+ window.scrollTo(o.to.x ?? window.scrollX, o.to.y ?? window.scrollY);
976
+ else
977
+ window.scrollBy(o.by?.x ?? 0, o.by?.y ?? window.innerHeight * 0.8);
978
+ }, { ...(options.to !== undefined ? { to: options.to } : {}), ...(options.by !== undefined ? { by: options.by } : {}) });
979
+ }
980
+ const pos = await this.adapter.evaluate(() => ({ x: window.scrollX, y: window.scrollY, atBottom: Math.ceil(window.scrollY + window.innerHeight) >= document.documentElement.scrollHeight - 2 }), null);
981
+ return {
982
+ success: true,
983
+ action: 'scroll',
984
+ target: options.selector ?? JSON.stringify(options.to ?? options.by ?? 'down'),
985
+ url: redactUrl(this.adapter.url()),
986
+ duration: Date.now() - started,
987
+ error: null,
988
+ details: pos,
989
+ };
990
+ }
991
+ /** Waits for a selector state, text, URL, load state, network idle or a fixed time. */
992
+ async waitFor(options) {
993
+ this.assertUsable();
994
+ const o = typeof options === 'string' ? { selector: options } : options;
995
+ const started = Date.now();
996
+ const timeout = o.timeout ?? this.services.config.browser.timeout;
997
+ let target = 'time';
998
+ try {
999
+ if (o.selector) {
1000
+ target = o.selector;
1001
+ await this.adapter
1002
+ .locator(normalizeSelector(o.selector))
1003
+ .nth(0)
1004
+ .waitFor({ state: o.state ?? 'visible', timeout });
1005
+ }
1006
+ else if (o.text) {
1007
+ target = `text:${o.text}`;
1008
+ await this.adapter.waitForFunction((t) => document.body?.innerText.includes(t) ?? false, o.text, { timeout, polling: 100 });
1009
+ }
1010
+ else if (o.url) {
1011
+ target = `url:${String(o.url)}`;
1012
+ await this.navigation.waitForUrlChange({ timeout, matches: o.url });
1013
+ }
1014
+ else if (o.networkIdle) {
1015
+ target = 'networkidle';
1016
+ await this.navigation.waitForNetworkIdle(timeout);
1017
+ }
1018
+ else if (o.loadState) {
1019
+ target = o.loadState;
1020
+ await this.adapter.waitForLoadState(o.loadState, { timeout });
1021
+ }
1022
+ else if (o.time !== undefined) {
1023
+ if (o.time < 0 || o.time > 300_000)
1024
+ throw new ValidationError('wait time must be between 0 and 300000 ms');
1025
+ await this.adapter.waitForTimeout(o.time);
1026
+ }
1027
+ else
1028
+ throw new ValidationError('waitFor requires selector, text, url, networkIdle, loadState or time');
1029
+ }
1030
+ catch (error) {
1031
+ const e = toBashirWebError(error);
1032
+ if (e instanceof TimeoutError || e.code === 'TIMEOUT')
1033
+ throw new TimeoutError(`Timed out after ${timeout}ms waiting for ${target}`, { cause: error, details: { target, timeout } });
1034
+ throw e;
1035
+ }
1036
+ return { success: true, action: 'wait', target, url: redactUrl(this.adapter.url()), duration: Date.now() - started, error: null };
1037
+ }
1038
+ /** The page's `localStorage` for its current origin (Playwright's `page.localStorage`). */
1039
+ get localStorage() {
1040
+ return this.webStorage('local');
1041
+ }
1042
+ /** The page's `sessionStorage` for its current origin. */
1043
+ get sessionStorage() {
1044
+ return this.webStorage('session');
1045
+ }
1046
+ webStorage(kind) {
1047
+ const run = async (fn) => {
1048
+ this.assertUsable();
1049
+ try {
1050
+ return await fn(this.adapter.webStorage(kind));
1051
+ }
1052
+ catch (error) {
1053
+ throw toBashirWebError(error, 'RUNTIME');
1054
+ }
1055
+ };
1056
+ const str = (what, v) => {
1057
+ if (typeof v !== 'string')
1058
+ throw new ValidationError(`${what} must be a string`);
1059
+ return v;
1060
+ };
1061
+ return {
1062
+ getItem: async (name) => run((s) => s.getItem(str('name', name))),
1063
+ setItem: async (name, value) => run((s) => s.setItem(str('name', name), str('value', value))),
1064
+ removeItem: async (name) => run((s) => s.removeItem(str('name', name))),
1065
+ clear: async () => run((s) => s.clear()),
1066
+ items: async () => run((s) => s.items()),
1067
+ };
1068
+ }
1069
+ /** Mouse, keyboard and touch primitives (coordinates are viewport CSS pixels). */
1070
+ get mouse() {
1071
+ return this.adapter.mouse;
1072
+ }
1073
+ get keyboard() {
1074
+ return this.adapter.keyboard;
1075
+ }
1076
+ get touchscreen() {
1077
+ return this.adapter.touchscreen;
1078
+ }
1079
+ /** Runs `trigger` and resolves with the download it starts (after it is saved and policy-checked). */
1080
+ async waitForDownload(trigger, timeout = this.services.config.browser.timeout) {
1081
+ this.assertUsable();
1082
+ const before = this.downloadRecords.length;
1083
+ const pendingBefore = new Set(this.pendingDownloads);
1084
+ await trigger();
1085
+ const deadline = Date.now() + timeout;
1086
+ while (Date.now() < deadline) {
1087
+ const fresh = [...this.pendingDownloads].filter((p) => !pendingBefore.has(p));
1088
+ if (fresh.length)
1089
+ return fresh[0];
1090
+ if (this.downloadRecords.length > before)
1091
+ return this.downloadRecords[before];
1092
+ await new Promise((r) => setTimeout(r, 50));
1093
+ }
1094
+ throw new TimeoutError(`No download started within ${timeout}ms`);
1095
+ }
1096
+ /** Runs `trigger` and resolves with the popup/new tab it opens. */
1097
+ async waitForPopup(trigger, timeout = this.services.config.browser.timeout) {
1098
+ this.assertUsable();
1099
+ const popup = new Promise((resolve, reject) => {
1100
+ const timer = setTimeout(() => {
1101
+ off();
1102
+ reject(new TimeoutError(`No popup opened within ${timeout}ms`));
1103
+ }, timeout);
1104
+ const off = this.adapter.on('popup', (p) => {
1105
+ clearTimeout(timer);
1106
+ off();
1107
+ resolve(p);
1108
+ });
1109
+ });
1110
+ await trigger();
1111
+ const adapter = await popup;
1112
+ const page = this.context.wrapExistingPage(adapter);
1113
+ await adapter.waitForLoadState('domcontentloaded', { timeout }).catch(() => undefined);
1114
+ return page;
1115
+ }
1116
+ // ---------------------------------------------------------------- element state (no waiting)
1117
+ /** Counts elements matching `selector` without waiting. */
1118
+ async count(selector) {
1119
+ this.assertUsable();
1120
+ return this.adapter.locator(normalizeSelector(selector)).count();
1121
+ }
1122
+ async single(selector, options, need) {
1123
+ this.assertUsable();
1124
+ const loc = this.adapter.locator(normalizeSelector(selector));
1125
+ const n = await loc.count();
1126
+ if (n === 0) {
1127
+ if (!need)
1128
+ return null;
1129
+ throw new ElementNotFoundError(`No element matches selector "${selector}"`, { details: { selector } });
1130
+ }
1131
+ if (options.index !== undefined) {
1132
+ if (!Number.isInteger(options.index) || options.index < 0 || options.index >= n)
1133
+ throw new ValidationError(`index ${options.index} is out of range (${n} matches)`);
1134
+ return loc.nth(options.index);
1135
+ }
1136
+ if (n > 1)
1137
+ throw new AmbiguousElementError(`Selector "${selector}" matches ${n} elements`, {
1138
+ details: { selector, count: n },
1139
+ hint: 'Pass { index } or refine the selector.',
1140
+ });
1141
+ return loc;
1142
+ }
1143
+ /** True when an element matches and is visible. Missing elements are not visible. */
1144
+ async isVisible(selector, options = {}) {
1145
+ const loc = await this.single(selector, options, false);
1146
+ return loc ? (await loc.state()).visible : false;
1147
+ }
1148
+ async isHidden(selector, options = {}) {
1149
+ return !(await this.isVisible(selector, options));
1150
+ }
1151
+ async isEnabled(selector, options = {}) {
1152
+ return (await (await this.single(selector, options, true)).state()).enabled;
1153
+ }
1154
+ async isDisabled(selector, options = {}) {
1155
+ return !(await this.isEnabled(selector, options));
1156
+ }
1157
+ async isEditable(selector, options = {}) {
1158
+ return (await (await this.single(selector, options, true)).state()).editable;
1159
+ }
1160
+ /** Checked state of a checkbox/radio (or ARIA checked); throws for other elements. */
1161
+ async isChecked(selector, options = {}) {
1162
+ const checked = (await (await this.single(selector, options, true)).state()).checked;
1163
+ if (checked === null)
1164
+ throw new ValidationError(`Element "${selector}" is not a checkbox or radio`);
1165
+ return checked;
1166
+ }
1167
+ /** Current value of an input, textarea or select. */
1168
+ async inputValue(selector, options = {}) {
1169
+ return (await this.single(selector, options, true)).inputValue({ timeout: this.services.config.browser.timeout });
1170
+ }
1171
+ /** Rendered text of an element (respects CSS, unlike textContent). */
1172
+ async innerText(selector, options = {}) {
1173
+ return (await this.single(selector, options, true)).innerText({ timeout: this.services.config.browser.timeout });
1174
+ }
1175
+ async innerHTML(selector, options = {}) {
1176
+ return (await this.single(selector, options, true)).innerHTML({ timeout: this.services.config.browser.timeout });
1177
+ }
1178
+ /** Attribute value, or null when the element lacks it. */
1179
+ async getAttribute(selector, name, options = {}) {
1180
+ return (await this.single(selector, options, true)).getAttribute(name, { timeout: this.services.config.browser.timeout });
1181
+ }
1182
+ /** Text content of every element matching `selector`. */
1183
+ async allTextContents(selector) {
1184
+ this.assertUsable();
1185
+ return this.adapter.locator(normalizeSelector(selector)).allTextContents();
1186
+ }
1187
+ /** Rendered text of every element matching `selector`. */
1188
+ async allInnerTexts(selector) {
1189
+ this.assertUsable();
1190
+ return this.adapter.locator(normalizeSelector(selector)).allInnerTexts();
1191
+ }
1192
+ // ---------------------------------------------------------------- more element actions
1193
+ /** Clears an input or textarea. */
1194
+ async clear(selector, options = {}) {
1195
+ return this.act('clear', selector, options, (loc, timeout) => loc.clear({ timeout }));
1196
+ }
1197
+ /** Sets a checkbox/radio to the given state (no-op when it already matches). */
1198
+ async setChecked(selector, checked, options = {}) {
1199
+ return this.act(checked ? 'check' : 'uncheck', selector, options, (loc, timeout) => loc.setChecked(checked, { timeout }));
1200
+ }
1201
+ /** Selects all text of an input or element. */
1202
+ async selectText(selector, options = {}) {
1203
+ return this.act('selectText', selector, options, (loc, timeout) => loc.selectText({ timeout }));
1204
+ }
1205
+ /** Removes focus from an element. */
1206
+ async blur(selector, options = {}) {
1207
+ return this.act('blur', selector, options, (loc, timeout) => loc.blur({ timeout }));
1208
+ }
1209
+ /** Dispatches a DOM event (e.g. "click", "dragstart") on an element regardless of visibility. */
1210
+ async dispatchEvent(selector, type, eventInit = {}, options = {}) {
1211
+ if (typeof type !== 'string' || !type)
1212
+ return Promise.reject(new ValidationError('Event type must be a non-empty string'));
1213
+ return this.act('dispatchEvent', selector, options, (loc, timeout) => loc.dispatchEvent(type, eventInit, { timeout }));
1214
+ }
1215
+ /**
1216
+ * Drops files or data onto an element (drag-and-drop upload zones). Files must be inside
1217
+ * `security.uploads.allowedDirs`, as with `uploadFile`.
1218
+ */
1219
+ async dropFiles(selector, payload, options = {}) {
1220
+ let files;
1221
+ try {
1222
+ files = payload.files === undefined ? [] : (Array.isArray(payload.files) ? payload.files : [payload.files]).map((f) => this.checkUpload(f));
1223
+ if (!files.length && !payload.data)
1224
+ throw new ValidationError('dropFiles needs files or data');
1225
+ }
1226
+ catch (error) {
1227
+ return Promise.reject(error);
1228
+ }
1229
+ return this.act('drop', selector, options, async (loc, timeout) => {
1230
+ const p = {};
1231
+ if (files.length)
1232
+ p.files = files;
1233
+ if (payload.data)
1234
+ p.data = payload.data;
1235
+ await loc.drop(p, { timeout });
1236
+ return { files: files.length };
1237
+ });
1238
+ }
1239
+ /**
1240
+ * Handles a native file chooser opened by `trigger` (e.g. clicking a styled "Upload" button) and
1241
+ * selects `files`, which must be inside `security.uploads.allowedDirs`.
1242
+ */
1243
+ async chooseFiles(trigger, files, timeout = this.services.config.browser.timeout) {
1244
+ this.assertUsable();
1245
+ const started = Date.now();
1246
+ const paths = (Array.isArray(files) ? files : [files]).map((f) => this.checkUpload(f));
1247
+ const chooser = new Promise((resolve, reject) => {
1248
+ const timer = setTimeout(() => {
1249
+ off();
1250
+ reject(new TimeoutError(`No file chooser opened within ${timeout}ms`, { details: { timeout } }));
1251
+ }, timeout);
1252
+ const off = this.adapter.on('filechooser', (fc) => {
1253
+ clearTimeout(timer);
1254
+ off();
1255
+ resolve(fc);
1256
+ });
1257
+ });
1258
+ await trigger();
1259
+ const fc = await chooser;
1260
+ if (paths.length > 1 && !fc.isMultiple())
1261
+ throw new ValidationError('The file chooser accepts a single file');
1262
+ await fc.setFiles(paths, { timeout });
1263
+ return {
1264
+ success: true,
1265
+ action: 'chooseFiles',
1266
+ target: 'filechooser',
1267
+ url: redactUrl(this.adapter.url()),
1268
+ duration: Date.now() - started,
1269
+ error: null,
1270
+ details: { files: paths.length },
1271
+ };
1272
+ }
1273
+ checkUpload(file) {
1274
+ return validateUploadPath(file, this.services.config.security.uploads.allowedDirs);
1275
+ }
1276
+ /** Outlines matching elements in the page for debugging (headed mode). */
1277
+ async highlight(selector) {
1278
+ this.assertUsable();
1279
+ await this.adapter.locator(normalizeSelector(selector)).highlight();
1280
+ }
1281
+ // ---------------------------------------------------------------- accessibility snapshot
1282
+ /**
1283
+ * YAML accessibility snapshot of the page (or of `selector`). In `ai` mode every interactive node
1284
+ * carries a `[ref=eN]` marker that `by.ref("eN")` (selector `aria-ref=eN`) resolves to.
1285
+ */
1286
+ async ariaSnapshot(options = {}) {
1287
+ this.assertUsable();
1288
+ const { selector, ...rest } = options;
1289
+ if (selector)
1290
+ return (await this.single(selector, {}, true)).ariaSnapshot(rest.timeout === undefined ? {} : { timeout: rest.timeout });
1291
+ return this.adapter.ariaSnapshot(rest);
1292
+ }
1293
+ // ---------------------------------------------------------------- output: PDF, video, screencast
1294
+ /** Prints the page to PDF (Chromium only). Emulates print media unless `emulateMedia` set otherwise. */
1295
+ async pdf(options = {}) {
1296
+ this.assertUsable();
1297
+ if (this.context.browser.engine !== 'chromium')
1298
+ throw new ValidationError('PDF generation is only supported in Chromium');
1299
+ const { path: requested, ...rest } = options;
1300
+ const path = requested ? confineOutput(this.services, requested) : undefined;
1301
+ const buffer = await this.adapter.pdf(rest);
1302
+ if (path) {
1303
+ mkdirSync(dirname(path), { recursive: true });
1304
+ writeFileSync(path, buffer);
1305
+ noteArtifact(this.services, 'pdf', path);
1306
+ }
1307
+ return { buffer, path: path ?? null, bytes: buffer.byteLength, url: redactUrl(this.adapter.url()) };
1308
+ }
1309
+ /**
1310
+ * The page's video when its context records video (`newContext({ recordVideo: { dir } })`).
1311
+ * The file is complete after the page or context closes.
1312
+ */
1313
+ video() {
1314
+ const v = this.adapter.video();
1315
+ if (!v)
1316
+ return null;
1317
+ return {
1318
+ path: () => v.path(),
1319
+ saveAs: async (path) => {
1320
+ const out = confineOutput(this.services, path);
1321
+ await v.saveAs(out);
1322
+ noteArtifact(this.services, 'videos', out);
1323
+ },
1324
+ delete: () => v.delete(),
1325
+ };
1326
+ }
1327
+ /** Streams JPEG frames of the page (and/or writes a video to `path`) until `stopScreencast()`. */
1328
+ async startScreencast(options = {}) {
1329
+ this.assertUsable();
1330
+ if (!options.path && !options.onFrame)
1331
+ throw new ValidationError('startScreencast needs a path or an onFrame callback');
1332
+ if (options.quality !== undefined && !(options.quality >= 0 && options.quality <= 100))
1333
+ throw new ValidationError('quality must be within [0, 100]');
1334
+ const opts = options.path ? { ...options, path: confineOutput(this.services, options.path) } : options;
1335
+ if (opts.path)
1336
+ mkdirSync(dirname(opts.path), { recursive: true });
1337
+ await this.adapter.startScreencast(opts);
1338
+ }
1339
+ async stopScreencast() {
1340
+ return this.adapter.stopScreencast();
1341
+ }
1342
+ // ---------------------------------------------------------------- emulation
1343
+ /** Emulates media type and user preferences (`null` resets an item). */
1344
+ async emulateMedia(options) {
1345
+ this.assertUsable();
1346
+ await this.adapter.emulateMedia(options);
1347
+ }
1348
+ /** Resizes the viewport. */
1349
+ async setViewport(viewport) {
1350
+ this.assertUsable();
1351
+ if (!(viewport.width > 0 && viewport.height > 0))
1352
+ throw new ValidationError('Viewport width and height must be positive');
1353
+ await this.adapter.setViewport({ width: Math.round(viewport.width), height: Math.round(viewport.height) });
1354
+ }
1355
+ viewport() {
1356
+ return this.adapter.viewport();
1357
+ }
1358
+ /** Headers added to every request from this page. */
1359
+ async setExtraHTTPHeaders(headers) {
1360
+ this.assertUsable();
1361
+ for (const [k, v] of Object.entries(headers))
1362
+ if (typeof v !== 'string' || /[\r\n]/.test(k + v))
1363
+ throw new ValidationError(`Invalid header ${JSON.stringify(k)}`);
1364
+ await this.adapter.setExtraHTTPHeaders(headers);
1365
+ }
1366
+ /**
1367
+ * Fake timers: `page.clock.install({ time })`, then `fastForward`, `runFor`, `pauseAt`, `resume`,
1368
+ * `setFixedTime` or `setSystemTime` control Date, setTimeout, setInterval and requestAnimationFrame.
1369
+ */
1370
+ get clock() {
1371
+ return this.adapter.clock;
1372
+ }
1373
+ /** JS/CSS coverage (Chromium only; null on other engines). */
1374
+ get coverage() {
1375
+ return this.adapter.coverage;
1376
+ }
1377
+ // ---------------------------------------------------------------- scripts (local API only)
1378
+ /** Runs a script in the page and its frames before any page script, on every navigation. */
1379
+ async addInitScript(script, arg) {
1380
+ this.assertUsable();
1381
+ assertCodeExecution(this.services, 'page.addInitScript');
1382
+ await this.adapter.addInitScript(scriptSource(script, arg));
1383
+ }
1384
+ /** Injects a `<script>` (inline `content` or `url`, loaded under the network policy). */
1385
+ async addScriptTag(options) {
1386
+ this.assertUsable();
1387
+ assertCodeExecution(this.services, 'page.addScriptTag');
1388
+ if (!options.content && !options.url)
1389
+ throw new ValidationError('addScriptTag needs content or url');
1390
+ await this.adapter.addScriptTag(options);
1391
+ }
1392
+ /** Injects a `<style>` (inline `content`) or stylesheet link (`url`). */
1393
+ async addStyleTag(options) {
1394
+ this.assertUsable();
1395
+ if (!options.content && !options.url)
1396
+ throw new ValidationError('addStyleTag needs content or url');
1397
+ await this.adapter.addStyleTag(options);
1398
+ }
1399
+ /** Exposes a Node.js function to the page as `window[name]` (returns a promise in the page). */
1400
+ async exposeFunction(name, fn) {
1401
+ this.assertUsable();
1402
+ assertCodeExecution(this.services, 'page.exposeFunction');
1403
+ if (!/^[A-Za-z_$][\w$]*$/.test(name))
1404
+ throw new ValidationError('Function name must be a valid JavaScript identifier');
1405
+ await this.adapter.exposeFunction(name, fn);
1406
+ }
1407
+ /** Waits until `fn` returns a truthy value in the page. */
1408
+ async waitForFunction(fn, arg, options = {}) {
1409
+ this.assertUsable();
1410
+ assertCodeExecution(this.services, 'page.waitForFunction');
1411
+ const timeout = options.timeout ?? this.services.config.browser.timeout;
1412
+ try {
1413
+ await this.adapter.waitForFunction(fn, arg, { ...options, timeout });
1414
+ }
1415
+ catch (error) {
1416
+ if (/timeout/i.test(error.message))
1417
+ throw new TimeoutError(`waitForFunction timed out after ${timeout}ms`, { cause: error, details: { timeout } });
1418
+ throw toBashirWebError(error, 'RUNTIME');
1419
+ }
1420
+ }
1421
+ // ---------------------------------------------------------------- overlays, mocking, network waits
1422
+ /**
1423
+ * Registers a handler for an overlay that can block actions (cookie banner, newsletter modal).
1424
+ * Whenever an element matching `selector` is visible before an action, the handler runs first.
1425
+ * The handler is your code: it decides what to click (a "Reject all" button, for instance).
1426
+ */
1427
+ async addLocatorHandler(selector, handler, options = {}) {
1428
+ this.assertUsable();
1429
+ await this.adapter.addLocatorHandler(normalizeSelector(selector), () => handler(this), options);
1430
+ }
1431
+ async removeLocatorHandler(selector) {
1432
+ await this.adapter.removeLocatorHandler(normalizeSelector(selector));
1433
+ }
1434
+ /**
1435
+ * Serves matching requests from a HAR file. Missing entries are aborted by default; with
1436
+ * `notFound: "fallback"` they go to the network under the normal network policy.
1437
+ */
1438
+ async routeFromHAR(path, options = {}) {
1439
+ this.assertUsable();
1440
+ const { existsSync } = await import('node:fs');
1441
+ if (!options.update && !existsSync(path))
1442
+ throw new ValidationError(`HAR file not found: ${path}`);
1443
+ await this.adapter.routeFromHAR(options.update ? confineOutput(this.services, path) : path, options);
1444
+ }
1445
+ /** Answers matching requests from a handler or canned response (see `NetworkMonitor.mock`). */
1446
+ async mock(...args) {
1447
+ this.assertUsable();
1448
+ return this.network.mock(...args);
1449
+ }
1450
+ /** Removes page mocks for `match` (optionally only those registered with `handler`); Playwright's `page.unroute`. */
1451
+ async unmock(...args) {
1452
+ return this.network.unmock(...args);
1453
+ }
1454
+ /**
1455
+ * Replaces the server for WebSockets whose URL matches: the handler receives a connection to the
1456
+ * page and can send messages, react to them and close. No network connection is made.
1457
+ */
1458
+ async mockWebSocket(match, handler) {
1459
+ this.assertUsable();
1460
+ return this.adapter.mockWebSocket((url) => urlMatches(match, url), handler);
1461
+ }
1462
+ /** Resolves with the next matching request (URL and headers redacted). */
1463
+ async waitForRequest(...args) {
1464
+ this.assertUsable();
1465
+ return this.network.waitForRequest(...args);
1466
+ }
1467
+ /** Resolves with the next matching response; its body can be read once. */
1468
+ async waitForResponse(match, options = {}) {
1469
+ this.assertUsable();
1470
+ return this.network.waitForResponse(match, { timeout: this.services.config.browser.timeout, ...options });
1471
+ }
1472
+ /** Web workers currently running in the page. */
1473
+ workers() {
1474
+ return this.adapter.workers().map((w) => ({ url: redactUrl(w.url) }));
1475
+ }
1476
+ /** Asks the engine to run garbage collection (useful for leak checks). */
1477
+ async requestGC() {
1478
+ this.assertUsable();
1479
+ await this.adapter.requestGC();
1480
+ }
1481
+ /** Opens the Playwright Inspector and pauses the script. Only available in headed mode. */
1482
+ async pause() {
1483
+ this.assertUsable();
1484
+ if (this.services.config.browser.headless)
1485
+ throw new ValidationError('page.pause() needs a headed browser (browser.headless: false)');
1486
+ await this.adapter.pause();
1487
+ }
1488
+ /** Remove listeners and close the page (alias of close used by owners). */
1489
+ async dispose() {
1490
+ await this.close();
1491
+ }
1492
+ }
1493
+ //# sourceMappingURL=page.js.map