testsurfer 0.1.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +52 -149
  2. package/dist/browser.d.ts +135 -1
  3. package/dist/browser.js +378 -2
  4. package/dist/browser.js.map +1 -1
  5. package/dist/cli.d.ts +16 -0
  6. package/dist/cli.js +140 -0
  7. package/dist/cli.js.map +1 -0
  8. package/dist/client.d.ts +12 -2
  9. package/dist/client.js +73 -4
  10. package/dist/client.js.map +1 -1
  11. package/dist/diff.d.ts +19 -0
  12. package/dist/diff.js +116 -0
  13. package/dist/diff.js.map +1 -0
  14. package/dist/events.d.ts +386 -0
  15. package/dist/events.js +1035 -0
  16. package/dist/events.js.map +1 -0
  17. package/dist/expect.d.ts +135 -26
  18. package/dist/expect.js +634 -130
  19. package/dist/expect.js.map +1 -1
  20. package/dist/frame.d.ts +88 -0
  21. package/dist/frame.js +194 -0
  22. package/dist/frame.js.map +1 -0
  23. package/dist/global.d.ts +12 -0
  24. package/dist/global.js +136 -0
  25. package/dist/global.js.map +1 -0
  26. package/dist/hooks.d.ts +28 -0
  27. package/dist/hooks.js +48 -0
  28. package/dist/hooks.js.map +1 -0
  29. package/dist/index.d.ts +22 -3
  30. package/dist/index.js +21 -3
  31. package/dist/index.js.map +1 -1
  32. package/dist/injected.d.ts +15 -0
  33. package/dist/injected.js +2025 -0
  34. package/dist/injected.js.map +1 -0
  35. package/dist/locator.d.ts +374 -86
  36. package/dist/locator.js +845 -244
  37. package/dist/locator.js.map +1 -1
  38. package/dist/media.d.ts +15 -0
  39. package/dist/media.js +83 -0
  40. package/dist/media.js.map +1 -0
  41. package/dist/net.d.ts +110 -0
  42. package/dist/net.js +498 -0
  43. package/dist/net.js.map +1 -0
  44. package/dist/page.d.ts +448 -5
  45. package/dist/page.js +1187 -31
  46. package/dist/page.js.map +1 -1
  47. package/dist/png.d.ts +28 -0
  48. package/dist/png.js +197 -0
  49. package/dist/png.js.map +1 -0
  50. package/dist/pwconfig.d.ts +66 -0
  51. package/dist/pwconfig.js +77 -0
  52. package/dist/pwconfig.js.map +1 -0
  53. package/dist/register.d.ts +6 -0
  54. package/dist/register.js +9 -0
  55. package/dist/register.js.map +1 -0
  56. package/dist/request.d.ts +29 -0
  57. package/dist/request.js +75 -0
  58. package/dist/request.js.map +1 -0
  59. package/dist/runner.d.ts +99 -15
  60. package/dist/runner.js +354 -58
  61. package/dist/runner.js.map +1 -1
  62. package/dist/screenshot.d.ts +35 -0
  63. package/dist/screenshot.js +171 -0
  64. package/dist/screenshot.js.map +1 -0
  65. package/dist/selector.d.ts +55 -0
  66. package/dist/selector.js +208 -0
  67. package/dist/selector.js.map +1 -0
  68. package/dist/selectors.d.ts +13 -0
  69. package/dist/selectors.js +16 -0
  70. package/dist/selectors.js.map +1 -0
  71. package/dist/serialize.d.ts +17 -0
  72. package/dist/serialize.js +149 -0
  73. package/dist/serialize.js.map +1 -0
  74. package/dist/shim.d.ts +15 -0
  75. package/dist/shim.js +211 -0
  76. package/dist/shim.js.map +1 -0
  77. package/dist/testinfo.d.ts +62 -0
  78. package/dist/testinfo.js +23 -0
  79. package/dist/testinfo.js.map +1 -0
  80. package/dist/values.d.ts +67 -0
  81. package/dist/values.js +293 -0
  82. package/dist/values.js.map +1 -0
  83. package/package.json +10 -3
  84. package/skills/testsurfer/SKILL.md +55 -0
package/dist/page.js CHANGED
@@ -37,8 +37,22 @@ function parseLayoutLines(lines) {
37
37
  }
38
38
  import { WireError } from "./errors.js";
39
39
  import { applyDelta, isDeltaBody, parseFullTree, walk } from "./tree.js";
40
- import { Locator } from "./locator.js";
40
+ import { byAttr, ElementHandle, FrameLocator, JSHandle, selectorSteps, Locator, } from "./locator.js";
41
+ import { installEngine } from "./injected.js";
42
+ import { APIRequestContext } from "./request.js";
43
+ import { selectorSettings } from "./selectors.js";
44
+ import { Frame } from "./frame.js";
45
+ import { mediaScript } from "./media.js";
46
+ import { deserializeValue, serializeValue, SERIALIZE_JS } from "./serialize.js";
47
+ import { decodePng, downscale, encodePng } from "./png.js";
48
+ /** The engine install expression: defines window.__tse and yields it. */
49
+ const ENGINE_JS = `(${installEngine.toString()})(${SERIALIZE_JS})`;
50
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
51
+ /** The frame-tree listing; its own reply never starts another refresh. */
52
+ const FRAMES_CALL = 'E.frames()';
41
53
  import { renderSnapshot } from "./aria.js";
