@ricsam/isolate-playwright 0.1.13 → 0.1.15

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.
@@ -3,1082 +3,149 @@ import ivm from "isolated-vm";
3
3
  import {
4
4
  DEFAULT_PLAYWRIGHT_HANDLER_META
5
5
  } from "./types.mjs";
6
- function getLocator(page, selectorType, selectorValue, optionsJson) {
7
- const options = optionsJson ? JSON.parse(optionsJson) : undefined;
8
- const nthIndex = options?.nth;
9
- const roleOptions = options ? { ...options } : undefined;
10
- if (roleOptions) {
11
- delete roleOptions.nth;
12
- delete roleOptions.filter;
13
- if (roleOptions.name && typeof roleOptions.name === "object" && roleOptions.name.$regex) {
14
- roleOptions.name = new RegExp(roleOptions.name.$regex, roleOptions.name.$flags);
15
- }
16
- }
17
- let locator;
18
- switch (selectorType) {
19
- case "css":
20
- locator = page.locator(selectorValue);
21
- break;
22
- case "role":
23
- locator = page.getByRole(selectorValue, roleOptions && Object.keys(roleOptions).length > 0 ? roleOptions : undefined);
24
- break;
25
- case "text":
26
- locator = page.getByText(selectorValue);
27
- break;
28
- case "label":
29
- locator = page.getByLabel(selectorValue);
30
- break;
31
- case "placeholder":
32
- locator = page.getByPlaceholder(selectorValue);
33
- break;
34
- case "testId":
35
- locator = page.getByTestId(selectorValue);
36
- break;
37
- case "or": {
38
- const [firstInfo, secondInfo] = JSON.parse(selectorValue);
39
- const first = getLocator(page, firstInfo[0], firstInfo[1], firstInfo[2]);
40
- const second = getLocator(page, secondInfo[0], secondInfo[1], secondInfo[2]);
41
- locator = first.or(second);
42
- break;
43
- }
44
- case "and": {
45
- const [firstInfo, secondInfo] = JSON.parse(selectorValue);
46
- const first = getLocator(page, firstInfo[0], firstInfo[1], firstInfo[2]);
47
- const second = getLocator(page, secondInfo[0], secondInfo[1], secondInfo[2]);
48
- locator = first.and(second);
49
- break;
50
- }
51
- case "chained": {
52
- const [parentInfo, childInfo] = JSON.parse(selectorValue);
53
- const parent = getLocator(page, parentInfo[0], parentInfo[1], parentInfo[2]);
54
- const childType = childInfo[0];
55
- const childValue = childInfo[1];
56
- const childOptionsJson = childInfo[2];
57
- const childOptions = childOptionsJson ? JSON.parse(childOptionsJson) : undefined;
58
- switch (childType) {
59
- case "css":
60
- locator = parent.locator(childValue);
61
- break;
62
- case "role": {
63
- const roleOpts = childOptions ? { ...childOptions } : undefined;
64
- if (roleOpts) {
65
- delete roleOpts.nth;
66
- delete roleOpts.filter;
67
- if (roleOpts.name && typeof roleOpts.name === "object" && roleOpts.name.$regex) {
68
- roleOpts.name = new RegExp(roleOpts.name.$regex, roleOpts.name.$flags);
69
- }
70
- }
71
- locator = parent.getByRole(childValue, roleOpts && Object.keys(roleOpts).length > 0 ? roleOpts : undefined);
72
- break;
73
- }
74
- case "text":
75
- locator = parent.getByText(childValue);
76
- break;
77
- case "label":
78
- locator = parent.getByLabel(childValue);
79
- break;
80
- case "placeholder":
81
- locator = parent.getByPlaceholder(childValue);
82
- break;
83
- case "testId":
84
- locator = parent.getByTestId(childValue);
85
- break;
86
- case "altText":
87
- locator = parent.getByAltText(childValue);
88
- break;
89
- case "title":
90
- locator = parent.getByTitle(childValue);
91
- break;
92
- default:
93
- locator = parent.locator(childValue);
94
- }
95
- if (childOptions?.nth !== undefined) {
96
- locator = locator.nth(childOptions.nth);
97
- }
98
- if (childOptions?.filter) {
99
- const filterOpts = { ...childOptions.filter };
100
- if (filterOpts.hasText && typeof filterOpts.hasText === "object" && filterOpts.hasText.$regex) {
101
- filterOpts.hasText = new RegExp(filterOpts.hasText.$regex, filterOpts.hasText.$flags);
102
- }
103
- if (filterOpts.hasNotText && typeof filterOpts.hasNotText === "object" && filterOpts.hasNotText.$regex) {
104
- filterOpts.hasNotText = new RegExp(filterOpts.hasNotText.$regex, filterOpts.hasNotText.$flags);
105
- }
106
- locator = locator.filter(filterOpts);
107
- }
108
- break;
109
- }
110
- case "altText":
111
- locator = page.getByAltText(selectorValue);
112
- break;
113
- case "title":
114
- locator = page.getByTitle(selectorValue);
115
- break;
116
- case "frame": {
117
- const [frameSelectorInfo, innerLocatorInfo] = JSON.parse(selectorValue);
118
- const frameSelector = frameSelectorInfo[1];
119
- const frame = page.frameLocator(frameSelector);
120
- const innerType = innerLocatorInfo[0];
121
- const innerValue = innerLocatorInfo[1];
122
- const innerOptionsJson = innerLocatorInfo[2];
123
- const innerOptions = innerOptionsJson ? JSON.parse(innerOptionsJson) : undefined;
124
- switch (innerType) {
125
- case "css":
126
- locator = frame.locator(innerValue);
127
- break;
128
- case "role": {
129
- const roleOpts = innerOptions ? { ...innerOptions } : undefined;
130
- if (roleOpts) {
131
- delete roleOpts.nth;
132
- delete roleOpts.filter;
133
- if (roleOpts.name && typeof roleOpts.name === "object" && roleOpts.name.$regex) {
134
- roleOpts.name = new RegExp(roleOpts.name.$regex, roleOpts.name.$flags);
135
- }
136
- }
137
- locator = frame.getByRole(innerValue, roleOpts && Object.keys(roleOpts).length > 0 ? roleOpts : undefined);
138
- break;
139
- }
140
- case "text":
141
- locator = frame.getByText(innerValue);
142
- break;
143
- case "label":
144
- locator = frame.getByLabel(innerValue);
145
- break;
146
- case "placeholder":
147
- locator = frame.getByPlaceholder(innerValue);
148
- break;
149
- case "testId":
150
- locator = frame.getByTestId(innerValue);
151
- break;
152
- case "altText":
153
- locator = frame.getByAltText(innerValue);
154
- break;
155
- case "title":
156
- locator = frame.getByTitle(innerValue);
157
- break;
158
- default:
159
- locator = frame.locator(innerValue);
160
- }
161
- if (innerOptions?.nth !== undefined) {
162
- locator = locator.nth(innerOptions.nth);
163
- }
164
- if (innerOptions?.filter) {
165
- const filterOpts = { ...innerOptions.filter };
166
- if (filterOpts.hasText && typeof filterOpts.hasText === "object" && filterOpts.hasText.$regex) {
167
- filterOpts.hasText = new RegExp(filterOpts.hasText.$regex, filterOpts.hasText.$flags);
168
- }
169
- if (filterOpts.hasNotText && typeof filterOpts.hasNotText === "object" && filterOpts.hasNotText.$regex) {
170
- filterOpts.hasNotText = new RegExp(filterOpts.hasNotText.$regex, filterOpts.hasNotText.$flags);
171
- }
172
- locator = locator.filter(filterOpts);
173
- }
174
- break;
175
- }
176
- default:
177
- locator = page.locator(selectorValue);
178
- }
179
- if (nthIndex !== undefined) {
180
- locator = locator.nth(nthIndex);
181
- }
182
- if (options?.filter) {
183
- const filterOpts = { ...options.filter };
184
- if (filterOpts.hasText && typeof filterOpts.hasText === "object" && filterOpts.hasText.$regex) {
185
- filterOpts.hasText = new RegExp(filterOpts.hasText.$regex, filterOpts.hasText.$flags);
186
- }
187
- if (filterOpts.hasNotText && typeof filterOpts.hasNotText === "object" && filterOpts.hasNotText.$regex) {
188
- filterOpts.hasNotText = new RegExp(filterOpts.hasNotText.$regex, filterOpts.hasNotText.$flags);
189
- }
190
- locator = locator.filter(filterOpts);
191
- }
192
- return locator;
193
- }
194
- async function executeLocatorAction(locator, action, actionArg, timeout, fileIO) {
195
- switch (action) {
196
- case "click":
197
- await locator.click({ timeout });
198
- return null;
199
- case "dblclick":
200
- await locator.dblclick({ timeout });
201
- return null;
202
- case "fill":
203
- await locator.fill(String(actionArg ?? ""), { timeout });
204
- return null;
205
- case "type":
206
- await locator.pressSequentially(String(actionArg ?? ""), { timeout });
207
- return null;
208
- case "check":
209
- await locator.check({ timeout });
210
- return null;
211
- case "uncheck":
212
- await locator.uncheck({ timeout });
213
- return null;
214
- case "selectOption":
215
- await locator.selectOption(String(actionArg ?? ""), { timeout });
216
- return null;
217
- case "clear":
218
- await locator.clear({ timeout });
219
- return null;
220
- case "press":
221
- await locator.press(String(actionArg ?? ""), { timeout });
222
- return null;
223
- case "hover":
224
- await locator.hover({ timeout });
225
- return null;
226
- case "focus":
227
- await locator.focus({ timeout });
228
- return null;
229
- case "getText":
230
- return await locator.textContent({ timeout });
231
- case "getValue":
232
- return await locator.inputValue({ timeout });
233
- case "isVisible":
234
- return await locator.isVisible();
235
- case "isEnabled":
236
- return await locator.isEnabled();
237
- case "isChecked":
238
- return await locator.isChecked();
239
- case "count":
240
- return await locator.count();
241
- case "getAttribute":
242
- return await locator.getAttribute(String(actionArg ?? ""), { timeout });
243
- case "isDisabled":
244
- return await locator.isDisabled();
245
- case "isHidden":
246
- return await locator.isHidden();
247
- case "innerHTML":
248
- return await locator.innerHTML({ timeout });
249
- case "innerText":
250
- return await locator.innerText({ timeout });
251
- case "allTextContents":
252
- return await locator.allTextContents();
253
- case "allInnerTexts":
254
- return await locator.allInnerTexts();
255
- case "waitFor": {
256
- const opts = actionArg && typeof actionArg === "object" ? actionArg : {};
257
- await locator.waitFor({ state: opts.state, timeout: opts.timeout ?? timeout });
258
- return null;
259
- }
260
- case "boundingBox":
261
- return await locator.boundingBox({ timeout });
262
- case "setInputFiles": {
263
- const files = actionArg;
264
- if (Array.isArray(files) && files.length > 0 && typeof files[0] === "object" && "buffer" in files[0]) {
265
- const fileBuffers2 = files.map((f) => ({
266
- name: f.name,
267
- mimeType: f.mimeType,
268
- buffer: Buffer.from(f.buffer, "base64")
269
- }));
270
- await locator.setInputFiles(fileBuffers2, { timeout });
271
- return null;
272
- }
273
- const filePaths = Array.isArray(files) ? files : [files];
274
- if (!fileIO?.readFile) {
275
- throw new Error("setInputFiles() with file paths requires a readFile callback in defaultPlaywrightHandler options. " + "Either provide file data directly using { name, mimeType, buffer } format, or " + "configure a readFile callback to control file access from the isolate.");
276
- }
277
- const fileBuffers = await Promise.all(filePaths.map(async (filePath) => {
278
- const fileData = await fileIO.readFile(filePath);
279
- return {
280
- name: fileData.name,
281
- mimeType: fileData.mimeType,
282
- buffer: fileData.buffer
283
- };
284
- }));
285
- await locator.setInputFiles(fileBuffers, { timeout });
286
- return null;
287
- }
288
- case "screenshot": {
289
- const opts = actionArg;
290
- const buffer = await locator.screenshot({
291
- timeout,
292
- type: opts?.type,
293
- quality: opts?.quality
294
- });
295
- if (opts?.path) {
296
- if (!fileIO?.writeFile) {
297
- throw new Error("screenshot() with path option requires a writeFile callback in defaultPlaywrightHandler options. " + "Either omit the path option (screenshot returns base64 data), or " + "configure a writeFile callback to control file writing from the isolate.");
298
- }
299
- await fileIO.writeFile(opts.path, buffer);
300
- }
301
- return buffer.toString("base64");
302
- }
303
- case "dragTo": {
304
- const targetInfo = actionArg;
305
- const targetLocator = getLocator(locator.page(), targetInfo[0], targetInfo[1], targetInfo[2]);
306
- await locator.dragTo(targetLocator, { timeout });
307
- return null;
308
- }
309
- case "scrollIntoViewIfNeeded":
310
- await locator.scrollIntoViewIfNeeded({ timeout });
311
- return null;
312
- case "highlight":
313
- await locator.highlight();
314
- return null;
315
- case "evaluate": {
316
- const [fnString, arg] = actionArg;
317
- const fn = new Function("return (" + fnString + ")")();
318
- return await locator.evaluate(fn, arg);
319
- }
320
- case "evaluateAll": {
321
- const [fnString, arg] = actionArg;
322
- const fn = new Function("return (" + fnString + ")")();
323
- return await locator.evaluateAll(fn, arg);
324
- }
325
- default:
326
- throw new Error(`Unknown action: ${action}`);
327
- }
328
- }
329
- async function executeExpectAssertion(locator, matcher, expected, negated, timeout) {
330
- switch (matcher) {
331
- case "toBeVisible": {
332
- const isVisible = await locator.isVisible();
333
- if (negated) {
334
- if (isVisible)
335
- throw new Error("Expected element to not be visible, but it was visible");
336
- } else {
337
- if (!isVisible)
338
- throw new Error("Expected element to be visible, but it was not");
339
- }
340
- break;
341
- }
342
- case "toContainText": {
343
- const text = await locator.textContent({ timeout });
344
- let matches;
345
- let expectedDisplay;
346
- if (expected && typeof expected === "object" && expected.$regex) {
347
- const regex = new RegExp(expected.$regex, expected.$flags);
348
- matches = regex.test(text ?? "");
349
- expectedDisplay = String(regex);
350
- } else {
351
- matches = text?.includes(String(expected)) ?? false;
352
- expectedDisplay = String(expected);
353
- }
354
- if (negated) {
355
- if (matches)
356
- throw new Error(`Expected text to not contain ${expectedDisplay}, but got "${text}"`);
357
- } else {
358
- if (!matches)
359
- throw new Error(`Expected text to contain ${expectedDisplay}, but got "${text}"`);
360
- }
361
- break;
362
- }
363
- case "toHaveValue": {
364
- const value = await locator.inputValue({ timeout });
365
- const matches = value === String(expected);
366
- if (negated) {
367
- if (matches)
368
- throw new Error(`Expected value to not be "${expected}", but it was`);
369
- } else {
370
- if (!matches)
371
- throw new Error(`Expected value to be "${expected}", but got "${value}"`);
372
- }
373
- break;
374
- }
375
- case "toBeEnabled": {
376
- const isEnabled = await locator.isEnabled();
377
- if (negated) {
378
- if (isEnabled)
379
- throw new Error("Expected element to be disabled, but it was enabled");
380
- } else {
381
- if (!isEnabled)
382
- throw new Error("Expected element to be enabled, but it was disabled");
383
- }
384
- break;
385
- }
386
- case "toBeChecked": {
387
- const isChecked = await locator.isChecked();
388
- if (negated) {
389
- if (isChecked)
390
- throw new Error("Expected element to not be checked, but it was checked");
391
- } else {
392
- if (!isChecked)
393
- throw new Error("Expected element to be checked, but it was not");
394
- }
395
- break;
396
- }
397
- case "toHaveAttribute": {
398
- const { name, value } = expected;
399
- const actual = await locator.getAttribute(name, { timeout });
400
- if (value instanceof RegExp || value && typeof value === "object" && value.$regex) {
401
- const regex = value.$regex ? new RegExp(value.$regex, value.$flags) : value;
402
- const matches = regex.test(actual ?? "");
403
- if (negated) {
404
- if (matches)
405
- throw new Error(`Expected attribute "${name}" to not match ${regex}, but got "${actual}"`);
406
- } else {
407
- if (!matches)
408
- throw new Error(`Expected attribute "${name}" to match ${regex}, but got "${actual}"`);
409
- }
410
- } else {
411
- const matches = actual === String(value);
412
- if (negated) {
413
- if (matches)
414
- throw new Error(`Expected attribute "${name}" to not be "${value}", but it was`);
415
- } else {
416
- if (!matches)
417
- throw new Error(`Expected attribute "${name}" to be "${value}", but got "${actual}"`);
418
- }
419
- }
420
- break;
421
- }
422
- case "toHaveText": {
423
- const text = await locator.textContent({ timeout }) ?? "";
424
- let matches;
425
- let expectedDisplay;
426
- if (expected && typeof expected === "object" && expected.$regex) {
427
- const regex = new RegExp(expected.$regex, expected.$flags);
428
- matches = regex.test(text);
429
- expectedDisplay = String(regex);
430
- } else {
431
- matches = text === String(expected);
432
- expectedDisplay = JSON.stringify(expected);
433
- }
434
- if (negated) {
435
- if (matches)
436
- throw new Error(`Expected text to not be ${expectedDisplay}, but got "${text}"`);
437
- } else {
438
- if (!matches)
439
- throw new Error(`Expected text to be ${expectedDisplay}, but got "${text}"`);
440
- }
441
- break;
442
- }
443
- case "toHaveCount": {
444
- const count = await locator.count();
445
- const expectedCount = Number(expected);
446
- if (negated) {
447
- if (count === expectedCount)
448
- throw new Error(`Expected count to not be ${expectedCount}, but it was`);
449
- } else {
450
- if (count !== expectedCount)
451
- throw new Error(`Expected count to be ${expectedCount}, but got ${count}`);
452
- }
453
- break;
454
- }
455
- case "toBeHidden": {
456
- const isHidden = await locator.isHidden();
457
- if (negated) {
458
- if (isHidden)
459
- throw new Error("Expected element to not be hidden, but it was hidden");
460
- } else {
461
- if (!isHidden)
462
- throw new Error("Expected element to be hidden, but it was not");
463
- }
464
- break;
465
- }
466
- case "toBeDisabled": {
467
- const isDisabled = await locator.isDisabled();
468
- if (negated) {
469
- if (isDisabled)
470
- throw new Error("Expected element to not be disabled, but it was disabled");
471
- } else {
472
- if (!isDisabled)
473
- throw new Error("Expected element to be disabled, but it was not");
474
- }
475
- break;
476
- }
477
- case "toBeFocused": {
478
- const isFocused = await locator.evaluate((el) => document.activeElement === el).catch(() => false);
479
- if (negated) {
480
- if (isFocused)
481
- throw new Error("Expected element to not be focused, but it was focused");
482
- } else {
483
- if (!isFocused)
484
- throw new Error("Expected element to be focused, but it was not");
485
- }
486
- break;
487
- }
488
- case "toBeEmpty": {
489
- const text = await locator.textContent({ timeout });
490
- const value = await locator.inputValue({ timeout }).catch(() => null);
491
- const isEmpty = value !== null ? value === "" : (text ?? "") === "";
492
- if (negated) {
493
- if (isEmpty)
494
- throw new Error("Expected element to not be empty, but it was");
495
- } else {
496
- if (!isEmpty)
497
- throw new Error("Expected element to be empty, but it was not");
498
- }
499
- break;
500
- }
501
- case "toBeAttached": {
502
- const count = await locator.count();
503
- const isAttached = count > 0;
504
- if (negated) {
505
- if (isAttached)
506
- throw new Error("Expected element to not be attached to DOM, but it was");
507
- } else {
508
- if (!isAttached)
509
- throw new Error("Expected element to be attached to DOM, but it was not");
510
- }
511
- break;
512
- }
513
- case "toBeEditable": {
514
- const isEditable = await locator.isEditable({ timeout });
515
- if (negated) {
516
- if (isEditable)
517
- throw new Error("Expected element to not be editable, but it was");
518
- } else {
519
- if (!isEditable)
520
- throw new Error("Expected element to be editable, but it was not");
521
- }
522
- break;
523
- }
524
- case "toHaveClass": {
525
- const classAttr = await locator.getAttribute("class", { timeout }) ?? "";
526
- const classes = classAttr.split(/\s+/).filter(Boolean);
527
- let matches;
528
- let expectedDisplay;
529
- if (expected && typeof expected === "object" && expected.$regex) {
530
- const regex = new RegExp(expected.$regex, expected.$flags);
531
- matches = regex.test(classAttr);
532
- expectedDisplay = String(regex);
533
- } else if (Array.isArray(expected)) {
534
- matches = expected.every((c) => classes.includes(c));
535
- expectedDisplay = JSON.stringify(expected);
536
- } else {
537
- matches = classAttr === String(expected) || classes.includes(String(expected));
538
- expectedDisplay = String(expected);
539
- }
540
- if (negated) {
541
- if (matches)
542
- throw new Error(`Expected class to not match ${expectedDisplay}, but got "${classAttr}"`);
543
- } else {
544
- if (!matches)
545
- throw new Error(`Expected class to match ${expectedDisplay}, but got "${classAttr}"`);
546
- }
547
- break;
548
- }
549
- case "toContainClass": {
550
- const classAttr = await locator.getAttribute("class", { timeout }) ?? "";
551
- const classes = classAttr.split(/\s+/).filter(Boolean);
552
- const expectedClass = String(expected);
553
- const hasClass = classes.includes(expectedClass);
554
- if (negated) {
555
- if (hasClass)
556
- throw new Error(`Expected element to not contain class "${expectedClass}", but it does`);
557
- } else {
558
- if (!hasClass)
559
- throw new Error(`Expected element to contain class "${expectedClass}", but classes are "${classAttr}"`);
560
- }
561
- break;
562
- }
563
- case "toHaveId": {
564
- const id = await locator.getAttribute("id", { timeout });
565
- const matches = id === String(expected);
566
- if (negated) {
567
- if (matches)
568
- throw new Error(`Expected id to not be "${expected}", but it was`);
569
- } else {
570
- if (!matches)
571
- throw new Error(`Expected id to be "${expected}", but got "${id}"`);
572
- }
573
- break;
574
- }
575
- case "toBeInViewport": {
576
- const isInViewport = await locator.evaluate((el) => {
577
- const rect = el.getBoundingClientRect();
578
- return rect.top < window.innerHeight && rect.bottom > 0 && rect.left < window.innerWidth && rect.right > 0;
579
- });
580
- if (negated) {
581
- if (isInViewport)
582
- throw new Error("Expected element to not be in viewport, but it was");
583
- } else {
584
- if (!isInViewport)
585
- throw new Error("Expected element to be in viewport, but it was not");
586
- }
587
- break;
588
- }
589
- case "toHaveCSS": {
590
- const { name, value } = expected;
591
- const actual = await locator.evaluate((el, propName) => {
592
- return getComputedStyle(el).getPropertyValue(propName);
593
- }, name);
594
- let matches;
595
- if (value && typeof value === "object" && value.$regex) {
596
- const regex = new RegExp(value.$regex, value.$flags);
597
- matches = regex.test(actual);
598
- } else {
599
- matches = actual === String(value);
600
- }
601
- if (negated) {
602
- if (matches)
603
- throw new Error(`Expected CSS "${name}" to not be "${value}", but it was`);
604
- } else {
605
- if (!matches)
606
- throw new Error(`Expected CSS "${name}" to be "${value}", but got "${actual}"`);
607
- }
608
- break;
609
- }
610
- case "toHaveJSProperty": {
611
- const { name, value } = expected;
612
- const actual = await locator.evaluate((el, propName) => {
613
- return el[propName];
614
- }, name);
615
- const matches = JSON.stringify(actual) === JSON.stringify(value);
616
- if (negated) {
617
- if (matches)
618
- throw new Error(`Expected JS property "${name}" to not be ${JSON.stringify(value)}, but it was`);
619
- } else {
620
- if (!matches)
621
- throw new Error(`Expected JS property "${name}" to be ${JSON.stringify(value)}, but got ${JSON.stringify(actual)}`);
622
- }
623
- break;
624
- }
625
- case "toHaveAccessibleName": {
626
- const accessibleName = await locator.evaluate((el) => {
627
- return el.getAttribute("aria-label") || el.getAttribute("aria-labelledby") || el.innerText || "";
628
- });
629
- let matches;
630
- if (expected && typeof expected === "object" && expected.$regex) {
631
- const regex = new RegExp(expected.$regex, expected.$flags);
632
- matches = regex.test(accessibleName);
633
- } else {
634
- matches = accessibleName === String(expected);
635
- }
636
- if (negated) {
637
- if (matches)
638
- throw new Error(`Expected accessible name to not be "${expected}", but it was`);
639
- } else {
640
- if (!matches)
641
- throw new Error(`Expected accessible name to be "${expected}", but got "${accessibleName}"`);
642
- }
643
- break;
644
- }
645
- case "toHaveAccessibleDescription": {
646
- const accessibleDesc = await locator.evaluate((el) => {
647
- const describedby = el.getAttribute("aria-describedby");
648
- if (describedby) {
649
- const descEl = document.getElementById(describedby);
650
- return descEl?.textContent || "";
651
- }
652
- return el.getAttribute("aria-description") || "";
653
- });
654
- let matches;
655
- if (expected && typeof expected === "object" && expected.$regex) {
656
- const regex = new RegExp(expected.$regex, expected.$flags);
657
- matches = regex.test(accessibleDesc);
658
- } else {
659
- matches = accessibleDesc === String(expected);
660
- }
661
- if (negated) {
662
- if (matches)
663
- throw new Error(`Expected accessible description to not be "${expected}", but it was`);
664
- } else {
665
- if (!matches)
666
- throw new Error(`Expected accessible description to be "${expected}", but got "${accessibleDesc}"`);
667
- }
668
- break;
669
- }
670
- case "toHaveRole": {
671
- const role = await locator.evaluate((el) => {
672
- return el.getAttribute("role") || el.tagName.toLowerCase();
673
- });
674
- const matches = role === String(expected);
675
- if (negated) {
676
- if (matches)
677
- throw new Error(`Expected role to not be "${expected}", but it was`);
678
- } else {
679
- if (!matches)
680
- throw new Error(`Expected role to be "${expected}", but got "${role}"`);
681
- }
682
- break;
683
- }
684
- default:
685
- throw new Error(`Unknown matcher: ${matcher}`);
686
- }
687
- }
688
- async function executePageExpectAssertion(page, matcher, expected, negated, timeout) {
689
- let expectedValue = expected;
690
- if (expected && typeof expected === "object" && expected.$regex) {
691
- expectedValue = new RegExp(expected.$regex, expected.$flags);
692
- }
693
- switch (matcher) {
694
- case "toHaveURL": {
695
- const expectedUrl = expectedValue;
696
- const startTime = Date.now();
697
- let lastUrl = "";
698
- while (Date.now() - startTime < timeout) {
699
- lastUrl = page.url();
700
- const matches = expectedUrl instanceof RegExp ? expectedUrl.test(lastUrl) : lastUrl === expectedUrl;
701
- if (negated ? !matches : matches)
702
- return;
703
- await new Promise((r) => setTimeout(r, 100));
704
- }
705
- if (negated) {
706
- throw new Error(`Expected URL to not match "${expectedUrl}", but got "${lastUrl}"`);
707
- } else {
708
- throw new Error(`Expected URL to be "${expectedUrl}", but got "${lastUrl}"`);
709
- }
710
- }
711
- case "toHaveTitle": {
712
- const expectedTitle = expectedValue;
713
- const startTime = Date.now();
714
- let lastTitle = "";
715
- while (Date.now() - startTime < timeout) {
716
- lastTitle = await page.title();
717
- const matches = expectedTitle instanceof RegExp ? expectedTitle.test(lastTitle) : lastTitle === expectedTitle;
718
- if (negated ? !matches : matches)
719
- return;
720
- await new Promise((r) => setTimeout(r, 100));
721
- }
722
- if (negated) {
723
- throw new Error(`Expected title to not match "${expectedTitle}", but got "${lastTitle}"`);
724
- } else {
725
- throw new Error(`Expected title to be "${expectedTitle}", but got "${lastTitle}"`);
726
- }
727
- }
728
- default:
729
- throw new Error(`Unknown page matcher: ${matcher}`);
730
- }
731
- }
732
- function createPlaywrightHandler(page, options) {
733
- const timeout = options?.timeout ?? 30000;
734
- const fileIO = {
735
- readFile: options?.readFile,
736
- writeFile: options?.writeFile
737
- };
738
- const registry = {
739
- pages: new Map([["page_0", page]]),
740
- contexts: new Map([["ctx_0", page.context()]]),
741
- nextPageId: 1,
742
- nextContextId: 1
743
- };
6
+ import {
7
+ createPlaywrightHandler,
8
+ defaultPlaywrightHandler,
9
+ getDefaultPlaywrightHandlerMetadata
10
+ } from "./handler.mjs";
11
+ import {
12
+ createPlaywrightHandler as createPlaywrightHandler2,
13
+ getDefaultPlaywrightHandlerMetadata as getDefaultPlaywrightHandlerMetadata2
14
+ } from "./handler.mjs";
15
+ function wrapHandlerWithPredicateSupport(handler, evaluatePredicate, defaultTimeout) {
744
16
  return async (op) => {
745
- try {
746
- switch (op.type) {
747
- case "newContext": {
748
- if (!options?.createContext) {
749
- return { ok: false, error: { name: "Error", message: "createContext callback not provided. Configure createContext in playwright options to enable browser.newContext()." } };
750
- }
751
- const [contextOptions] = op.args;
752
- const newContext = await options.createContext(contextOptions);
753
- const contextId2 = `ctx_${registry.nextContextId++}`;
754
- registry.contexts.set(contextId2, newContext);
755
- return { ok: true, value: { contextId: contextId2 } };
756
- }
757
- case "newPage": {
758
- if (!options?.createPage) {
759
- return { ok: false, error: { name: "Error", message: "createPage callback not provided. Configure createPage in playwright options to enable context.newPage()." } };
760
- }
761
- const contextId2 = op.contextId ?? "ctx_0";
762
- const targetContext2 = registry.contexts.get(contextId2);
763
- if (!targetContext2) {
764
- return { ok: false, error: { name: "Error", message: `Context ${contextId2} not found` } };
765
- }
766
- const newPage = await options.createPage(targetContext2);
767
- const pageId2 = `page_${registry.nextPageId++}`;
768
- registry.pages.set(pageId2, newPage);
769
- return { ok: true, value: { pageId: pageId2 } };
770
- }
771
- case "closeContext": {
772
- const contextId2 = op.contextId ?? "ctx_0";
773
- const context = registry.contexts.get(contextId2);
774
- if (!context) {
775
- return { ok: false, error: { name: "Error", message: `Context ${contextId2} not found` } };
776
- }
777
- await context.close();
778
- registry.contexts.delete(contextId2);
779
- for (const [pid, p] of registry.pages) {
780
- if (p.context() === context) {
781
- registry.pages.delete(pid);
17
+ switch (op.type) {
18
+ case "waitForURLPredicate": {
19
+ const [predicateId, customTimeout, waitUntil] = op.args;
20
+ const effectiveTimeout = customTimeout ?? defaultTimeout;
21
+ const startTime = Date.now();
22
+ const pollInterval = 100;
23
+ while (true) {
24
+ const urlResult = await handler({ type: "url", args: [], pageId: op.pageId, contextId: op.contextId });
25
+ if (urlResult.ok) {
26
+ try {
27
+ if (evaluatePredicate(predicateId, urlResult.value)) {
28
+ return { ok: true };
29
+ }
30
+ } catch (e) {
31
+ const error = e;
32
+ return { ok: false, error: { name: error.name, message: error.message } };
782
33
  }
783
34
  }
784
- return { ok: true };
785
- }
786
- }
787
- const pageId = op.pageId ?? "page_0";
788
- const targetPage = registry.pages.get(pageId);
789
- if (!targetPage) {
790
- return { ok: false, error: { name: "Error", message: `Page ${pageId} not found` } };
791
- }
792
- const contextId = op.contextId ?? "ctx_0";
793
- const targetContext = registry.contexts.get(contextId);
794
- switch (op.type) {
795
- case "goto": {
796
- const [url, waitUntil] = op.args;
797
- await targetPage.goto(url, {
798
- timeout,
799
- waitUntil: waitUntil ?? "load"
800
- });
801
- return { ok: true };
802
- }
803
- case "reload":
804
- await targetPage.reload({ timeout });
805
- return { ok: true };
806
- case "url":
807
- return { ok: true, value: targetPage.url() };
808
- case "title":
809
- return { ok: true, value: await targetPage.title() };
810
- case "content":
811
- return { ok: true, value: await targetPage.content() };
812
- case "waitForSelector": {
813
- const [selector, optionsJson] = op.args;
814
- const opts = optionsJson ? JSON.parse(optionsJson) : {};
815
- await targetPage.waitForSelector(selector, { timeout, ...opts });
816
- return { ok: true };
817
- }
818
- case "waitForTimeout": {
819
- const [ms] = op.args;
820
- await targetPage.waitForTimeout(ms);
821
- return { ok: true };
822
- }
823
- case "waitForLoadState": {
824
- const [state] = op.args;
825
- await targetPage.waitForLoadState(state ?? "load", { timeout });
826
- return { ok: true };
827
- }
828
- case "evaluate": {
829
- const [script, arg] = op.args;
830
- if (op.args.length > 1) {
831
- const fn = new Function("return (" + script + ")")();
832
- const result2 = await targetPage.evaluate(fn, arg);
833
- return { ok: true, value: result2 };
35
+ if (effectiveTimeout > 0 && Date.now() - startTime >= effectiveTimeout) {
36
+ return { ok: false, error: { name: "Error", message: `Timeout ${effectiveTimeout}ms exceeded waiting for URL` } };
834
37
  }
835
- const result = await targetPage.evaluate(script);
836
- return { ok: true, value: result };
837
- }
838
- case "locatorAction": {
839
- const [selectorType, selectorValue, roleOptions, action, actionArg] = op.args;
840
- const locator = getLocator(targetPage, selectorType, selectorValue, roleOptions);
841
- const result = await executeLocatorAction(locator, action, actionArg, timeout, fileIO);
842
- return { ok: true, value: result };
38
+ await new Promise((r) => setTimeout(r, pollInterval));
843
39
  }
844
- case "expectLocator": {
845
- const [selectorType, selectorValue, roleOptions, matcher, expected, negated, customTimeout] = op.args;
846
- const locator = getLocator(targetPage, selectorType, selectorValue, roleOptions);
847
- const effectiveTimeout = customTimeout ?? timeout;
848
- await executeExpectAssertion(locator, matcher, expected, negated ?? false, effectiveTimeout);
849
- return { ok: true };
850
- }
851
- case "expectPage": {
852
- const [matcher, expected, negated, customTimeout] = op.args;
853
- const effectiveTimeout = customTimeout ?? timeout;
854
- await executePageExpectAssertion(targetPage, matcher, expected, negated ?? false, effectiveTimeout);
855
- return { ok: true };
856
- }
857
- case "request": {
858
- const [url, method, data, headers] = op.args;
859
- const requestOptions = {
860
- timeout
861
- };
862
- if (headers) {
863
- requestOptions.headers = headers;
864
- }
865
- if (data !== undefined && data !== null) {
866
- requestOptions.data = data;
867
- }
868
- const response = await targetPage.request.fetch(url, {
869
- method,
870
- ...requestOptions
40
+ }
41
+ case "waitForResponsePredicateFinish": {
42
+ const [initialListenerId, predicateId, customTimeout] = op.args;
43
+ const effectiveTimeout = customTimeout ?? defaultTimeout;
44
+ const broadMatcher = { type: "regex", value: { $regex: ".*", $flags: "" } };
45
+ const startTime = Date.now();
46
+ let currentListenerId = initialListenerId;
47
+ while (true) {
48
+ const finishResult = await handler({
49
+ type: "waitForResponseFinish",
50
+ args: [currentListenerId],
51
+ pageId: op.pageId,
52
+ contextId: op.contextId
871
53
  });
872
- const text = await response.text();
873
- let json = null;
54
+ if (!finishResult.ok)
55
+ return finishResult;
56
+ const responseData = finishResult.value;
874
57
  try {
875
- json = JSON.parse(text);
876
- } catch {}
877
- return {
878
- ok: true,
879
- value: {
880
- status: response.status(),
881
- ok: response.ok(),
882
- headers: response.headers(),
883
- text,
884
- json,
885
- body: null
58
+ const serialized = {
59
+ method: "",
60
+ headers: Object.entries(responseData.headers || {}),
61
+ url: responseData.url,
62
+ status: responseData.status,
63
+ statusText: responseData.statusText,
64
+ body: responseData.text || ""
65
+ };
66
+ if (evaluatePredicate(predicateId, serialized)) {
67
+ return finishResult;
886
68
  }
887
- };
888
- }
889
- case "goBack": {
890
- const [waitUntil] = op.args;
891
- await targetPage.goBack({
892
- timeout,
893
- waitUntil: waitUntil ?? "load"
894
- });
895
- return { ok: true };
896
- }
897
- case "goForward": {
898
- const [waitUntil] = op.args;
899
- await targetPage.goForward({
900
- timeout,
901
- waitUntil: waitUntil ?? "load"
902
- });
903
- return { ok: true };
904
- }
905
- case "waitForURL": {
906
- const [urlArg, customTimeout, waitUntil] = op.args;
907
- const url = urlArg && typeof urlArg === "object" && "$regex" in urlArg ? new RegExp(urlArg.$regex, urlArg.$flags) : urlArg;
908
- await targetPage.waitForURL(url, {
909
- timeout: customTimeout ?? timeout,
910
- waitUntil: waitUntil ?? undefined
69
+ } catch (e) {
70
+ const error = e;
71
+ return { ok: false, error: { name: error.name, message: error.message } };
72
+ }
73
+ if (effectiveTimeout > 0 && Date.now() - startTime >= effectiveTimeout) {
74
+ return { ok: false, error: { name: "Error", message: `Timeout ${effectiveTimeout}ms exceeded waiting for response` } };
75
+ }
76
+ const remainingTimeout = effectiveTimeout > 0 ? Math.max(1, effectiveTimeout - (Date.now() - startTime)) : effectiveTimeout;
77
+ const nextStartResult = await handler({
78
+ type: "waitForResponseStart",
79
+ args: [broadMatcher, remainingTimeout],
80
+ pageId: op.pageId,
81
+ contextId: op.contextId
911
82
  });
912
- return { ok: true };
913
- }
914
- case "clearCookies": {
915
- const ctx = targetContext ?? targetPage.context();
916
- await ctx.clearCookies();
917
- return { ok: true };
83
+ if (!nextStartResult.ok)
84
+ return nextStartResult;
85
+ currentListenerId = nextStartResult.value.listenerId;
918
86
  }
919
- case "screenshot": {
920
- const [screenshotOptions] = op.args;
921
- const buffer = await targetPage.screenshot({
922
- type: screenshotOptions?.type,
923
- quality: screenshotOptions?.quality,
924
- fullPage: screenshotOptions?.fullPage,
925
- clip: screenshotOptions?.clip
87
+ }
88
+ case "waitForRequestPredicateFinish": {
89
+ const [initialListenerId, predicateId, customTimeout] = op.args;
90
+ const effectiveTimeout = customTimeout ?? defaultTimeout;
91
+ const broadMatcher = { type: "regex", value: { $regex: ".*", $flags: "" } };
92
+ const startTime = Date.now();
93
+ let currentListenerId = initialListenerId;
94
+ while (true) {
95
+ const finishResult = await handler({
96
+ type: "waitForRequestFinish",
97
+ args: [currentListenerId],
98
+ pageId: op.pageId,
99
+ contextId: op.contextId
926
100
  });
927
- if (screenshotOptions?.path) {
928
- if (!fileIO.writeFile) {
929
- throw new Error("screenshot() with path option requires a writeFile callback to be provided. " + "Either provide a writeFile callback in defaultPlaywrightHandler options, or omit the path option " + "and handle the returned base64 data yourself.");
101
+ if (!finishResult.ok)
102
+ return finishResult;
103
+ const requestData = finishResult.value;
104
+ try {
105
+ const serialized = {
106
+ method: requestData.method,
107
+ headers: Object.entries(requestData.headers || {}),
108
+ url: requestData.url,
109
+ body: requestData.postData || ""
110
+ };
111
+ if (evaluatePredicate(predicateId, serialized)) {
112
+ return finishResult;
930
113
  }
931
- await fileIO.writeFile(screenshotOptions.path, buffer);
114
+ } catch (e) {
115
+ const error = e;
116
+ return { ok: false, error: { name: error.name, message: error.message } };
932
117
  }
933
- return { ok: true, value: buffer.toString("base64") };
934
- }
935
- case "setViewportSize": {
936
- const [size] = op.args;
937
- await targetPage.setViewportSize(size);
938
- return { ok: true };
939
- }
940
- case "viewportSize": {
941
- return { ok: true, value: targetPage.viewportSize() };
942
- }
943
- case "keyboardType": {
944
- const [text, typeOptions] = op.args;
945
- await targetPage.keyboard.type(text, typeOptions);
946
- return { ok: true };
947
- }
948
- case "keyboardPress": {
949
- const [key, pressOptions] = op.args;
950
- await targetPage.keyboard.press(key, pressOptions);
951
- return { ok: true };
952
- }
953
- case "keyboardDown": {
954
- const [key] = op.args;
955
- await targetPage.keyboard.down(key);
956
- return { ok: true };
957
- }
958
- case "keyboardUp": {
959
- const [key] = op.args;
960
- await targetPage.keyboard.up(key);
961
- return { ok: true };
962
- }
963
- case "keyboardInsertText": {
964
- const [text] = op.args;
965
- await targetPage.keyboard.insertText(text);
966
- return { ok: true };
967
- }
968
- case "mouseMove": {
969
- const [x, y, moveOptions] = op.args;
970
- await targetPage.mouse.move(x, y, moveOptions);
971
- return { ok: true };
972
- }
973
- case "mouseClick": {
974
- const [x, y, clickOptions] = op.args;
975
- await targetPage.mouse.click(x, y, clickOptions);
976
- return { ok: true };
977
- }
978
- case "mouseDown": {
979
- const [downOptions] = op.args;
980
- await targetPage.mouse.down(downOptions);
981
- return { ok: true };
982
- }
983
- case "mouseUp": {
984
- const [upOptions] = op.args;
985
- await targetPage.mouse.up(upOptions);
986
- return { ok: true };
987
- }
988
- case "mouseWheel": {
989
- const [deltaX, deltaY] = op.args;
990
- await targetPage.mouse.wheel(deltaX, deltaY);
991
- return { ok: true };
992
- }
993
- case "frames": {
994
- const frames = targetPage.frames();
995
- return { ok: true, value: frames.map((f) => ({ name: f.name(), url: f.url() })) };
996
- }
997
- case "mainFrame": {
998
- const mainFrame = targetPage.mainFrame();
999
- return { ok: true, value: { name: mainFrame.name(), url: mainFrame.url() } };
1000
- }
1001
- case "bringToFront": {
1002
- await targetPage.bringToFront();
1003
- return { ok: true };
1004
- }
1005
- case "close": {
1006
- await targetPage.close();
1007
- registry.pages.delete(pageId);
1008
- return { ok: true };
1009
- }
1010
- case "isClosed": {
1011
- return { ok: true, value: targetPage.isClosed() };
1012
- }
1013
- case "pdf": {
1014
- const [pdfOptions] = op.args;
1015
- const { path: pdfPath, ...restPdfOptions } = pdfOptions ?? {};
1016
- const buffer = await targetPage.pdf(restPdfOptions);
1017
- if (pdfPath) {
1018
- if (!fileIO.writeFile) {
1019
- throw new Error("pdf() with path option requires a writeFile callback to be provided. " + "Either provide a writeFile callback in defaultPlaywrightHandler options, or omit the path option " + "and handle the returned base64 data yourself.");
1020
- }
1021
- await fileIO.writeFile(pdfPath, buffer);
118
+ if (effectiveTimeout > 0 && Date.now() - startTime >= effectiveTimeout) {
119
+ return { ok: false, error: { name: "Error", message: `Timeout ${effectiveTimeout}ms exceeded waiting for request` } };
1022
120
  }
1023
- return { ok: true, value: buffer.toString("base64") };
1024
- }
1025
- case "emulateMedia": {
1026
- const [mediaOptions] = op.args;
1027
- await targetPage.emulateMedia(mediaOptions);
1028
- return { ok: true };
1029
- }
1030
- case "addCookies": {
1031
- const [cookies] = op.args;
1032
- const ctx = targetContext ?? targetPage.context();
1033
- await ctx.addCookies(cookies);
1034
- return { ok: true };
1035
- }
1036
- case "cookies": {
1037
- const [urls] = op.args;
1038
- const ctx = targetContext ?? targetPage.context();
1039
- const cookies = await ctx.cookies(urls);
1040
- return { ok: true, value: cookies };
1041
- }
1042
- case "setExtraHTTPHeaders": {
1043
- const [headers] = op.args;
1044
- await targetPage.setExtraHTTPHeaders(headers);
1045
- return { ok: true };
1046
- }
1047
- case "pause": {
1048
- await targetPage.pause();
1049
- return { ok: true };
121
+ const remainingTimeout = effectiveTimeout > 0 ? Math.max(1, effectiveTimeout - (Date.now() - startTime)) : effectiveTimeout;
122
+ const nextStartResult = await handler({
123
+ type: "waitForRequestStart",
124
+ args: [broadMatcher, remainingTimeout],
125
+ pageId: op.pageId,
126
+ contextId: op.contextId
127
+ });
128
+ if (!nextStartResult.ok)
129
+ return nextStartResult;
130
+ currentListenerId = nextStartResult.value.listenerId;
1050
131
  }
1051
- default:
1052
- return { ok: false, error: { name: "Error", message: `Unknown operation: ${op.type}` } };
1053
132
  }
1054
- } catch (err) {
1055
- const error = err;
1056
- return { ok: false, error: { name: error.name, message: error.message } };
133
+ default:
134
+ return handler(op);
1057
135
  }
1058
136
  };
1059
137
  }
1060
- function defaultPlaywrightHandler(page, options) {
1061
- const handler = createPlaywrightHandler(page, options);
1062
- handler[DEFAULT_PLAYWRIGHT_HANDLER_META] = { page, options };
1063
- return handler;
1064
- }
1065
- function getDefaultPlaywrightHandlerMetadata(handler) {
1066
- return handler[DEFAULT_PLAYWRIGHT_HANDLER_META];
1067
- }
1068
138
  async function setupPlaywright(context, options) {
1069
139
  const timeout = options.timeout ?? 30000;
1070
140
  const explicitPage = "page" in options ? options.page : undefined;
1071
141
  const handler = "handler" in options ? options.handler : undefined;
1072
- const handlerMetadata = handler ? getDefaultPlaywrightHandlerMetadata(handler) : undefined;
142
+ const handlerMetadata = handler ? getDefaultPlaywrightHandlerMetadata2(handler) : undefined;
1073
143
  const page = explicitPage ?? handlerMetadata?.page;
1074
144
  const createPage = "createPage" in options ? options.createPage : undefined;
1075
145
  const createContext = "createContext" in options ? options.createContext : undefined;
1076
- const effectiveHandler = handler ?? (page ? createPlaywrightHandler(page, {
1077
- timeout,
1078
- createPage,
1079
- createContext
1080
- }) : undefined);
1081
- if (!effectiveHandler) {
146
+ const readFile = "readFile" in options ? options.readFile : undefined;
147
+ const writeFile = "writeFile" in options ? options.writeFile : undefined;
148
+ if (!handler && !page) {
1082
149
  throw new Error("Either page or handler must be provided to setupPlaywright");
1083
150
  }
1084
151
  const browserConsoleLogs = [];
@@ -1157,14 +224,9 @@ async function setupPlaywright(context, options) {
1157
224
  page.on("response", responseHandler);
1158
225
  page.on("console", consoleHandler);
1159
226
  }
1160
- global.setSync("__Playwright_handler_ref", new ivm.Reference(async (opJson) => {
1161
- const op = JSON.parse(opJson);
1162
- const result = await effectiveHandler(op);
1163
- return JSON.stringify(result);
1164
- }));
1165
227
  context.evalSync(`
1166
228
  (function() {
1167
- globalThis.__pw_invoke = async function(type, args, options) {
229
+ globalThis.__pw_invoke_sync = function(type, args, options) {
1168
230
  const op = JSON.stringify({ type, args, pageId: options?.pageId, contextId: options?.contextId });
1169
231
  const resultJson = __Playwright_handler_ref.applySyncPromise(undefined, [op]);
1170
232
  const result = JSON.parse(resultJson);
@@ -1176,13 +238,68 @@ async function setupPlaywright(context, options) {
1176
238
  throw error;
1177
239
  }
1178
240
  };
241
+ globalThis.__pw_invoke = async function(type, args, options) {
242
+ return globalThis.__pw_invoke_sync(type, args, options);
243
+ };
1179
244
  })();
1180
245
  `);
1181
246
  context.evalSync(`
247
+ (function() {
248
+ const __pw_predicates = new Map();
249
+ let __pw_next_id = 0;
250
+ globalThis.__pw_register_predicate = function(fn) {
251
+ const id = __pw_next_id++;
252
+ __pw_predicates.set(id, fn);
253
+ return id;
254
+ };
255
+ globalThis.__pw_unregister_predicate = function(id) {
256
+ __pw_predicates.delete(id);
257
+ };
258
+ globalThis.__pw_evaluate_predicate = function(id, data) {
259
+ const fn = __pw_predicates.get(id);
260
+ if (!fn) throw new Error('Predicate not found: ' + id);
261
+ const result = fn(data);
262
+ if (result && typeof result === 'object' && typeof result.then === 'function') {
263
+ throw new Error('Async predicates are not supported. Use a synchronous predicate function.');
264
+ }
265
+ return !!result;
266
+ };
267
+ })();
268
+ `);
269
+ const evaluatePredicateRef = context.global.getSync("__pw_evaluate_predicate", { reference: true });
270
+ const evaluatePredicateFn = (predicateId, data) => {
271
+ return evaluatePredicateRef.applySync(undefined, [new ivm.ExternalCopy(predicateId).copyInto(), new ivm.ExternalCopy(data).copyInto()]);
272
+ };
273
+ let effectiveHandler;
274
+ if (handler && handlerMetadata?.page) {
275
+ effectiveHandler = createPlaywrightHandler2(handlerMetadata.page, {
276
+ ...handlerMetadata.options,
277
+ evaluatePredicate: evaluatePredicateFn
278
+ });
279
+ } else if (handler) {
280
+ effectiveHandler = wrapHandlerWithPredicateSupport(handler, evaluatePredicateFn, timeout);
281
+ } else if (page) {
282
+ effectiveHandler = createPlaywrightHandler2(page, {
283
+ timeout,
284
+ readFile,
285
+ writeFile,
286
+ createPage,
287
+ createContext,
288
+ evaluatePredicate: evaluatePredicateFn
289
+ });
290
+ } else {
291
+ throw new Error("Either page or handler must be provided to setupPlaywright");
292
+ }
293
+ global.setSync("__Playwright_handler_ref", new ivm.Reference(async (opJson) => {
294
+ const op = JSON.parse(opJson);
295
+ const result = await effectiveHandler(op);
296
+ return JSON.stringify(result);
297
+ }));
298
+ context.evalSync(`
1182
299
  (function() {
1183
300
  // IsolatePage class - represents a page with a specific pageId
1184
301
  class IsolatePage {
1185
- #pageId; #contextId; #currentUrl = '';
302
+ #pageId; #contextId;
1186
303
  constructor(pageId, contextId) {
1187
304
  this.#pageId = pageId;
1188
305
  this.#contextId = contextId;
@@ -1193,15 +310,11 @@ async function setupPlaywright(context, options) {
1193
310
 
1194
311
  async goto(url, options) {
1195
312
  await __pw_invoke("goto", [url, options?.waitUntil || null], { pageId: this.#pageId });
1196
- const resolvedUrl = await __pw_invoke("url", [], { pageId: this.#pageId });
1197
- this.#currentUrl = resolvedUrl || url;
1198
313
  }
1199
314
  async reload() {
1200
315
  await __pw_invoke("reload", [], { pageId: this.#pageId });
1201
- const resolvedUrl = await __pw_invoke("url", [], { pageId: this.#pageId });
1202
- if (resolvedUrl) this.#currentUrl = resolvedUrl;
1203
316
  }
1204
- url() { return this.#currentUrl; }
317
+ url() { return __pw_invoke_sync("url", [], { pageId: this.#pageId }); }
1205
318
  async title() { return __pw_invoke("title", [], { pageId: this.#pageId }); }
1206
319
  async content() { return __pw_invoke("content", [], { pageId: this.#pageId }); }
1207
320
  async waitForSelector(selector, options) {
@@ -1251,21 +364,139 @@ async function setupPlaywright(context, options) {
1251
364
  }
1252
365
  async goBack(options) {
1253
366
  await __pw_invoke("goBack", [options?.waitUntil || null], { pageId: this.#pageId });
1254
- const resolvedUrl = await __pw_invoke("url", [], { pageId: this.#pageId });
1255
- if (resolvedUrl) this.#currentUrl = resolvedUrl;
1256
367
  }
1257
368
  async goForward(options) {
1258
369
  await __pw_invoke("goForward", [options?.waitUntil || null], { pageId: this.#pageId });
1259
- const resolvedUrl = await __pw_invoke("url", [], { pageId: this.#pageId });
1260
- if (resolvedUrl) this.#currentUrl = resolvedUrl;
1261
370
  }
1262
371
  async waitForURL(url, options) {
1263
- let serializedUrl = url;
1264
- if (url && typeof url === 'object' && typeof url.source === 'string' && typeof url.flags === 'string') {
1265
- serializedUrl = { $regex: url.source, $flags: url.flags };
372
+ if (typeof url === 'function') {
373
+ const predicateId = __pw_register_predicate(url);
374
+ try {
375
+ await __pw_invoke("waitForURLPredicate", [predicateId, options?.timeout || null, options?.waitUntil || null], { pageId: this.#pageId });
376
+ } finally {
377
+ __pw_unregister_predicate(predicateId);
378
+ }
379
+ return;
380
+ }
381
+ let serializedUrl;
382
+ if (typeof url === 'string') {
383
+ serializedUrl = { type: 'string', value: url };
384
+ } else if (url && typeof url === 'object' && typeof url.source === 'string' && typeof url.flags === 'string') {
385
+ serializedUrl = { type: 'regex', value: { $regex: url.source, $flags: url.flags } };
386
+ } else {
387
+ serializedUrl = url;
1266
388
  }
1267
389
  return __pw_invoke("waitForURL", [serializedUrl, options?.timeout || null, options?.waitUntil || null], { pageId: this.#pageId });
1268
390
  }
391
+ waitForRequest(urlOrPredicate, options) {
392
+ if (typeof urlOrPredicate === 'function') {
393
+ const userPredicate = urlOrPredicate;
394
+ const wrappedPredicate = (data) => {
395
+ const requestLike = {
396
+ url: () => data.url,
397
+ method: () => data.method,
398
+ headers: () => Object.fromEntries(data.headers),
399
+ headersArray: () => data.headers.map(h => ({ name: h[0], value: h[1] })),
400
+ postData: () => data.body || null,
401
+ };
402
+ return userPredicate(requestLike);
403
+ };
404
+ const predicateId = __pw_register_predicate(wrappedPredicate);
405
+ const pageId = this.#pageId;
406
+ // Start listening immediately (before the user triggers the request)
407
+ const broadMatcher = { type: 'regex', value: { $regex: '.*', $flags: '' } };
408
+ const startResult = __pw_invoke_sync("waitForRequestStart", [broadMatcher, options?.timeout || null], { pageId });
409
+ const listenerId = startResult.listenerId;
410
+ return {
411
+ then(resolve, reject) {
412
+ try {
413
+ const r = __pw_invoke_sync("waitForRequestPredicateFinish", [listenerId, predicateId, options?.timeout || null], { pageId });
414
+ resolve({ url: () => r.url, method: () => r.method, headers: () => r.headers, postData: () => r.postData });
415
+ } catch(e) { reject(e); } finally { __pw_unregister_predicate(predicateId); }
416
+ }
417
+ };
418
+ }
419
+ let serializedMatcher;
420
+ if (typeof urlOrPredicate === 'string') {
421
+ serializedMatcher = { type: 'string', value: urlOrPredicate };
422
+ } else if (urlOrPredicate && typeof urlOrPredicate === 'object'
423
+ && typeof urlOrPredicate.source === 'string'
424
+ && typeof urlOrPredicate.flags === 'string') {
425
+ serializedMatcher = { type: 'regex', value: { $regex: urlOrPredicate.source, $flags: urlOrPredicate.flags } };
426
+ } else {
427
+ throw new Error('waitForRequest requires a URL string, RegExp, or predicate function');
428
+ }
429
+ const startResult = __pw_invoke_sync("waitForRequestStart", [serializedMatcher, options?.timeout || null], { pageId: this.#pageId });
430
+ const listenerId = startResult.listenerId;
431
+ const pageId = this.#pageId;
432
+ return {
433
+ then(resolve, reject) {
434
+ try {
435
+ const r = __pw_invoke_sync("waitForRequestFinish", [listenerId], { pageId });
436
+ resolve({ url: () => r.url, method: () => r.method, headers: () => r.headers, postData: () => r.postData });
437
+ } catch(e) { reject(e); }
438
+ }
439
+ };
440
+ }
441
+ waitForResponse(urlOrPredicate, options) {
442
+ if (typeof urlOrPredicate === 'function') {
443
+ const userPredicate = urlOrPredicate;
444
+ const wrappedPredicate = (data) => {
445
+ const responseLike = {
446
+ url: () => data.url,
447
+ status: () => data.status,
448
+ statusText: () => data.statusText,
449
+ headers: () => Object.fromEntries(data.headers),
450
+ headersArray: () => data.headers.map(h => ({ name: h[0], value: h[1] })),
451
+ ok: () => data.status >= 200 && data.status < 300,
452
+ };
453
+ return userPredicate(responseLike);
454
+ };
455
+ const predicateId = __pw_register_predicate(wrappedPredicate);
456
+ const pageId = this.#pageId;
457
+ // Start listening immediately (before the user triggers the response)
458
+ const broadMatcher = { type: 'regex', value: { $regex: '.*', $flags: '' } };
459
+ const startResult = __pw_invoke_sync("waitForResponseStart", [broadMatcher, options?.timeout || null], { pageId });
460
+ const listenerId = startResult.listenerId;
461
+ return {
462
+ then(resolve, reject) {
463
+ try {
464
+ const r = __pw_invoke_sync("waitForResponsePredicateFinish", [listenerId, predicateId, options?.timeout || null], { pageId });
465
+ resolve({
466
+ url: () => r.url, status: () => r.status, statusText: () => r.statusText,
467
+ headers: () => r.headers, headersArray: () => r.headersArray,
468
+ ok: () => r.ok, json: async () => r.json, text: async () => r.text, body: async () => r.body,
469
+ });
470
+ } catch(e) { reject(e); } finally { __pw_unregister_predicate(predicateId); }
471
+ }
472
+ };
473
+ }
474
+ let serializedMatcher;
475
+ if (typeof urlOrPredicate === 'string') {
476
+ serializedMatcher = { type: 'string', value: urlOrPredicate };
477
+ } else if (urlOrPredicate && typeof urlOrPredicate === 'object'
478
+ && typeof urlOrPredicate.source === 'string'
479
+ && typeof urlOrPredicate.flags === 'string') {
480
+ serializedMatcher = { type: 'regex', value: { $regex: urlOrPredicate.source, $flags: urlOrPredicate.flags } };
481
+ } else {
482
+ throw new Error('waitForResponse requires a URL string, RegExp, or predicate function');
483
+ }
484
+ const startResult = __pw_invoke_sync("waitForResponseStart", [serializedMatcher, options?.timeout || null], { pageId: this.#pageId });
485
+ const listenerId = startResult.listenerId;
486
+ const pageId = this.#pageId;
487
+ return {
488
+ then(resolve, reject) {
489
+ try {
490
+ const r = __pw_invoke_sync("waitForResponseFinish", [listenerId], { pageId });
491
+ resolve({
492
+ url: () => r.url, status: () => r.status, statusText: () => r.statusText,
493
+ headers: () => r.headers, headersArray: () => r.headersArray,
494
+ ok: () => r.ok, json: async () => r.json, text: async () => r.text, body: async () => r.body,
495
+ });
496
+ } catch(e) { reject(e); }
497
+ }
498
+ };
499
+ }
1269
500
  context() {
1270
501
  const contextId = this.#contextId;
1271
502
  return new IsolateContext(contextId);
@@ -1381,6 +612,86 @@ async function setupPlaywright(context, options) {
1381
612
  return JSON.stringify(serialized);
1382
613
  }
1383
614
 
615
+ const INPUT_FILES_VALIDATION_ERROR =
616
+ "setInputFiles() expects a file path string, an array of file path strings, " +
617
+ "a single inline file object ({ name, mimeType, buffer }), or an array of inline file objects.";
618
+
619
+ function isInlineFileObject(value) {
620
+ return !!value
621
+ && typeof value === 'object'
622
+ && typeof value.name === 'string'
623
+ && typeof value.mimeType === 'string'
624
+ && 'buffer' in value;
625
+ }
626
+
627
+ function encodeInlineFileBuffer(buffer) {
628
+ if (typeof buffer === 'string') {
629
+ return buffer;
630
+ }
631
+ let bytes;
632
+ if (buffer instanceof ArrayBuffer) {
633
+ bytes = new Uint8Array(buffer);
634
+ } else if (ArrayBuffer.isView(buffer)) {
635
+ bytes = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
636
+ } else {
637
+ throw new Error(
638
+ "setInputFiles() inline file buffer must be a base64 string, ArrayBuffer, or TypedArray."
639
+ );
640
+ }
641
+ let binary = '';
642
+ for (let i = 0; i < bytes.length; i++) {
643
+ binary += String.fromCharCode(bytes[i]);
644
+ }
645
+ return btoa(binary);
646
+ }
647
+
648
+ function serializeInlineFile(file) {
649
+ return {
650
+ name: file.name,
651
+ mimeType: file.mimeType,
652
+ buffer: encodeInlineFileBuffer(file.buffer),
653
+ };
654
+ }
655
+
656
+ function normalizeSetInputFilesArg(files) {
657
+ if (typeof files === 'string') {
658
+ return files;
659
+ }
660
+ if (isInlineFileObject(files)) {
661
+ return serializeInlineFile(files);
662
+ }
663
+ if (!Array.isArray(files)) {
664
+ throw new Error(INPUT_FILES_VALIDATION_ERROR);
665
+ }
666
+ if (files.length === 0) {
667
+ return [];
668
+ }
669
+
670
+ let hasPaths = false;
671
+ let hasInline = false;
672
+ const inlineFiles = [];
673
+
674
+ for (const file of files) {
675
+ if (typeof file === 'string') {
676
+ hasPaths = true;
677
+ continue;
678
+ }
679
+ if (isInlineFileObject(file)) {
680
+ hasInline = true;
681
+ inlineFiles.push(serializeInlineFile(file));
682
+ continue;
683
+ }
684
+ throw new Error(INPUT_FILES_VALIDATION_ERROR);
685
+ }
686
+
687
+ if (hasPaths && hasInline) {
688
+ throw new Error(
689
+ "setInputFiles() does not support mixing file paths and inline file objects in the same array."
690
+ );
691
+ }
692
+ return hasInline ? inlineFiles : files;
693
+ }
694
+
1384
695
  class Locator {
1385
696
  #type; #value; #options; #pageId;
1386
697
  constructor(type, value, options, pageId) {
@@ -1479,15 +790,7 @@ async function setupPlaywright(context, options) {
1479
790
  return __pw_invoke("locatorAction", [...this._getInfo(), "boundingBox", null], { pageId: this.#pageId });
1480
791
  }
1481
792
  async setInputFiles(files) {
1482
- // Serialize files - if they have buffers, convert to base64
1483
- let serializedFiles = files;
1484
- if (Array.isArray(files) && files.length > 0 && typeof files[0] === 'object' && files[0].buffer) {
1485
- serializedFiles = files.map(f => ({
1486
- name: f.name,
1487
- mimeType: f.mimeType,
1488
- buffer: typeof f.buffer === 'string' ? f.buffer : btoa(String.fromCharCode(...new Uint8Array(f.buffer)))
1489
- }));
1490
- }
793
+ const serializedFiles = normalizeSetInputFilesArg(files);
1491
794
  return __pw_invoke("locatorAction", [...this._getInfo(), "setInputFiles", serializedFiles], { pageId: this.#pageId });
1492
795
  }
1493
796
  async screenshot(options) {
@@ -1857,4 +1160,4 @@ export {
1857
1160
  DEFAULT_PLAYWRIGHT_HANDLER_META
1858
1161
  };
1859
1162
 
1860
- //# debugId=AFE0563DA4EAC06264756E2164756E21
1163
+ //# debugId=917AA0A37B759B7B64756E2164756E21