54
+ import { PAGE_SHIM } from "./shim.js";
55
+ import { ConsoleMessage, PageEvents, Request, Response, urlMatches, } from "./events.js";
42
56
  export const DEFAULT_TIMEOUTS = {
43
57
  action: 10_000,
44
58
  expect: 5_000,
@@ -74,8 +88,24 @@ export class Page {
74
88
  actDeltas;
75
89
  navInPlace;
76
90
  baseURL;
91
+ /** HTTP requests from the test process (not the browser). */
92
+ request;
93
+ testIdOption = null;
94
+ /** Attribute getByTestId matches: the `testIdAttribute` launch option, else selectors.setTestIdAttribute(), else `data-testid`. */
95
+ get testIdAttribute() {
96
+ return this.testIdOption ?? selectorSettings.testIdAttribute ?? 'data-testid';
97
+ }
98
+ set testIdAttribute(name) {
99
+ this.testIdOption = name;
100
+ }
101
+ /** Document-start scripts, replayed into the web view when it is created. */
102
+ initScripts = [];
103
+ shimInstalled = false;
104
+ events;
105
+ ctx = null;
77
106
  constructor(client, sessionId, timeouts, inputMode = 'robotic', clickVia = 'click-at', protocol = {}, baseURL) {
78
107
  this.baseURL = baseURL;
108
+ this.request = new APIRequestContext(baseURL);
79
109
  this.client = client;
80
110
  this.sessionId = sessionId;
81
111
  this.timeouts = timeouts;
@@ -83,6 +113,378 @@ export class Page {
83
113
  this.clickVia = clickVia;
84
114
  this.actDeltas = protocol.actDeltas ?? false;
85
115
  this.navInPlace = protocol.navInPlace ?? false;
116
+ this.events = new PageEvents({
117
+ openPoller: () => this.client.sibling(),
118
+ target: () => ({ pageId: this.pageId, sessionId: this.sessionId }),
119
+ baseURL,
120
+ ensureShim: () => this.ensureShim(),
121
+ addInitScript: (src) => this.addInitSource(src),
122
+ proxied: () => this.ctx?.intercept ?? false,
123
+ mainFrame: () => this.mainFrame(),
124
+ childFrame: (url) => {
125
+ // The frame list may predate the iframe; the newest child stands in.
126
+ const kids = this.frames().slice(1);
127
+ return kids.find((f) => f.frameUrl === url) ?? kids[kids.length - 1] ?? null;
128
+ },
129
+ extraHeaders: () => ({ ...(this.ctx?.extraHeaders ?? {}), ...this.extraHeaders }),
130
+ isPopup: () => this.openerPage !== undefined,
131
+ swControlled: () => this.swControlled,
132
+ pageURL: () => this.lastHref,
133
+ });
134
+ }
135
+ /** The page that opened this one; undefined when not a popup. */
136
+ openerPage = undefined;
137
+ closedFlag = false;
138
+ /** The URL a popup was opened with, until waitForLoadState() sees it loaded. */
139
+ popupURL = '';
140
+ /**
141
+ * @internal Take over a page vibesurfer opened as a popup of `opener`
142
+ * (`--popups`). Joins the network hub at once, so the popup's first
143
+ * request is reported to it.
144
+ */
145
+ adoptPopup(pageId, url, opener) {
146
+ this.pageId = pageId;
147
+ this.openerPage = opener;
148
+ this.popupURL = url || 'about:blank';
149
+ this.lastHref = url || 'about:blank';
150
+ this.events.documentChanged();
151
+ this.events.attachHub();
152
+ return this.events;
153
+ }
154
+ /** @internal The vibesurfer page id, once the page has one. */
155
+ wireId() {
156
+ return this.pageId;
157
+ }
158
+ /** The page that opened this one (window.open, target=_blank), or null. */
159
+ async opener() {
160
+ return this.openerPage ?? null;
161
+ }
162
+ isClosed() {
163
+ return this.closedFlag;
164
+ }
165
+ /** @internal The page closed itself (window.close()); vibesurfer already released it. */
166
+ closedByPage() {
167
+ if (this.closedFlag)
168
+ return;
169
+ this.pageId = null;
170
+ this.markClosed();
171
+ }
172
+ markClosed() {
173
+ this.closedFlag = true;
174
+ this.events.emitPageEvent('close', this);
175
+ this.events.close();
176
+ this.ctx?.forgetPage(this);
177
+ }
178
+ /** @internal Report a popup this page opened. */
179
+ emitPopup(popup) {
180
+ this.events.emitPageEvent('popup', popup);
181
+ }
182
+ /**
183
+ * @internal A dialog this page opened. Listeners on the page (or its
184
+ * context) decide; with none it is dismissed, as in Playwright.
185
+ */
186
+ handleDialog(d, contextListens) {
187
+ if (!this.events.hasListeners('dialog') && !contextListens) {
188
+ void d.dismiss().catch(() => { });
189
+ return;
190
+ }
191
+ this.events.emitPageEvent('dialog', d);
192
+ }
193
+ /** @internal Set by the context that created this page. */
194
+ bindContext(ctx) {
195
+ this.ctx = ctx;
196
+ }
197
+ /** The context this page belongs to. */
198
+ context() {
199
+ if (!this.ctx)
200
+ throw new Error('page has no context');
201
+ return this.ctx;
202
+ }
203
+ async addInitSource(source) {
204
+ this.initScripts.push(source);
205
+ if (this.pageId)
206
+ await this.client.call('vs_init_script', [this.pageId, source], { session: this.sessionId });
207
+ }
208
+ async ensureShim() {
209
+ if (this.shimInstalled)
210
+ return;
211
+ this.shimInstalled = true;
212
+ await this.addInitSource(PAGE_SHIM);
213
+ if (this.pageId)
214
+ await this.evaluate(PAGE_SHIM.replace(/;\s*$/, ''));
215
+ }
216
+ /**
217
+ * Run a script at document start in every later document of this
218
+ * page, before the page's own scripts (Playwright's addInitScript).
219
+ * A function is called with `arg`. The current document is not
220
+ * touched.
221
+ */
222
+ async addInitScript(script, arg) {
223
+ let source;
224
+ if (typeof script === 'function')
225
+ source = `(${script.toString()})(${JSON.stringify(arg ?? null)});`;
226
+ else if (typeof script === 'string')
227
+ source = script;
228
+ else if (script.content !== undefined)
229
+ source = script.content;
230
+ else if (script.path)
231
+ source = await (await import('node:fs/promises')).readFile(script.path, 'utf8');
232
+ else
233
+ throw new Error('addInitScript: pass a function, a string, or { path } / { content }');
234
+ await this.addInitSource(source);
235
+ }
236
+ /**
237
+ * Emulate media features: matchMedia and the page's @media rules
238
+ * follow (see src/media.ts). null resets a feature. Applies to this
239
+ * document and later ones.
240
+ */
241
+ async emulateMedia(options = {}) {
242
+ for (const k of ['media', 'colorScheme', 'reducedMotion', 'forcedColors']) {
243
+ if (k in options)
244
+ this.media[k] = options[k] ?? null;
245
+ }
246
+ const src = mediaScript(this.media);
247
+ await this.addInitSource(src);
248
+ if (this.pageId)
249
+ await this.rawEval(`(${src.replace(/;\s*$/, '')}, 0)`).catch(() => { });
250
+ }
251
+ media = {};
252
+ /**
253
+ * Add a <script> (from `url`, a file at `path`, or `content`) and
254
+ * wait for it to load. Returns its element.
255
+ */
256
+ async addScriptTag(options) {
257
+ let content = options.content;
258
+ if (options.path !== undefined) {
259
+ content = `${await (await import('node:fs/promises')).readFile(options.path, 'utf8')}\n//# sourceURL=${options.path.replace(/\n/g, '')}`;
260
+ }
261
+ const fn = `(o) => new Promise((resolve, reject) => {
262
+ const s = document.createElement('script');
263
+ if (o.type) s.type = o.type;
264
+ if (o.url !== undefined) {
265
+ s.src = o.url;
266
+ s.onload = () => resolve(s);
267
+ s.onerror = () => reject(new Error('Failed to load script at ' + o.url));
268
+ document.head.appendChild(s);
269
+ return;
270
+ }
271
+ let err = null;
272
+ const onErr = (e) => { err = e.error || new Error(e.message); };
273
+ window.addEventListener('error', onErr);
274
+ s.text = o.content;
275
+ document.head.appendChild(s);
276
+ window.removeEventListener('error', onErr);
277
+ if (err) reject(err); else resolve(s);
278
+ })`;
279
+ const args = { url: options.url, content, type: options.type };
280
+ return (await this.evaluateHandle(fn, args));
281
+ }
282
+ /** Add a <link rel=stylesheet> (from `url`) or a <style> (from `path` or `content`) and wait for it. */
283
+ async addStyleTag(options) {
284
+ let content = options.content;
285
+ if (options.path !== undefined)
286
+ content = await (await import('node:fs/promises')).readFile(options.path, 'utf8');
287
+ const fn = `(o) => new Promise((resolve, reject) => {
288
+ let el;
289
+ if (o.url !== undefined) {
290
+ el = document.createElement('link');
291
+ el.rel = 'stylesheet';
292
+ el.href = o.url;
293
+ } else {
294
+ el = document.createElement('style');
295
+ el.textContent = o.content;
296
+ }
297
+ el.onload = () => resolve(el);
298
+ el.onerror = () => reject(new Error('Error while loading style'));
299
+ document.head.appendChild(el);
300
+ if (o.url === undefined) resolve(el);
301
+ })`;
302
+ return (await this.evaluateHandle(fn, { url: options.url, content }));
303
+ }
304
+ /**
305
+ * Intercept fetch and XHR requests whose URL matches. The handler
306
+ * gets a Route to fulfill, continue, abort, fall back or fetch.
307
+ * Navigations, images, scripts and stylesheets are not intercepted.
308
+ */
309
+ async route(url, handler, options = {}) {
310
+ this.events.addRoute(url, handler, options.times ?? null);
311
+ await this.events.sync();
312
+ }
313
+ /** Remove routes for `url` (only `handler`'s, when given). */
314
+ async unroute(url, handler) {
315
+ this.events.removeRoutes(url, handler);
316
+ await this.events.sync();
317
+ }
318
+ async unrouteAll() {
319
+ this.events.removeRoutes();
320
+ await this.events.sync();
321
+ }
322
+ on(event, listener) {
323
+ this.events.on(event, listener);
324
+ void this.events.sync().catch(() => { });
325
+ return this;
326
+ }
327
+ once(event, listener) {
328
+ const wrapped = (arg) => {
329
+ this.off(event, wrapped);
330
+ listener(arg);
331
+ };
332
+ return this.on(event, wrapped);
333
+ }
334
+ off(event, listener) {
335
+ this.events.off(event, listener);
336
+ void this.events.sync().catch(() => { });
337
+ return this;
338
+ }
339
+ removeListener(event, listener) {
340
+ return this.off(event, listener);
341
+ }
342
+ /** The next `event` that `predicate` accepts. */
343
+ async waitForEvent(event, optionsOrPredicate) {
344
+ const opts = typeof optionsOrPredicate === 'function' ? { predicate: optionsOrPredicate } : (optionsOrPredicate ?? {});
345
+ return this.events.waitFor(event, opts.predicate ?? (() => true), opts.timeout ?? this.timeouts.action);
346
+ }
347
+ /** The next fetch/XHR request matching a URL pattern or predicate. */
348
+ async waitForRequest(match, options = {}) {
349
+ const test = typeof match === 'function' && match.length === 1 && !(match instanceof RegExp)
350
+ ? (r) => match(r)
351
+ : (r) => urlMatches(match, r.url(), this.baseURL);
352
+ return this.events.waitFor('request', test, options.timeout ?? this.timeouts.action);
353
+ }
354
+ /** The next fetch/XHR response matching a URL pattern or predicate. */
355
+ async waitForResponse(match, options = {}) {
356
+ const test = typeof match === 'function' && !(match instanceof RegExp)
357
+ ? (r) => match(r)
358
+ : (r) => urlMatches(match, r.url(), this.baseURL);
359
+ return this.events.waitFor('response', test, options.timeout ?? this.timeouts.action);
360
+ }
361
+ async waitForTimeout(ms) {
362
+ await new Promise((r) => setTimeout(r, ms));
363
+ }
364
+ /** Poll until the URL matches. */
365
+ async waitForURL(url, options = {}) {
366
+ const budget = options.timeout ?? this.timeouts.navigation;
367
+ const deadline = Date.now() + budget;
368
+ for (;;) {
369
+ const now = await this.currentURL().catch(() => '');
370
+ if (now && urlMatches(url, now, this.baseURL))
371
+ return;
372
+ if (Date.now() >= deadline)
373
+ throw new Error(`waitForURL(${String(url)}) timed out after ${budget}ms; URL is ${now}`);
374
+ await new Promise((r) => setTimeout(r, 50));
375
+ }
376
+ }
377
+ /**
378
+ * Resolve when the page has loaded a new document (and, with `url`,
379
+ * one whose URL matches). Start it before the action that navigates:
380
+ * `await Promise.all([page.waitForNavigation(), link.click()])`.
381
+ */
382
+ async waitForNavigation(options = {}) {
383
+ const budget = options.timeout ?? this.timeouts.navigation;
384
+ const deadline = Date.now() + budget;
385
+ // Mark the current document; a new one will not carry the mark.
386
+ const mark = `nav${Date.now()}${Math.random().toString(36).slice(2)}`;
387
+ await this.rawEval(`(window.__tsNavMark = ${JSON.stringify(mark)}, 0)`).catch(() => { });
388
+ for (;;) {
389
+ const state = await this.rawEval(`({ m: window.__tsNavMark || null, r: document.readyState, u: location.href })`).catch(() => null);
390
+ if (state && state.m !== mark && state.r !== 'loading') {
391
+ if (!options.url || urlMatches(options.url, state.u, this.baseURL)) {
392
+ this.snapshot = null;
393
+ this.synced = false;
394
+ this.fresh = false;
395
+ this.events.documentChanged();
396
+ return null;
397
+ }
398
+ }
399
+ if (Date.now() >= deadline)
400
+ throw new Error(`page.waitForNavigation: Timeout ${budget}ms exceeded.`);
401
+ await sleep(20);
402
+ }
403
+ }
404
+ /**
405
+ * goto() already waits for the load. A popup loads on its own, so
406
+ * for one this waits until its document is there and loaded.
407
+ */
408
+ async waitForLoadState(state, options = {}) {
409
+ if (this.popupURL) {
410
+ const want = this.popupURL;
411
+ const budget = options.timeout ?? this.timeouts.navigation;
412
+ const deadline = Date.now() + budget;
413
+ for (;;) {
414
+ const r = await this.rawEval(`location.href + ' ' + document.readyState`).catch(() => '');
415
+ const cut = r.lastIndexOf(' ');
416
+ const href = r.slice(0, cut);
417
+ const ready = r.slice(cut + 1);
418
+ const loaded = state === 'domcontentloaded' ? ready === 'interactive' || ready === 'complete' : ready === 'complete';
419
+ if (loaded && (href !== 'about:blank' || want === 'about:blank')) {
420
+ this.lastHref = href;
421
+ break;
422
+ }
423
+ if (Date.now() >= deadline)
424
+ throw new Error(`page.waitForLoadState: Timeout ${budget}ms exceeded.`);
425
+ await new Promise((res) => setTimeout(res, 30));
426
+ }
427
+ this.popupURL = '';
428
+ }
429
+ await this.refreshFrames();
430
+ }
431
+ /**
432
+ * Replace the document with `html`; its scripts run. On an http(s)
433
+ * page the document is rewritten in place, so it keeps that origin
434
+ * and relative URLs resolve against it. Otherwise the page loads the
435
+ * HTML as a data: URL (an opaque origin, no storage): WebKit drops
436
+ * native clicks on a rewritten about:blank.
437
+ */
438
+ async setContent(html) {
439
+ const here = this.pageId ? await this.currentURL().catch(() => '') : '';
440
+ if (!/^https?:/.test(here)) {
441
+ const shown = here.startsWith('data:') ? here : 'about:blank';
442
+ const data = `data:text/html;charset=utf-8,${encodeURIComponent(html)}`;
443
+ await this.navigate(data);
444
+ await this.rememberNav(shown, data);
445
+ await this.refreshFrames();
446
+ return;
447
+ }
448
+ await this.evaluate(`(document.open(), document.write(${JSON.stringify(html)}), document.close(), 'ok')`);
449
+ // Like Playwright, return once the new document (stylesheets, images) has loaded.
450
+ await this.waitForFunction("document.readyState === 'complete'", undefined, { timeout: this.timeouts.navigation }).catch(() => { });
451
+ await this.refreshFrames();
452
+ this.snapshot = null;
453
+ this.synced = false;
454
+ this.fresh = false;
455
+ }
456
+ /** The document's HTML, without the ref markers vibesurfer adds. */
457
+ async content() {
458
+ return this.evaluate(`(function(){var c=document.documentElement.cloneNode(true);c.removeAttribute('data-vs-ref');` +
459
+ `c.querySelectorAll('[data-vs-ref]').forEach(function(e){e.removeAttribute('data-vs-ref');});` +
460
+ `return '<!DOCTYPE html>'+c.outerHTML;})()`);
461
+ }
462
+ /** Load the current URL again. */
463
+ async reload() {
464
+ return this.goto(await this.currentURL());
465
+ }
466
+ /** History back; resolves once the URL changed (or immediately when there is no history). */
467
+ async goBack() {
468
+ await this.historyMove(-1);
469
+ }
470
+ async goForward() {
471
+ await this.historyMove(1);
472
+ }
473
+ async historyMove(delta) {
474
+ const before = await this.currentURL();
475
+ await this.evaluate(`(history.go(${delta}), 'ok')`);
476
+ // No history entry means no change; give up on the URL after 2s.
477
+ const deadline = Date.now() + 2_000;
478
+ while (Date.now() < deadline) {
479
+ await new Promise((r) => setTimeout(r, 50));
480
+ const now = await this.currentURL().catch(() => before);
481
+ if (now !== before)
482
+ break;
483
+ }
484
+ this.snapshot = null;
485
+ this.synced = false;
486
+ this.fresh = false;
487
+ this.events.documentChanged();
86
488
  }
87
489
  /**
88
490
  * Fold a 0.2 mutation response body (the ViewForm the daemon emitted
@@ -115,22 +517,134 @@ export class Page {
115
517
  throw new Error('page has no URL yet; call page.goto(url) first');
116
518
  return this.pageId;
117
519
  }
520
+ /**
521
+ * A new page starts at about:blank, as in Playwright: the first call
522
+ * that needs a document opens one (with the init scripts installed).
523
+ */
524
+ async ensureOpen() {
525
+ if (this.pageId)
526
+ return;
527
+ if (this.closedFlag)
528
+ throw new Error('Target page, context or browser has been closed');
529
+ const resp = await this.client.call('vs_open', ['about:blank'], { session: this.sessionId });
530
+ const id = resp.body[0];
531
+ if (!id)
532
+ throw new Error('vs_open returned no page id for about:blank');
533
+ this.pageId = id;
534
+ await this.applyViewport();
535
+ this.token = resp.token;
536
+ for (const src of this.initScripts) {
537
+ await this.client.call('vs_init_script', [id, src], { session: this.sessionId });
538
+ }
539
+ this.events.documentChanged();
540
+ }
118
541
  /**
119
542
  * Navigate to a URL, relative to the baseURL launch option when set.
120
543
  * Navigates in place on protocol-v1 daemons; older ones close the
121
544
  * page and open a new one.
122
545
  */
123
- async goto(target) {
546
+ async goto(target, _options = {}) {
547
+ try {
548
+ await this.events.beforeNavigation();
549
+ // Shim mode: the in-page shim cannot see a document request, so
550
+ // the page's routes decide it here.
551
+ const url = this.baseURL ? new URL(target, this.baseURL).href : target;
552
+ const routed = /^https?:/.test(url) ? await this.events.routeDocument(url) : null;
553
+ if (routed?.kind === 'abort')
554
+ this.events.netNavAborted();
555
+ if (routed?.kind === 'abort')
556
+ throw new Error('aborted by route');
557
+ if (routed?.kind === 'fulfill') {
558
+ await this.navigate(url, routed.body);
559
+ const res = new Response(routed.req, { url, status: routed.status, statusText: '', headers: routed.headers });
560
+ res.bodyLoader = async () => routed.body;
561
+ routed.req.responseValue = res;
562
+ return res;
563
+ }
564
+ await this.navigate(routed?.kind === 'continue' ? routed.url : target);
565
+ }
566
+ catch (e) {
567
+ // A route that aborted the document fails the navigation the way WebKit reports it.
568
+ if (this.events.abortedNavigation())
569
+ throw new Error(`page.goto: Blocked by Web Inspector`);
570
+ throw e;
571
+ }
572
+ const viaProxy = await this.events.proxiedNavResponse();
573
+ const res = viaProxy ?? (await this.mainResponse());
574
+ if (res || !target.startsWith('file:'))
575
+ return res;
576
+ // A file: page has a response too, with status 0, as in WebKit under Playwright.
577
+ const req = new Request({ id: 0, url: target, method: 'GET', headers: {}, body: null, type: 'document', navigation: true });
578
+ req.frameValue = this.mainFrame();
579
+ const fileRes = new Response(req, { url: target, status: 0, statusText: '', headers: {} });
580
+ req.responseValue = fileRes;
581
+ return fileRes;
582
+ }
583
+ /**
584
+ * The main document's response after a navigation (vibesurfer 0.2.16+
585
+ * `vs_inspect response`), or null for data:, about: and file: URLs or
586
+ * on older daemons.
587
+ */
588
+ async mainResponse() {
589
+ if (!this.pageId)
590
+ return null;
591
+ let body;
592
+ try {
593
+ body = (await this.client.call('vs_inspect', ['response', this.pageId], { session: this.sessionId })).body;
594
+ }
595
+ catch {
596
+ return null;
597
+ }
598
+ if (body.length === 0 || body[0] === 'none')
599
+ return null;
600
+ let url = '';
601
+ let status = 0;
602
+ let statusText = '';
603
+ const headers = {};
604
+ for (const line of body) {
605
+ if (line.startsWith('url='))
606
+ url = line.slice(4);
607
+ else if (line.startsWith('status='))
608
+ status = Number(line.slice(7));
609
+ else if (line.startsWith('status_text='))
610
+ statusText = line.slice(12);
611
+ else if (line.startsWith('h ')) {
612
+ const i = line.indexOf(': ');
613
+ if (i > 2) {
614
+ const k = line.slice(2, i);
615
+ const v = line.slice(i + 2);
616
+ headers[k] = headers[k] === undefined ? v : `${headers[k]}, ${v}`;
617
+ }
618
+ }
619
+ }
620
+ // Responses do not carry the fragment.
621
+ url = url.replace(/#.*$/, '');
622
+ const req = new Request({ id: 0, url, method: 'GET', headers: {}, body: null, type: 'document' });
623
+ req.frameValue = this.mainFrame();
624
+ const res = new Response(req, { url, status, statusText, headers });
625
+ req.responseValue = res;
626
+ res.bodyLoader = async () => {
627
+ const b64 = await this.evaluate(`fetch(${JSON.stringify(url)}, { credentials: 'include' }).then((r) => r.arrayBuffer()).then((b) => { let s = ''; const a = new Uint8Array(b); for (let i = 0; i < a.length; i += 32768) s += String.fromCharCode.apply(null, a.subarray(i, i + 32768)); return btoa(s); })`);
628
+ return Buffer.from(b64, 'base64');
629
+ };
630
+ return res;
631
+ }
632
+ /** `html`: load that document under the URL instead of fetching it (a routed document). */
633
+ async navigate(target, html) {
124
634
  const url = this.baseURL ? new URL(target, this.baseURL).href : target;
635
+ const gotoFlags = { session: this.sessionId };
636
+ if (html)
637
+ gotoFlags['html'] = html.toString('base64');
125
638
  if (this.pageId && this.navInPlace) {
126
639
  try {
127
- const resp = await this.client.call('vs_goto', [this.pageId, url], {
128
- session: this.sessionId,
129
- });
640
+ const resp = await this.client.call('vs_goto', [this.pageId, url], gotoFlags);
130
641
  this.token = resp.token;
131
642
  this.snapshot = null;
132
643
  this.synced = false;
133
644
  this.fresh = false;
645
+ this.events.documentChanged();
646
+ await this.rememberNav(url, url);
647
+ await this.refreshFrames();
134
648
  return;
135
649
  }
136
650
  catch {
@@ -147,12 +661,26 @@ export class Page {
147
661
  this.snapshot = null;
148
662
  this.synced = false;
149
663
  this.fresh = false;
150
- const resp = await this.client.call('vs_open', [url], { session: this.sessionId });
664
+ // Init scripts have to be in place before the first document, so
665
+ // a page that has them opens blank, installs them, then loads.
666
+ const first = this.initScripts.length > 0 || html ? 'about:blank' : url;
667
+ const resp = await this.client.call('vs_open', [first], { session: this.sessionId });
151
668
  const id = resp.body[0];
152
669
  if (!id)
153
670
  throw new Error(`vs_open returned no page id for ${url}`);
154
671
  this.pageId = id;
672
+ await this.applyViewport();
155
673
  this.token = resp.token;
674
+ if (first !== url) {
675
+ for (const src of this.initScripts) {
676
+ await this.client.call('vs_init_script', [id, src], { session: this.sessionId });
677
+ }
678
+ const nav = await this.client.call('vs_goto', [id, url], gotoFlags);
679
+ this.token = nav.token;
680
+ }
681
+ this.events.documentChanged();
682
+ await this.rememberNav(url, url);
683
+ await this.refreshFrames();
156
684
  // No settle wait here: locators auto-wait and assertions poll, so
157
685
  // a still-loading tree just resolves a poll tick later.
158
686
  }
@@ -164,6 +692,7 @@ export class Page {
164
692
  * either way.
165
693
  */
166
694
  async view() {
695
+ await this.ensureOpen();
167
696
  const canDelta = this.synced && this.snapshot !== null;
168
697
  const flags = { session: this.sessionId };
169
698
  if (!canDelta)
@@ -248,6 +777,8 @@ export class Page {
248
777
  }
249
778
  }
250
779
  catch (e) {
780
+ if (await this.closedByItself(e))
781
+ return;
251
782
  if (e instanceof WireError && e.code === 'STALE_TOKEN' && e.args[0]) {
252
783
  this.token = e.args[0];
253
784
  }
@@ -256,6 +787,22 @@ export class Page {
256
787
  throw e;
257
788
  }
258
789
  }
790
+ /**
791
+ * The action made the page close itself (a popup's "Close" button):
792
+ * vibesurfer released the page under the action, which then finds
793
+ * nothing. The action did its work; the close event follows on the
794
+ * event stream.
795
+ */
796
+ async closedByItself(e) {
797
+ if (!(e instanceof WireError) || e.code !== 'NOT_FOUND' || !String(e.args[0] ?? '').startsWith('page='))
798
+ return false;
799
+ if (this.openerPage === undefined)
800
+ return false;
801
+ const deadline = Date.now() + 1000;
802
+ while (!this.closedFlag && Date.now() < deadline)
803
+ await sleep(20);
804
+ return this.closedFlag;
805
+ }
259
806
  /**
260
807
  * Trusted native click at viewport coordinates via vs_click_at. The
261
808
  * cursor op leaves the daemon's delta baseline and last token
@@ -263,10 +810,9 @@ export class Page {
263
810
  * click's effects) but `fresh` does not.
264
811
  */
265
812
  async clickAt(x, y, mode) {
266
- if (this.token === null)
267
- await this.view();
813
+ await this.ensureOpen();
268
814
  try {
269
- const resp = await this.client.call('vs_click_at', [this.id, String(Math.round(x)), String(Math.round(y))], { session: this.sessionId, token: this.token ?? '', mode: mode ?? this.inputMode });
815
+ const resp = await this.client.call('vs_click_at', [this.id, String(Math.round(x * 100) / 100), String(Math.round(y * 100) / 100)], { session: this.sessionId, token: this.token ?? '0', mode: mode ?? this.inputMode });
270
816
  this.token = resp.token;
271
817
  if (this.actDeltas) {
272
818
  this.applyMutationBody(resp);
@@ -278,6 +824,8 @@ export class Page {
278
824
  }
279
825
  }
280
826
  catch (e) {
827
+ if (await this.closedByItself(e))
828
+ return;
281
829
  if (e instanceof WireError && e.code === 'STALE_TOKEN' && e.args[0]) {
282
830
  this.token = e.args[0];
283
831
  }
@@ -302,6 +850,7 @@ export class Page {
302
850
  }
303
851
  /** Trusted per-character typing into the focused element. */
304
852
  async typeTrusted(text, options) {
853
+ await this.ensureOpen();
305
854
  const flags = {
306
855
  session: this.sessionId,
307
856
  token: this.token ?? '',
@@ -359,28 +908,555 @@ export class Page {
359
908
  * arguments. Runs through vs_inspect eval, which reads the page
360
909
  * without mutating the daemon's state token.
361
910
  */
362
- async evaluate(fnOrExpr) {
363
- const src = typeof fnOrExpr === 'function' ? `(${fnOrExpr.toString()})()` : `(${fnOrExpr})`;
364
- const resp = await this.client.call('vs_inspect', ['eval', this.id, `JSON.stringify(${src}) ?? "null"`], { session: this.sessionId, full: true });
911
+ async evaluate(fn, arg) {
912
+ const a = JSON.stringify(serializeValue(arg));
913
+ // A function, or a string holding one, is called with `arg`; any
914
+ // other string is an expression. Promises are awaited.
915
+ const src = typeof fn === 'function' ? fn.toString() : fn;
916
+ const body = `(function(){var v=(${src});return typeof v==='function'?v(E.des(${a})):v;})()`;
917
+ return (await this.engineCall(body));
918
+ }
919
+ /** Raw evaluate through vs_inspect: JSON in, JSON out, no promise handling. */
920
+ async rawEval(src, frame = null) {
921
+ await this.ensureOpen();
922
+ const flags = { session: this.sessionId, full: true };
923
+ // A subframe by URL, cross-origin ones included (vibesurfer 0.2.16+).
924
+ if (frame !== null)
925
+ flags['frame'] = frame;
926
+ const resp = await this.client.call('vs_inspect', ['eval', this.id, `JSON.stringify(${src}) ?? "null"`], flags);
365
927
  const line = resp.body.find((l) => l.startsWith('result='));
366
928
  if (line === undefined) {
367
929
  throw new Error(`evaluate failed: ${resp.body.join(' ').slice(0, 300)}`);
368
930
  }
369
931
  return JSON.parse(line.slice('result='.length));
370
932
  }
933
+ /**
934
+ * Run `body` (an expression that may use the engine as `E`) in the
935
+ * page, or in the subframe with URL `frame`. Installs the engine on
936
+ * first use in each document, waits out promises, and turns page
937
+ * exceptions into thrown Errors.
938
+ */
939
+ async engineCall(body, frame = null) {
940
+ const call = (install) => `(function(){var E=${install ? ENGINE_JS : 'window.__tse'};if(!E)return {noengine:1};return E.exec(function(){return ${body};});})()`;
941
+ let r = await this.rawEval(call(false), frame);
942
+ if (r && r.noengine)
943
+ r = await this.rawEval(call(true), frame);
944
+ for (let i = 0; r && r.p !== undefined; i++) {
945
+ await sleep(i < 5 ? 2 : i < 20 ? 10 : 25);
946
+ r = await this.rawEval(`(function(){var E=window.__tse;return E?E.take(${r.p}):{gone:1};})()`, frame);
947
+ }
948
+ if (!r || r.gone || r.noengine) {
949
+ throw new Error('Execution context was destroyed, most likely because of a navigation');
950
+ }
951
+ if (frame === null) {
952
+ if (typeof r.u === 'string')
953
+ this.lastHref = r.u;
954
+ if (typeof r.sw === 'boolean')
955
+ this.swControlled = r.sw;
956
+ // Keep frames() current: re-read the frame tree when the page's iframe count changed.
957
+ const fc = r?.fc;
958
+ if (typeof fc === 'number' && fc !== this.lastFrameCount && body !== FRAMES_CALL) {
959
+ this.lastFrameCount = fc;
960
+ await this.refreshFrames();
961
+ }
962
+ }
963
+ // Bindings, console messages and page errors a call caused are
964
+ // delivered before it returns, as Playwright's protocol events are.
965
+ if ((this.events.hasBindings || this.events.hasListeners('console') || this.events.hasListeners('pageerror')) && !body.startsWith('E.doc')) {
966
+ await this.events.flush();
967
+ }
968
+ if (r.e) {
969
+ // As Playwright prints a page exception: "TypeError: Load failed".
970
+ const name = r.e.name && r.e.name !== 'Error' ? r.e.name : null;
971
+ const err = new Error(name ? `${name}: ${r.e.message}` : r.e.message);
972
+ err.name = r.e.name ?? 'Error';
973
+ throw err;
974
+ }
975
+ return deserializeValue(r.v);
976
+ }
977
+ /** One locator-engine request (see src/injected.ts). `fn` is a function source passed alongside. */
978
+ async engineRun(req, fn) {
979
+ return (await this.engineRunIn(null, req, fn, 0, 0));
980
+ }
981
+ /**
982
+ * engineRun in `frame`. A chain that crosses into a cross-origin
983
+ * frame stops there (XOFrame); the rest runs inside that frame, and
984
+ * a point it returns moves by where the frame sits in the page.
985
+ */
986
+ async engineRunIn(frame, req, fn, dx, dy) {
987
+ let r;
988
+ try {
989
+ r = await this.engineCall(`E.run(${JSON.stringify(req)}${fn ? `,(${fn})` : ''})`, frame);
990
+ }
991
+ catch (e) {
992
+ if (e.name !== 'XOFrame')
993
+ throw e;
994
+ const xo = JSON.parse(e.message.replace(/^XOFrame: /, ''));
995
+ const steps = req['steps'].slice(xo.rest);
996
+ return this.engineRunIn(xo.url, { ...req, steps }, fn, dx + xo.x, dy + xo.y);
997
+ }
998
+ const v = r?.v;
999
+ if (frame !== null && v && typeof v.x === 'number' && typeof v.y === 'number') {
1000
+ r.v = { ...v, x: v.x + dx, y: v.y + dy };
1001
+ }
1002
+ return r;
1003
+ }
1004
+ /** @internal page.evaluate() inside a cross-origin subframe, addressed by URL. */
1005
+ async evaluateInFrame(frame, fn, arg) {
1006
+ const a = JSON.stringify(serializeValue(arg));
1007
+ const src = typeof fn === 'function' ? fn.toString() : fn;
1008
+ const body = `(function(){var v=(${src});return typeof v==='function'?v(E.des(${a})):v;})()`;
1009
+ return (await this.engineCall(body, frame));
1010
+ }
1011
+ /** Log lines from the last locator-handler run that blocked a wait. */
1012
+ handlerLog = [];
1013
+ locatorHandlers = [];
1014
+ handlingLocators = false;
1015
+ /**
1016
+ * Run `handler` whenever `locator` becomes visible while an action or
1017
+ * assertion is waiting (a cookie banner, a newsletter dialog). By
1018
+ * default the wait resumes once the locator is hidden again.
1019
+ */
1020
+ async addLocatorHandler(locator, handler, options = {}) {
1021
+ this.locatorHandlers.push({ locator, handler, times: options.times ?? null, noWaitAfter: options.noWaitAfter ?? false });
1022
+ }
1023
+ async removeLocatorHandler(locator) {
1024
+ this.locatorHandlers = this.locatorHandlers.filter((h) => h.locator.toString() !== locator.toString());
1025
+ }
1026
+ /**
1027
+ * @internal Run the handlers whose locator is visible now. Called on
1028
+ * each action and assertion retry. Returns false while a handled
1029
+ * locator has not gone away yet: the caller keeps waiting, as
1030
+ * Playwright does, until it hides or the caller's time runs out.
1031
+ */
1032
+ async runLocatorHandlers(deadline = Date.now() + this.timeouts.action) {
1033
+ if (this.handlingLocators || this.locatorHandlers.length === 0)
1034
+ return true;
1035
+ this.handlingLocators = true;
1036
+ try {
1037
+ for (const h of [...this.locatorHandlers]) {
1038
+ const seen = await h.locator.peek('locatorHandler', 'visible').catch(() => ({ found: false, v: false, preview: '' }));
1039
+ if (!seen.found || seen.v !== true)
1040
+ continue;
1041
+ this.handlerLog = [`found ${h.locator.toString()}, intercepting action to run the handler`, `locator resolved to visible ${seen.preview ?? ''}`];
1042
+ await h.handler(h.locator);
1043
+ if (h.times !== null && --h.times <= 0)
1044
+ this.locatorHandlers = this.locatorHandlers.filter((x) => x !== h);
1045
+ if (h.noWaitAfter)
1046
+ continue;
1047
+ this.handlerLog.push(`locator handler has finished, waiting for ${h.locator.toString()} to be hidden`);
1048
+ const left = Math.max(1, deadline - Date.now());
1049
+ const hidden = await h.locator.waitFor({ state: 'hidden', timeout: left }).then(() => true, () => false);
1050
+ if (!hidden)
1051
+ return false;
1052
+ this.handlerLog = [];
1053
+ }
1054
+ return true;
1055
+ }
1056
+ finally {
1057
+ this.handlingLocators = false;
1058
+ }
1059
+ }
1060
+ /** Poll `fn(arg)` in the page until it returns a truthy value, and return that value. */
1061
+ async waitForFunction(fn, arg, options = {}) {
1062
+ const budget = options.timeout ?? this.timeouts.action;
1063
+ const deadline = Date.now() + budget;
1064
+ const every = typeof options.polling === 'number' ? options.polling : 16;
1065
+ const a = JSON.stringify(serializeValue(arg));
1066
+ const src = typeof fn === 'function' ? fn.toString() : fn;
1067
+ // A truthy value is adopted in the same call and handed back as a JSHandle, as in Playwright.
1068
+ const body = `(function(){var f=(${src});var v=typeof f==='function'?f(E.des(${a})):f;` +
1069
+ `var fin=function(x){return x?E.adoptValue(x):null;};return v&&typeof v.then==='function'?v.then(fin):fin(v);})()`;
1070
+ for (;;) {
1071
+ const r = (await this.engineCall(body));
1072
+ if (r) {
1073
+ const h = r.el ? new ElementHandle(this, r.id) : new JSHandle(this, r.id);
1074
+ h.previewText = r.p ?? '';
1075
+ return h;
1076
+ }
1077
+ if (budget > 0 && Date.now() >= deadline) {
1078
+ throw new Error(`page.waitForFunction: Timeout ${budget}ms exceeded.`);
1079
+ }
1080
+ await sleep(every);
1081
+ }
1082
+ }
1083
+ /** `fn(element, arg)` on the first element matching `selector`; throws when there is none. */
1084
+ async $eval(selector, fn, arg) {
1085
+ const r = await this.engineRun({ steps: this.locator(selector).wire(), op: 'eval', args: { arg: serializeValue(arg) }, first: true }, fn.toString());
1086
+ if (r.none)
1087
+ throw new Error(`page.$eval: Error: failed to find element matching selector "${selector}"`);
1088
+ return r.v;
1089
+ }
1090
+ /** `fn(elements, arg)` with every element matching `selector`. */
1091
+ async $$eval(selector, fn, arg) {
1092
+ return this.locator(selector).evaluateAll(fn, arg);
1093
+ }
1094
+ /** The first element matching `selector`, or null. */
1095
+ async $(selector) {
1096
+ return this.locator(selector).firstHandle();
1097
+ }
1098
+ /** Every element matching `selector`. */
1099
+ async $$(selector) {
1100
+ return this.locator(selector).elementHandles();
1101
+ }
1102
+ main = null;
1103
+ /** The page's top frame. */
1104
+ mainFrame() {
1105
+ this.main ??= new Frame(this, null, null);
1106
+ return this.main;
1107
+ }
1108
+ frameCache = [];
1109
+ lastFrameCount = 0;
1110
+ /** Refreshes run one after another, so an older listing never overwrites a newer one. */
1111
+ frameChain = Promise.resolve();
1112
+ /**
1113
+ * The main frame, then every iframe, depth first, as of the last
1114
+ * navigation or refreshFrames() call (Playwright's frames() is
1115
+ * synchronous; testsurfer reads the frame tree after each load).
1116
+ */
1117
+ frames() {
1118
+ return [this.mainFrame(), ...this.frameCache];
1119
+ }
1120
+ /** Re-read the frame tree, for iframes added after the page loaded. */
1121
+ async refreshFrames() {
1122
+ const next = this.frameChain.then(() => this.readFrames(), () => this.readFrames());
1123
+ this.frameChain = next;
1124
+ return next;
1125
+ }
1126
+ async readFrames() {
1127
+ let rows = [];
1128
+ try {
1129
+ rows = (await this.engineCall(FRAMES_CALL));
1130
+ }
1131
+ catch {
1132
+ rows = [];
1133
+ }
1134
+ const byId = new Map();
1135
+ const known = new Map(this.frameCache.map((f) => [f.elementId(), f]));
1136
+ const out = [];
1137
+ for (const [id, parent, name, url, xo] of rows) {
1138
+ // An iframe already listed keeps its Frame object (Playwright compares them by identity).
1139
+ const f = known.get(id) ?? new Frame(this, new ElementHandle(this, id), parent === null ? this.mainFrame() : (byId.get(parent) ?? this.mainFrame()));
1140
+ f.frameName = name;
1141
+ f.frameUrl = url;
1142
+ f.crossOrigin = xo === 1;
1143
+ byId.set(id, f);
1144
+ out.push(f);
1145
+ }
1146
+ this.frameCache = out;
1147
+ return this.frames();
1148
+ }
1149
+ /** A frame by name, or by URL (string, RegExp or predicate). */
1150
+ frame(match) {
1151
+ const all = this.frames();
1152
+ const m = typeof match === 'string' ? { name: match } : match;
1153
+ return (all.find((f) => {
1154
+ if (m.name !== undefined && f.name() !== m.name)
1155
+ return false;
1156
+ if (m.url !== undefined) {
1157
+ const u = f === this.main ? '' : f.frameUrl;
1158
+ if (typeof m.url === 'string' && !urlMatches(m.url, u, this.baseURL))
1159
+ return false;
1160
+ if (m.url instanceof RegExp && !m.url.test(u))
1161
+ return false;
1162
+ if (typeof m.url === 'function' && !(u && m.url(new URL(u))))
1163
+ return false;
1164
+ }
1165
+ return true;
1166
+ }) ?? null);
1167
+ }
1168
+ /**
1169
+ * Make `fn` callable from the page as `window[name](...args)`; the
1170
+ * call returns a promise of fn's result. Arguments and results cross
1171
+ * as JSON. Covers this document and every later one.
1172
+ */
1173
+ async exposeFunction(name, fn) {
1174
+ await this.exposeBinding(name, (_source, ...args) => fn(...args));
1175
+ }
1176
+ /** Like exposeFunction, with `{ page, context, frame }` as the first argument. */
1177
+ async exposeBinding(name, fn) {
1178
+ const script = this.events.addBinding(name, (...args) => fn({ page: this, context: this.ctx, frame: this.mainFrame() }, ...args));
1179
+ await this.ensureShim();
1180
+ await this.addInitSource(script);
1181
+ await this.events.sync();
1182
+ if (this.pageId)
1183
+ await this.rawEval(`(${script.replace(/;\s*$/, '')}, 0)`).catch(() => { });
1184
+ }
1185
+ extraHeaders = {};
1186
+ /** @internal Re-apply routing after the context's network settings changed. */
1187
+ async refreshNetwork() {
1188
+ await this.events.sync();
1189
+ }
1190
+ /**
1191
+ * Headers added to every request this page makes. In proxy mode they
1192
+ * reach every http request; otherwise fetch and XHR only.
1193
+ */
1194
+ async setExtraHTTPHeaders(headers) {
1195
+ this.extraHeaders = Object.fromEntries(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), String(v)]));
1196
+ await this.events.sync();
1197
+ }
1198
+ /** Like evaluate(), but keeps the result in the page and returns a handle to it. */
1199
+ async evaluateHandle(fn, arg) {
1200
+ const a = JSON.stringify(serializeValue(arg));
1201
+ const src = typeof fn === 'function' ? fn.toString() : fn;
1202
+ return this.adoptResult(`(function(){var v=(${src});return typeof v==='function'?v(E.des(${a})):v;})()`);
1203
+ }
1204
+ /** @internal Evaluate `expr` (may be a promise) and hand back a handle to its value. */
1205
+ async adoptResult(expr) {
1206
+ const r = (await this.engineCall(`E.adoptValue(${expr})`));
1207
+ const h = r.el ? new ElementHandle(this, r.id) : new JSHandle(this, r.id);
1208
+ h.previewText = r.p ?? '';
1209
+ return h;
1210
+ }
1211
+ /** Wait for `selector` to reach a state (visible by default); returns the element as a locator. */
1212
+ async waitForSelector(selector, options = {}) {
1213
+ const l = this.locator(selector);
1214
+ await l.first().waitFor(options);
1215
+ return options.state === 'detached' || options.state === 'hidden' ? null : l.firstHandle();
1216
+ }
1217
+ // Selector shorthands (Playwright's page.click(selector) family).
1218
+ // Not strict unless asked (`strict: true`): the first match acts, as in Playwright.
1219
+ pick(selector, options) {
1220
+ const l = this.locator(selector);
1221
+ return options?.strict ? l : l.first();
1222
+ }
1223
+ click(selector, options) {
1224
+ return this.pick(selector, options).click(options);
1225
+ }
1226
+ dblclick(selector, options) {
1227
+ return this.pick(selector, options).dblclick(options);
1228
+ }
1229
+ tap(selector, options) {
1230
+ return this.pick(selector, options).tap(options);
1231
+ }
1232
+ hover(selector, options) {
1233
+ return this.pick(selector, options).hover(options);
1234
+ }
1235
+ focus(selector, options) {
1236
+ return this.pick(selector, options).focus(options);
1237
+ }
1238
+ fill(selector, value, options) {
1239
+ return this.pick(selector, options).fill(value, options);
1240
+ }
1241
+ type(selector, text, options) {
1242
+ return this.pick(selector, options).type(text, options);
1243
+ }
1244
+ press(selector, key, options) {
1245
+ return this.pick(selector, options).press(key, options);
1246
+ }
1247
+ check(selector, options) {
1248
+ return this.pick(selector, options).check(options);
1249
+ }
1250
+ uncheck(selector, options) {
1251
+ return this.pick(selector, options).uncheck(options);
1252
+ }
1253
+ setChecked(selector, checked, options) {
1254
+ return this.pick(selector, options).setChecked(checked, options);
1255
+ }
1256
+ selectOption(selector, values, options) {
1257
+ return this.pick(selector, options).selectOption(values, options);
1258
+ }
1259
+ setInputFiles(selector, files, options) {
1260
+ return this.pick(selector, options).setInputFiles(files, options);
1261
+ }
1262
+ dispatchEvent(selector, type, eventInit, options) {
1263
+ return this.pick(selector, options).dispatchEvent(type, eventInit, options);
1264
+ }
1265
+ textContent(selector, options) {
1266
+ return this.pick(selector, options).textContent(options);
1267
+ }
1268
+ innerText(selector, options) {
1269
+ return this.pick(selector, options).innerText(options);
1270
+ }
1271
+ innerHTML(selector, options) {
1272
+ return this.pick(selector, options).innerHTML(options);
1273
+ }
1274
+ getAttribute(selector, name, options) {
1275
+ return this.pick(selector, options).getAttribute(name, options);
1276
+ }
1277
+ inputValue(selector, options) {
1278
+ return this.pick(selector, options).inputValue(options);
1279
+ }
1280
+ isVisible(selector) {
1281
+ return this.pick(selector).isVisible();
1282
+ }
1283
+ isHidden(selector) {
1284
+ return this.pick(selector).isHidden();
1285
+ }
1286
+ isChecked(selector, options) {
1287
+ return this.pick(selector, options).isChecked(options);
1288
+ }
1289
+ isDisabled(selector, options) {
1290
+ return this.pick(selector, options).isDisabled(options);
1291
+ }
1292
+ isEnabled(selector, options) {
1293
+ return this.pick(selector, options).isEnabled(options);
1294
+ }
1295
+ isEditable(selector, options) {
1296
+ return this.pick(selector, options).isEditable(options);
1297
+ }
1298
+ /**
1299
+ * Keyboard input to the focused element. press/down/up dispatch key
1300
+ * events with the browser's default action (typing, Enter submits,
1301
+ * Backspace deletes, Tab moves focus); type() sends trusted
1302
+ * per-character input.
1303
+ */
1304
+ keyboard = {
1305
+ press: async (key, _options) => {
1306
+ await this.engineCall(`E.key(${JSON.stringify(key)})`);
1307
+ },
1308
+ down: async (key) => {
1309
+ await this.engineCall(`E.key(${JSON.stringify(key)},'down')`);
1310
+ },
1311
+ up: async (key) => {
1312
+ await this.engineCall(`E.key(${JSON.stringify(key)},'up')`);
1313
+ },
1314
+ type: async (text, _options) => {
1315
+ await this.typeTrusted(text);
1316
+ },
1317
+ insertText: async (text) => {
1318
+ await this.engineCall(`E.insertText(${JSON.stringify(text)})`);
1319
+ },
1320
+ };
1321
+ viewport = null;
1322
+ dpr = 1;
1323
+ /** @internal Size every new web view of this page gets. */
1324
+ initialViewport(size, dpr) {
1325
+ this.viewport = size;
1326
+ this.dpr = dpr;
1327
+ }
1328
+ /**
1329
+ * @internal Take over a blank page the browser opened ahead of time
1330
+ * (see Browser.newContext), already sized to `sized`. The first goto
1331
+ * then navigates it in place instead of opening a web view.
1332
+ */
1333
+ async adoptBlank(pageId, token, sized) {
1334
+ this.pageId = pageId;
1335
+ this.token = token;
1336
+ const same = sized && this.viewport && sized.width === this.viewport.width && sized.height === this.viewport.height && sized.dpr === this.dpr;
1337
+ if (!same)
1338
+ await this.applyViewport();
1339
+ this.events.documentChanged();
1340
+ }
1341
+ async applyViewport() {
1342
+ if (!this.viewport || !this.pageId)
1343
+ return;
1344
+ await this.client.call('vs_viewport', [this.pageId, `${this.viewport.width}x${this.viewport.height}`], {
1345
+ session: this.sessionId,
1346
+ dpr: String(this.dpr),
1347
+ });
1348
+ this.snapshot = null;
1349
+ this.synced = false;
1350
+ this.fresh = false;
1351
+ }
1352
+ /** Resize the page (CSS px). */
1353
+ async setViewportSize(size) {
1354
+ this.viewport = { width: size.width, height: size.height };
1355
+ await this.applyViewport();
1356
+ }
1357
+ viewportSize() {
1358
+ return this.viewport ? { ...this.viewport } : null;
1359
+ }
1360
+ /** Viewport crop of the page around `box` (CSS px), as PNG bytes; written to `path` when given. */
1361
+ async screenshotClip(box, path) {
1362
+ const file = await this.capture(null);
1363
+ const fs = await import('node:fs/promises');
1364
+ const img = decodePng(await fs.readFile(file));
1365
+ const cssWidth = await this.evaluate('window.innerWidth');
1366
+ const scale = img.width / (cssWidth || img.width);
1367
+ const x0 = Math.max(0, Math.floor(box.x * scale));
1368
+ const y0 = Math.max(0, Math.floor(box.y * scale));
1369
+ const x1 = Math.min(img.width, Math.ceil((box.x + box.width) * scale));
1370
+ const y1 = Math.min(img.height, Math.ceil((box.y + box.height) * scale));
1371
+ const w = Math.max(1, x1 - x0);
1372
+ const h = Math.max(1, y1 - y0);
1373
+ const data = new Uint8Array(w * h * 4);
1374
+ for (let y = 0; y < h; y++) {
1375
+ const src = ((y0 + y) * img.width + x0) * 4;
1376
+ data.set(img.data.subarray(src, src + w * 4), y * w * 4);
1377
+ }
1378
+ // The engine captures at the screen's scale; deliver the configured device scale factor.
1379
+ const factor = Math.round(scale / this.dpr);
1380
+ const out = encodePng(factor > 1 ? downscale({ width: w, height: h, data }, factor) : { width: w, height: h, data });
1381
+ if (path) {
1382
+ const nodePath = await import('node:path');
1383
+ await fs.mkdir(nodePath.dirname(path), { recursive: true });
1384
+ await fs.writeFile(path, out);
1385
+ }
1386
+ return out;
1387
+ }
371
1388
  /** The page's current URL. */
372
- async url() {
373
- return this.evaluate('location.href');
1389
+ /** The location every engine call reports; Playwright's page.url() is synchronous. */
1390
+ lastHref = 'about:blank';
1391
+ /** A service worker controlled the page as of the last engine call. */
1392
+ swControlled = false;
1393
+ /** The page's URL as of the last call into the page (actions, reads and navigations all refresh it). */
1394
+ url() {
1395
+ return this.shownURL(this.lastHref);
1396
+ }
1397
+ /** Read location.href now. */
1398
+ async currentURL() {
1399
+ this.lastHref = await this.evaluate('location.href');
1400
+ return this.url();
1401
+ }
1402
+ shownURL(href) {
1403
+ const nav = this.navURL;
1404
+ if (!nav || href !== nav.actual) {
1405
+ // WebKit percent-encodes data: URLs; show them as written.
1406
+ if (href.startsWith('data:')) {
1407
+ try {
1408
+ return decodeURI(href);
1409
+ }
1410
+ catch {
1411
+ return href;
1412
+ }
1413
+ }
1414
+ return href;
1415
+ }
1416
+ // The engine percent-encodes a data: URL; report it as given, and a
1417
+ // setContent() page as the about:blank Playwright would show.
1418
+ return nav.shown;
1419
+ }
1420
+ /** What goto() was asked for, and what the engine then reports. */
1421
+ navURL = null;
1422
+ async rememberNav(shown, requested) {
1423
+ if (!requested.startsWith('data:')) {
1424
+ this.navURL = null;
1425
+ return;
1426
+ }
1427
+ const actual = await this.evaluate('location.href').catch(() => '');
1428
+ this.navURL = actual ? { shown, actual } : null;
374
1429
  }
375
1430
  /**
376
1431
  * Save a PNG of the viewport (or the whole page with `fullPage`).
377
1432
  * Returns the file path; with `path`, the file is copied there.
378
1433
  */
379
1434
  async screenshot(options = {}) {
1435
+ if (options.clip)
1436
+ return this.screenshotClip(options.clip, options.path);
1437
+ const file = await this.capture(null, options.fullPage ? { fullPage: true } : {});
1438
+ const fs = await import('node:fs/promises');
1439
+ let buf = await fs.readFile(file);
1440
+ const img = decodePng(buf);
1441
+ const cssWidth = await this.evaluate('window.innerWidth');
1442
+ const factor = Math.round(img.width / (cssWidth || img.width) / this.dpr);
1443
+ if (factor > 1)
1444
+ buf = encodePng(downscale(img, factor));
1445
+ if (options.path) {
1446
+ const nodePath = await import('node:path');
1447
+ await fs.mkdir(nodePath.dirname(options.path), { recursive: true });
1448
+ await fs.writeFile(options.path, buf);
1449
+ }
1450
+ return buf;
1451
+ }
1452
+ /** PNG of the page, or of one element when `ref` is given. Returns the file path. */
1453
+ async capture(ref, options = {}) {
1454
+ await this.ensureOpen();
380
1455
  const flags = { session: this.sessionId };
381
1456
  if (options.fullPage)
382
1457
  flags['full-page'] = true;
383
- const resp = await this.client.call('vs_capture', [this.id], flags);
1458
+ const args = ref === null ? [this.id] : [this.id, String(ref)];
1459
+ const resp = await this.client.call('vs_capture', args, flags);
384
1460
  const saved = (resp.body[0] ?? '').trim();
385
1461
  if (!saved)
386
1462
  throw new Error('vs_capture returned no path');
@@ -397,6 +1473,12 @@ export class Page {
397
1473
  * IndexedDB) under `name`, encrypted at rest by the daemon. Load it
398
1474
  * in a later run with loadAuth(name) to skip the login flow.
399
1475
  */
1476
+ /** @internal Load an imported cookie blob into this page's jar (the session's). */
1477
+ async loadCookieBlob(name) {
1478
+ await this.ensureOpen();
1479
+ await this.client.call('vs_auth', ['load', this.id, name], { session: this.sessionId });
1480
+ await this.client.call('vs_auth', ['clear', name], { session: this.sessionId }).catch(() => { });
1481
+ }
400
1482
  async saveAuth(name) {
401
1483
  await this.client.call('vs_auth', ['save', this.id, name], { session: this.sessionId });
402
1484
  }
@@ -423,17 +1505,70 @@ export class Page {
423
1505
  * mode unless a call overrides it.
424
1506
  */
425
1507
  mouse = {
426
- move: (x, y, options) => this.cursorOp('vs_move_to', [x, y], options?.mode, false),
427
- click: (x, y, options) => this.clickAt(x, y, options?.mode),
1508
+ /**
1509
+ * Move the pointer. While a button is down (mouse.down()), the move
1510
+ * is only recorded: the press, the path and the release go out as
1511
+ * one native drag at mouse.up(), so the page sees them in order.
1512
+ */
1513
+ move: async (x, y, options) => {
1514
+ this.pointer = { x, y };
1515
+ if (this.pressedAt)
1516
+ return;
1517
+ await this.cursorOp('vs_move_to', [x, y], options?.mode, false);
1518
+ },
1519
+ click: async (x, y, options) => {
1520
+ this.pointer = { x, y };
1521
+ await this.clickAt(x, y, options?.mode);
1522
+ },
1523
+ down: async () => {
1524
+ this.pressedAt = { ...this.pointer };
1525
+ },
1526
+ up: async (options) => {
1527
+ const from = this.pressedAt;
1528
+ this.pressedAt = null;
1529
+ if (!from)
1530
+ return;
1531
+ const to = this.pointer;
1532
+ if (from.x === to.x && from.y === to.y)
1533
+ await this.clickAt(to.x, to.y, options?.mode);
1534
+ else
1535
+ await this.cursorOp('vs_drag', [from.x, from.y, to.x, to.y], options?.mode, true);
1536
+ },
1537
+ /**
1538
+ * Scroll by (deltaX, deltaY) at the pointer: a wheel event goes to
1539
+ * the element there and, unless the page cancels it, the nearest
1540
+ * scrollable box scrolls. The event is dispatched in the page, so
1541
+ * it is not trusted.
1542
+ */
1543
+ wheel: async (deltaX, deltaY) => {
1544
+ const { x, y } = this.pointer;
1545
+ await this.evaluate(`([x, y, dx, dy]) => new Promise((done) => {
1546
+ const t = document.elementFromPoint(x, y) || document.scrollingElement || document.body;
1547
+ const ev = new WheelEvent('wheel', { deltaX: dx, deltaY: dy, deltaMode: 0, clientX: x, clientY: y, bubbles: true, cancelable: true, composed: true });
1548
+ if (t.dispatchEvent(ev)) {
1549
+ let s = t instanceof Element ? t : null;
1550
+ const scrolls = (e) => {
1551
+ const st = getComputedStyle(e);
1552
+ return (/(auto|scroll|overlay)/.test(st.overflowY) && e.scrollHeight > e.clientHeight) || (/(auto|scroll|overlay)/.test(st.overflowX) && e.scrollWidth > e.clientWidth);
1553
+ };
1554
+ while (s && s !== document.documentElement && s !== document.body && !scrolls(s)) s = s.parentElement;
1555
+ const box = s && s !== document.documentElement && s !== document.body ? s : (document.scrollingElement || document.documentElement);
1556
+ box.scrollBy({ left: dx, top: dy, behavior: 'instant' });
1557
+ }
1558
+ requestAnimationFrame(() => requestAnimationFrame(() => done(0)));
1559
+ })`, [x, y, deltaX, deltaY]);
1560
+ },
428
1561
  /** Press at (x1, y1), move along a path, release at (x2, y2). Fires the HTML5 drag events too. */
429
1562
  drag: (x1, y1, x2, y2, options) => this.cursorOp('vs_drag', [x1, y1, x2, y2], options?.mode, true),
430
1563
  };
1564
+ /** Where mouse.move/click last put the pointer, and where mouse.down pressed. */
1565
+ pointer = { x: 0, y: 0 };
1566
+ pressedAt = null;
431
1567
  async cursorOp(op, coords, mode, mutates) {
432
- if (this.token === null)
433
- await this.view();
1568
+ await this.ensureOpen();
434
1569
  const flags = { session: this.sessionId, mode: mode ?? this.inputMode };
435
1570
  if (mutates)
436
- flags['token'] = this.token ?? '';
1571
+ flags['token'] = this.token ?? '0';
437
1572
  try {
438
1573
  const resp = await this.client.call(op, [this.id, ...coords.map((c) => String(Math.round(c)))], flags);
439
1574
  if (resp.token && !/^0+$/.test(resp.token))
@@ -457,14 +1592,9 @@ export class Page {
457
1592
  const snap = await this.view();
458
1593
  return renderSnapshot(snap, snap.roots);
459
1594
  }
460
- /** The document title (the doc node's label). */
1595
+ /** The document title. */
461
1596
  async title() {
462
- const snap = await this.view();
463
- for (const node of walk(snap)) {
464
- if (node.role === 'doc')
465
- return node.label;
466
- }
467
- return '';
1597
+ return this.evaluate('document.title');
468
1598
  }
469
1599
  getByRole(role, options = {}) {
470
1600
  return new Locator(this, { kind: 'role', role, options });
@@ -475,13 +1605,39 @@ export class Page {
475
1605
  getByLabel(text, options = {}) {
476
1606
  return new Locator(this, { kind: 'label', text, options });
477
1607
  }
1608
+ /** Locators inside the iframe matching `selector` (same-origin frames, vibesurfer 0.2.15+). */
1609
+ frameLocator(selector) {
1610
+ return new FrameLocator(this.locator(selector));
1611
+ }
1612
+ /** Elements matching a CSS selector, mapped to their tree nodes. */
1613
+ locator(selector, options) {
1614
+ const l = new Locator(this, selectorSteps(selector));
1615
+ return options && Object.keys(options).length ? l.filter(options) : l;
1616
+ }
1617
+ /** Exact match on the test-id attribute (`data-testid` by default). */
1618
+ getByTestId(id) {
1619
+ return new Locator(this, byAttr('getByTestId', this.testIdAttribute, id, true));
1620
+ }
1621
+ /** Fields by placeholder text (substring, case-insensitive; exact for whole-string). */
1622
+ getByPlaceholder(text, options = {}) {
1623
+ return new Locator(this, byAttr('getByPlaceholder', 'placeholder', text, options.exact ?? false));
1624
+ }
1625
+ /** Images and areas by alt text. */
1626
+ getByAltText(text, options = {}) {
1627
+ return new Locator(this, byAttr('getByAltText', 'alt', text, options.exact ?? false));
1628
+ }
1629
+ /** Elements by their title attribute. */
1630
+ getByTitle(text, options = {}) {
1631
+ return new Locator(this, byAttr('getByTitle', 'title', text, options.exact ?? false));
1632
+ }
478
1633
  async close() {
479
- if (!this.pageId)
1634
+ if (this.closedFlag)
480
1635
  return;
481
- await this.client
482
- .call('vs_close', [this.pageId], { session: this.sessionId })
483
- .catch(() => { });
1636
+ const id = this.pageId;
484
1637
  this.pageId = null;
1638
+ this.markClosed();
1639
+ if (id)
1640
+ await this.client.call('vs_close', [id], { session: this.sessionId }).catch(() => { });
485
1641
  this.token = null;
486
1642
  this.snapshot = null;
487
1643
  this.synced = false;