@dream_engine/browser 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/LICENSE +21 -0
  2. package/dist/.tsbuildinfo +1 -0
  3. package/dist/adapter/playwright.d.ts +27 -0
  4. package/dist/adapter/playwright.d.ts.map +1 -0
  5. package/dist/adapter/playwright.js +1087 -0
  6. package/dist/adapter/playwright.js.map +1 -0
  7. package/dist/adapter/types.d.ts +833 -0
  8. package/dist/adapter/types.d.ts.map +1 -0
  9. package/dist/adapter/types.js +9 -0
  10. package/dist/adapter/types.js.map +1 -0
  11. package/dist/api-request.d.ts +93 -0
  12. package/dist/api-request.d.ts.map +1 -0
  13. package/dist/api-request.js +284 -0
  14. package/dist/api-request.js.map +1 -0
  15. package/dist/artifacts.d.ts +99 -0
  16. package/dist/artifacts.d.ts.map +1 -0
  17. package/dist/artifacts.js +211 -0
  18. package/dist/artifacts.js.map +1 -0
  19. package/dist/browser.d.ts +79 -0
  20. package/dist/browser.d.ts.map +1 -0
  21. package/dist/browser.js +186 -0
  22. package/dist/browser.js.map +1 -0
  23. package/dist/code-execution.d.ts +12 -0
  24. package/dist/code-execution.d.ts.map +1 -0
  25. package/dist/code-execution.js +15 -0
  26. package/dist/code-execution.js.map +1 -0
  27. package/dist/context.d.ts +174 -0
  28. package/dist/context.d.ts.map +1 -0
  29. package/dist/context.js +474 -0
  30. package/dist/context.js.map +1 -0
  31. package/dist/events.d.ts +66 -0
  32. package/dist/events.d.ts.map +1 -0
  33. package/dist/events.js +87 -0
  34. package/dist/events.js.map +1 -0
  35. package/dist/index.d.ts +24 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +23 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/locator.d.ts +208 -0
  40. package/dist/locator.d.ts.map +1 -0
  41. package/dist/locator.js +402 -0
  42. package/dist/locator.js.map +1 -0
  43. package/dist/login.d.ts +76 -0
  44. package/dist/login.d.ts.map +1 -0
  45. package/dist/login.js +176 -0
  46. package/dist/login.js.map +1 -0
  47. package/dist/manager.d.ts +109 -0
  48. package/dist/manager.d.ts.map +1 -0
  49. package/dist/manager.js +320 -0
  50. package/dist/manager.js.map +1 -0
  51. package/dist/navigation.d.ts +74 -0
  52. package/dist/navigation.d.ts.map +1 -0
  53. package/dist/navigation.js +234 -0
  54. package/dist/navigation.js.map +1 -0
  55. package/dist/network.d.ts +260 -0
  56. package/dist/network.d.ts.map +1 -0
  57. package/dist/network.js +582 -0
  58. package/dist/network.js.map +1 -0
  59. package/dist/page.d.ts +512 -0
  60. package/dist/page.d.ts.map +1 -0
  61. package/dist/page.js +1493 -0
  62. package/dist/page.js.map +1 -0
  63. package/dist/selectors.d.ts +67 -0
  64. package/dist/selectors.d.ts.map +1 -0
  65. package/dist/selectors.js +137 -0
  66. package/dist/selectors.js.map +1 -0
  67. package/dist/sessions.d.ts +114 -0
  68. package/dist/sessions.d.ts.map +1 -0
  69. package/dist/sessions.js +285 -0
  70. package/dist/sessions.js.map +1 -0
  71. package/dist/smart/dom-scan.d.ts +104 -0
  72. package/dist/smart/dom-scan.d.ts.map +1 -0
  73. package/dist/smart/dom-scan.js +491 -0
  74. package/dist/smart/dom-scan.js.map +1 -0
  75. package/dist/smart/ranking.d.ts +63 -0
  76. package/dist/smart/ranking.d.ts.map +1 -0
  77. package/dist/smart/ranking.js +318 -0
  78. package/dist/smart/ranking.js.map +1 -0
  79. package/dist/smart/recovery.d.ts +106 -0
  80. package/dist/smart/recovery.d.ts.map +1 -0
  81. package/dist/smart/recovery.js +197 -0
  82. package/dist/smart/recovery.js.map +1 -0
  83. package/dist/smart/smart.d.ts +249 -0
  84. package/dist/smart/smart.d.ts.map +1 -0
  85. package/dist/smart/smart.js +840 -0
  86. package/dist/smart/smart.js.map +1 -0
  87. package/dist/trace-parser.d.ts +70 -0
  88. package/dist/trace-parser.d.ts.map +1 -0
  89. package/dist/trace-parser.js +203 -0
  90. package/dist/trace-parser.js.map +1 -0
  91. package/dist/types.d.ts +57 -0
  92. package/dist/types.d.ts.map +1 -0
  93. package/dist/types.js +2 -0
  94. package/dist/types.js.map +1 -0
  95. package/dist/visual.d.ts +185 -0
  96. package/dist/visual.d.ts.map +1 -0
  97. package/dist/visual.js +384 -0
  98. package/dist/visual.js.map +1 -0
  99. package/package.json +37 -3
  100. package/README.md +0 -3
@@ -0,0 +1,1087 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import { dirname, join } from 'node:path';
4
+ import { createId } from '@dream_engine/core';
5
+ import * as pw from 'playwright-core';
6
+ const requestIds = new WeakMap();
7
+ function requestId(req) {
8
+ let id = requestIds.get(req);
9
+ if (!id) {
10
+ id = createId('req', 5);
11
+ requestIds.set(req, id);
12
+ }
13
+ return id;
14
+ }
15
+ function toRequestInfo(req) {
16
+ let frameUrl = null;
17
+ try {
18
+ frameUrl = req.frame().url();
19
+ }
20
+ catch {
21
+ frameUrl = null; // service worker requests have no frame
22
+ }
23
+ return {
24
+ id: requestId(req),
25
+ url: req.url(),
26
+ method: req.method(),
27
+ resourceType: req.resourceType(),
28
+ headers: req.headers(),
29
+ isNavigation: req.isNavigationRequest(),
30
+ frameUrl,
31
+ redirectedFrom: req.redirectedFrom()?.url() ?? null,
32
+ postDataSize: req.postDataBuffer()?.byteLength ?? 0,
33
+ };
34
+ }
35
+ function toPwShot(options) {
36
+ if (!options)
37
+ return undefined;
38
+ const { mask, ...rest } = options;
39
+ // Output paths are written by BashirWeb after confinement, never by the engine directly.
40
+ delete rest.path;
41
+ if (!mask?.length)
42
+ return rest;
43
+ return {
44
+ ...rest,
45
+ mask: mask.map((m) => {
46
+ if (!(m instanceof PlaywrightLocator))
47
+ throw new TypeError('mask locators must come from the same adapter');
48
+ return m.raw;
49
+ }),
50
+ };
51
+ }
52
+ function postDataText(req) {
53
+ try {
54
+ return req.postData();
55
+ }
56
+ catch {
57
+ return null; // binary body
58
+ }
59
+ }
60
+ function toResponseInfo(res) {
61
+ if (!res)
62
+ return null;
63
+ const chain = [];
64
+ let r = res.request().redirectedFrom();
65
+ while (r) {
66
+ chain.unshift(r.url());
67
+ r = r.redirectedFrom();
68
+ }
69
+ return { url: res.url(), status: res.status(), statusText: res.statusText(), headers: res.headers(), redirectChain: chain };
70
+ }
71
+ class PlaywrightLocator {
72
+ loc;
73
+ selector;
74
+ constructor(loc, selector) {
75
+ this.loc = loc;
76
+ this.selector = selector;
77
+ }
78
+ count() {
79
+ return this.loc.count();
80
+ }
81
+ nth(index) {
82
+ return new PlaywrightLocator(this.loc.nth(index), `${this.selector} >> nth=${index}`);
83
+ }
84
+ click(options) {
85
+ return this.loc.click(options);
86
+ }
87
+ dblclick(options) {
88
+ return this.loc.dblclick(options);
89
+ }
90
+ hover(options) {
91
+ return this.loc.hover(options);
92
+ }
93
+ tap(options) {
94
+ return this.loc.tap(options);
95
+ }
96
+ focus(options) {
97
+ return this.loc.focus(options);
98
+ }
99
+ fill(value, options) {
100
+ return this.loc.fill(value, options);
101
+ }
102
+ type(text, options) {
103
+ return this.loc.pressSequentially(text, options);
104
+ }
105
+ press(key, options) {
106
+ return this.loc.press(key, options);
107
+ }
108
+ check(options) {
109
+ return this.loc.check(options);
110
+ }
111
+ uncheck(options) {
112
+ return this.loc.uncheck(options);
113
+ }
114
+ selectOption(values, options) {
115
+ return this.loc.selectOption(values, options);
116
+ }
117
+ setInputFiles(files, options) {
118
+ return this.loc.setInputFiles(files, options);
119
+ }
120
+ dragTo(target, options) {
121
+ if (!(target instanceof PlaywrightLocator))
122
+ throw new TypeError('dragTo target must come from the same adapter');
123
+ return this.loc.dragTo(target.loc, options);
124
+ }
125
+ scrollIntoView(options) {
126
+ return this.loc.scrollIntoViewIfNeeded(options);
127
+ }
128
+ boundingBox(options) {
129
+ return this.loc.boundingBox(options);
130
+ }
131
+ /** The underlying Playwright locator (adapter-internal). */
132
+ get raw() {
133
+ return this.loc;
134
+ }
135
+ screenshot(options) {
136
+ return this.loc.screenshot(toPwShot(options));
137
+ }
138
+ textContent(options) {
139
+ return this.loc.textContent(options);
140
+ }
141
+ innerText(options) {
142
+ return this.loc.innerText(options);
143
+ }
144
+ inputValue(options) {
145
+ return this.loc.inputValue(options);
146
+ }
147
+ getAttribute(name, options) {
148
+ return this.loc.getAttribute(name, options);
149
+ }
150
+ async state() {
151
+ const count = await this.loc.count();
152
+ if (count === 0)
153
+ return { attached: false, visible: false, enabled: false, editable: false, checked: null };
154
+ const first = this.loc.first();
155
+ const [visible, enabled, editable] = await Promise.all([first.isVisible(), first.isEnabled().catch(() => false), first.isEditable().catch(() => false)]);
156
+ const checked = await first.isChecked({ timeout: 500 }).catch(() => null);
157
+ return { attached: true, visible, enabled, editable, checked };
158
+ }
159
+ is(state, options) {
160
+ switch (state) {
161
+ case 'visible':
162
+ return this.loc.isVisible();
163
+ case 'hidden':
164
+ return this.loc.isHidden();
165
+ case 'enabled':
166
+ return this.loc.isEnabled(options);
167
+ case 'disabled':
168
+ return this.loc.isDisabled(options);
169
+ case 'editable':
170
+ return this.loc.isEditable(options);
171
+ case 'checked':
172
+ return this.loc.isChecked(options);
173
+ }
174
+ }
175
+ waitFor(options) {
176
+ return this.loc.waitFor(options);
177
+ }
178
+ evaluate(fn, arg) {
179
+ return this.loc.evaluate(portableFunction(fn, ['element', 'arg']), arg);
180
+ }
181
+ evaluateAll(fn, arg) {
182
+ return this.loc.evaluateAll(portableFunction(fn, ['elements', 'arg']), arg);
183
+ }
184
+ locator(selector) {
185
+ return new PlaywrightLocator(this.loc.locator(selector), `${this.selector} >> ${selector}`);
186
+ }
187
+ clear(options) {
188
+ return this.loc.clear(options);
189
+ }
190
+ pressSequentially(text, options) {
191
+ return this.loc.pressSequentially(text, options);
192
+ }
193
+ selectText(options) {
194
+ return this.loc.selectText(options);
195
+ }
196
+ setChecked(checked, options) {
197
+ return this.loc.setChecked(checked, options);
198
+ }
199
+ blur(options) {
200
+ return this.loc.blur(options);
201
+ }
202
+ dispatchEvent(type, eventInit, options) {
203
+ return this.loc.dispatchEvent(type, eventInit, options);
204
+ }
205
+ async highlight() {
206
+ await this.loc.highlight();
207
+ }
208
+ innerHTML(options) {
209
+ return this.loc.innerHTML(options);
210
+ }
211
+ allInnerTexts() {
212
+ return this.loc.allInnerTexts();
213
+ }
214
+ allTextContents() {
215
+ return this.loc.allTextContents();
216
+ }
217
+ ariaSnapshot(options) {
218
+ return this.loc.ariaSnapshot(options);
219
+ }
220
+ async drop(payload, options) {
221
+ const p = {};
222
+ if (payload.files)
223
+ p.files = payload.files;
224
+ if (payload.data)
225
+ p.data = payload.data;
226
+ await this.loc.drop(p, options);
227
+ }
228
+ }
229
+ const frameIds = new WeakMap();
230
+ class PlaywrightFrame {
231
+ frame;
232
+ id;
233
+ constructor(frame) {
234
+ this.frame = frame;
235
+ let id = frameIds.get(frame);
236
+ if (!id) {
237
+ id = createId('frame', 4);
238
+ frameIds.set(frame, id);
239
+ }
240
+ this.id = id;
241
+ }
242
+ name() {
243
+ return this.frame.name();
244
+ }
245
+ url() {
246
+ return this.frame.url();
247
+ }
248
+ isMain() {
249
+ return this.frame.parentFrame() === null;
250
+ }
251
+ isDetached() {
252
+ return this.frame.isDetached();
253
+ }
254
+ parent() {
255
+ const p = this.frame.parentFrame();
256
+ return p ? new PlaywrightFrame(p) : null;
257
+ }
258
+ children() {
259
+ return this.frame.childFrames().map((f) => new PlaywrightFrame(f));
260
+ }
261
+ waitForLoadState(state, options) {
262
+ return this.frame.waitForLoadState(state, options);
263
+ }
264
+ locator(selector) {
265
+ return new PlaywrightLocator(this.frame.locator(selector), selector);
266
+ }
267
+ evaluate(fn, arg) {
268
+ return this.frame.evaluate(portableFunction(fn, ['arg']), arg);
269
+ }
270
+ content() {
271
+ return this.frame.content();
272
+ }
273
+ title() {
274
+ return this.frame.title();
275
+ }
276
+ }
277
+ class PlaywrightDownload {
278
+ d;
279
+ constructor(d) {
280
+ this.d = d;
281
+ }
282
+ url() {
283
+ return this.d.url();
284
+ }
285
+ suggestedFilename() {
286
+ return this.d.suggestedFilename();
287
+ }
288
+ saveAs(path) {
289
+ return this.d.saveAs(path);
290
+ }
291
+ failure() {
292
+ return this.d.failure();
293
+ }
294
+ cancel() {
295
+ return this.d.cancel();
296
+ }
297
+ delete() {
298
+ return this.d.delete();
299
+ }
300
+ }
301
+ function wrapDialog(d) {
302
+ return {
303
+ type: d.type(),
304
+ message: d.message(),
305
+ defaultValue: d.defaultValue(),
306
+ accept: (text) => d.accept(text),
307
+ dismiss: () => d.dismiss(),
308
+ };
309
+ }
310
+ async function applyRoute(route, handler) {
311
+ const req = route.request();
312
+ let decision;
313
+ try {
314
+ decision = await handler({ ...toRequestInfo(req), postData: postDataText(req) });
315
+ }
316
+ catch {
317
+ // A failing handler (policy check, user mock) must neither hang the request nor let it through.
318
+ await route.abort('failed').catch(() => undefined);
319
+ return;
320
+ }
321
+ if (decision.action === 'continue') {
322
+ // Overrides can change headers, method and body, never the URL: the policy already approved it.
323
+ const o = decision.overrides;
324
+ if (o && (o.headers || o.method || o.postData !== undefined)) {
325
+ const fb = {};
326
+ if (o.headers)
327
+ fb.headers = o.headers;
328
+ if (o.method)
329
+ fb.method = o.method;
330
+ if (o.postData !== undefined)
331
+ fb.postData = o.postData;
332
+ await route.fallback(fb);
333
+ }
334
+ else
335
+ await route.fallback();
336
+ }
337
+ else if (decision.action === 'abort')
338
+ await route.abort(decision.errorCode ?? 'blockedbyclient');
339
+ else {
340
+ const f = { status: decision.status, body: decision.body, contentType: decision.contentType ?? 'text/plain' };
341
+ if (decision.headers)
342
+ f.headers = decision.headers;
343
+ await route.fulfill(f);
344
+ }
345
+ }
346
+ function toMockConnection(ws) {
347
+ return {
348
+ url: ws.url(),
349
+ send: (message) => ws.send(message),
350
+ close: (options) => ws.close(options),
351
+ onMessage: (handler) => ws.onMessage(handler),
352
+ onClose: (handler) => ws.onClose(handler),
353
+ };
354
+ }
355
+ function wrapWebSocket(ws) {
356
+ return {
357
+ url: () => ws.url(),
358
+ isClosed: () => ws.isClosed(),
359
+ on: ((event, listener) => {
360
+ if (event === 'framesent')
361
+ ws.on('framesent', (f) => listener({ payload: f.payload }));
362
+ else if (event === 'framereceived')
363
+ ws.on('framereceived', (f) => listener({ payload: f.payload }));
364
+ else if (event === 'close')
365
+ ws.on('close', () => listener());
366
+ else if (event === 'socketerror')
367
+ ws.on('socketerror', (e) => listener(e));
368
+ }),
369
+ };
370
+ }
371
+ function wrapFileChooser(fc) {
372
+ return { isMultiple: () => fc.isMultiple(), setFiles: (files, options) => fc.setFiles(files, options) };
373
+ }
374
+ const pageWrappers = new WeakMap();
375
+ /** Engines of persistent contexts, whose `browser()` may be null. */
376
+ const persistentEngines = new WeakMap();
377
+ function engineOfContext(ctx) {
378
+ return ctx.browser()?.browserType().name() ?? persistentEngines.get(ctx) ?? null;
379
+ }
380
+ class PlaywrightPage {
381
+ raw;
382
+ id = createId('pwpage', 5);
383
+ routeHandler;
384
+ wsRouted = false;
385
+ wsPolicy = null;
386
+ wsMocks = [];
387
+ locatorHandlers = new Map();
388
+ static wrap(page) {
389
+ let w = pageWrappers.get(page);
390
+ if (!w) {
391
+ w = new PlaywrightPage(page);
392
+ pageWrappers.set(page, w);
393
+ }
394
+ return w;
395
+ }
396
+ constructor(raw) {
397
+ this.raw = raw;
398
+ }
399
+ mainFrame() {
400
+ return new PlaywrightFrame(this.raw.mainFrame());
401
+ }
402
+ frames() {
403
+ return this.raw.frames().map((f) => new PlaywrightFrame(f));
404
+ }
405
+ url() {
406
+ return this.raw.url();
407
+ }
408
+ title() {
409
+ return this.raw.title();
410
+ }
411
+ content() {
412
+ return this.raw.content();
413
+ }
414
+ setContent(html, options) {
415
+ return this.raw.setContent(html, options);
416
+ }
417
+ async goto(url, options) {
418
+ return toResponseInfo(await this.raw.goto(url, options));
419
+ }
420
+ async reload(options) {
421
+ return toResponseInfo(await this.raw.reload(options));
422
+ }
423
+ async goBack(options) {
424
+ return toResponseInfo(await this.raw.goBack(options));
425
+ }
426
+ async goForward(options) {
427
+ return toResponseInfo(await this.raw.goForward(options));
428
+ }
429
+ waitForLoadState(state, options) {
430
+ return this.raw.waitForLoadState(state, options);
431
+ }
432
+ waitForURL(predicate, options) {
433
+ return this.raw.waitForURL((u) => predicate(u.toString()), { ...options, waitUntil: 'commit' });
434
+ }
435
+ waitForTimeout(ms) {
436
+ return this.raw.waitForTimeout(ms);
437
+ }
438
+ async waitForFunction(fn, arg, options) {
439
+ await this.raw.waitForFunction(portableFunction(fn, ['arg']), arg, options);
440
+ }
441
+ evaluate(fn, arg) {
442
+ return this.raw.evaluate(portableFunction(fn, ['arg']), arg);
443
+ }
444
+ locator(selector) {
445
+ return new PlaywrightLocator(this.raw.locator(selector), selector);
446
+ }
447
+ screenshot(options) {
448
+ return this.raw.screenshot(toPwShot(options));
449
+ }
450
+ viewport() {
451
+ return this.raw.viewportSize();
452
+ }
453
+ setViewport(viewport) {
454
+ return this.raw.setViewportSize(viewport);
455
+ }
456
+ get mouse() {
457
+ const m = this.raw.mouse;
458
+ return {
459
+ move: (x, y, o) => m.move(x, y, o),
460
+ click: (x, y, o) => m.click(x, y, o),
461
+ down: (o) => m.down(o),
462
+ up: (o) => m.up(o),
463
+ wheel: (dx, dy) => m.wheel(dx, dy),
464
+ dblclick: (x, y, o) => m.dblclick(x, y, o),
465
+ };
466
+ }
467
+ get keyboard() {
468
+ const k = this.raw.keyboard;
469
+ return {
470
+ press: (key, o) => k.press(key, o),
471
+ type: (text, o) => k.type(text, o),
472
+ down: (key) => k.down(key),
473
+ up: (key) => k.up(key),
474
+ insertText: (text) => k.insertText(text),
475
+ };
476
+ }
477
+ get touchscreen() {
478
+ return { tap: (x, y) => this.raw.touchscreen.tap(x, y) };
479
+ }
480
+ webStorage(kind) {
481
+ const s = kind === 'local' ? this.raw.localStorage : this.raw.sessionStorage;
482
+ return {
483
+ getItem: (name) => s.getItem(name),
484
+ setItem: (name, value) => s.setItem(name, value),
485
+ removeItem: (name) => s.removeItem(name),
486
+ clear: () => s.clear(),
487
+ items: async () => (await s.items()).map((i) => ({ name: i.name, value: i.value })),
488
+ };
489
+ }
490
+ async route(handler) {
491
+ await this.unroute();
492
+ this.routeHandler = (route) => applyRoute(route, handler);
493
+ await this.raw.route('**/*', this.routeHandler);
494
+ }
495
+ async unroute() {
496
+ if (this.routeHandler) {
497
+ await this.raw.unroute('**/*', this.routeHandler);
498
+ this.routeHandler = undefined;
499
+ }
500
+ }
501
+ /** One catch-all WebSocket route per page: user mocks (newest first), then the policy, then the network. */
502
+ async ensureWebSocketRoute() {
503
+ if (this.wsRouted)
504
+ return;
505
+ this.wsRouted = true;
506
+ await this.raw.routeWebSocket(/.*/, async (ws) => {
507
+ const url = ws.url();
508
+ for (let i = this.wsMocks.length - 1; i >= 0; i--) {
509
+ const m = this.wsMocks[i];
510
+ if (m.match(url)) {
511
+ m.handler(toMockConnection(ws));
512
+ return; // mocked: never reaches the network
513
+ }
514
+ }
515
+ let allowed = true;
516
+ if (this.wsPolicy) {
517
+ try {
518
+ allowed = await this.wsPolicy(url);
519
+ }
520
+ catch {
521
+ allowed = false;
522
+ }
523
+ }
524
+ if (allowed)
525
+ ws.connectToServer();
526
+ else
527
+ await ws.close({ code: 1008, reason: 'Blocked by network policy' }).catch(() => undefined);
528
+ });
529
+ }
530
+ async routeWebSockets(handler) {
531
+ this.wsPolicy = handler;
532
+ await this.ensureWebSocketRoute();
533
+ }
534
+ async mockWebSocket(match, handler) {
535
+ const entry = { match, handler };
536
+ this.wsMocks.push(entry);
537
+ await this.ensureWebSocketRoute();
538
+ return async () => {
539
+ const i = this.wsMocks.indexOf(entry);
540
+ if (i >= 0)
541
+ this.wsMocks.splice(i, 1);
542
+ };
543
+ }
544
+ pdf(options = {}) {
545
+ return this.raw.pdf(options);
546
+ }
547
+ emulateMedia(options) {
548
+ return this.raw.emulateMedia(options);
549
+ }
550
+ ariaSnapshot(options = {}) {
551
+ return this.raw.ariaSnapshot(options);
552
+ }
553
+ setExtraHTTPHeaders(headers) {
554
+ return this.raw.setExtraHTTPHeaders(headers);
555
+ }
556
+ async addInitScript(script) {
557
+ await this.raw.addInitScript(script);
558
+ }
559
+ async addScriptTag(options) {
560
+ await this.raw.addScriptTag(options);
561
+ }
562
+ async addStyleTag(options) {
563
+ await this.raw.addStyleTag(options);
564
+ }
565
+ async exposeFunction(name, fn) {
566
+ await this.raw.exposeFunction(name, fn);
567
+ }
568
+ get clock() {
569
+ const c = this.raw.clock;
570
+ return {
571
+ install: (o) => c.install(o),
572
+ fastForward: (t) => c.fastForward(t),
573
+ runFor: (t) => c.runFor(t),
574
+ pauseAt: (t) => c.pauseAt(t),
575
+ resume: () => c.resume(),
576
+ setFixedTime: (t) => c.setFixedTime(t),
577
+ setSystemTime: (t) => c.setSystemTime(t),
578
+ };
579
+ }
580
+ video() {
581
+ const v = this.raw.video();
582
+ return v ? { path: () => v.path(), saveAs: (p) => v.saveAs(p), delete: () => v.delete() } : null;
583
+ }
584
+ async startScreencast(options) {
585
+ const o = {};
586
+ if (options.path)
587
+ o.path = options.path;
588
+ if (options.onFrame)
589
+ o.onFrame = options.onFrame;
590
+ if (options.size)
591
+ o.size = options.size;
592
+ if (options.quality !== undefined)
593
+ o.quality = options.quality;
594
+ if (options.fps !== undefined)
595
+ o.fps = options.fps;
596
+ await this.raw.screencast.start(o);
597
+ }
598
+ stopScreencast() {
599
+ return this.raw.screencast.stop();
600
+ }
601
+ get coverage() {
602
+ // Playwright exposes `coverage` on every page but only Chromium implements it.
603
+ const cov = this.raw.coverage;
604
+ if (!cov || engineOfContext(this.raw.context()) !== 'chromium')
605
+ return null;
606
+ return {
607
+ startJSCoverage: (o) => cov.startJSCoverage(o),
608
+ stopJSCoverage: async () => (await cov.stopJSCoverage()).map((e) => ({
609
+ url: e.url,
610
+ scriptId: e.scriptId,
611
+ ...(e.source !== undefined ? { source: e.source } : {}),
612
+ functions: e.functions,
613
+ })),
614
+ startCSSCoverage: (o) => cov.startCSSCoverage(o),
615
+ stopCSSCoverage: async () => (await cov.stopCSSCoverage()).map((e) => ({ url: e.url, ...(e.text !== undefined ? { text: e.text } : {}), ranges: e.ranges })),
616
+ };
617
+ }
618
+ workers() {
619
+ return this.raw.workers().map((w) => ({ url: w.url() }));
620
+ }
621
+ async addLocatorHandler(selector, handler, options = {}) {
622
+ const loc = this.raw.locator(selector);
623
+ this.locatorHandlers.set(selector, loc);
624
+ await this.raw.addLocatorHandler(loc, () => handler(), options);
625
+ }
626
+ async removeLocatorHandler(selector) {
627
+ const loc = this.locatorHandlers.get(selector);
628
+ if (!loc)
629
+ return;
630
+ this.locatorHandlers.delete(selector);
631
+ await this.raw.removeLocatorHandler(loc);
632
+ }
633
+ async routeFromHAR(path, options = {}) {
634
+ await this.raw.routeFromHAR(path, harReplayOptions(options));
635
+ }
636
+ requestGC() {
637
+ return this.raw.requestGC();
638
+ }
639
+ pause() {
640
+ return this.raw.pause();
641
+ }
642
+ bringToFront() {
643
+ return this.raw.bringToFront();
644
+ }
645
+ setDefaultTimeout(ms) {
646
+ this.raw.setDefaultTimeout(ms);
647
+ this.raw.setDefaultNavigationTimeout(ms);
648
+ }
649
+ close() {
650
+ return this.raw.close();
651
+ }
652
+ isClosed() {
653
+ return this.raw.isClosed();
654
+ }
655
+ on(event, listener) {
656
+ const emit = listener;
657
+ let raw;
658
+ let name = event;
659
+ switch (event) {
660
+ case 'request':
661
+ raw = ((r) => emit(toRequestInfo(r)));
662
+ break;
663
+ case 'response':
664
+ raw = ((r) => {
665
+ const t = r.request().timing();
666
+ emit({
667
+ requestId: requestId(r.request()),
668
+ url: r.url(),
669
+ status: r.status(),
670
+ statusText: r.statusText(),
671
+ headers: r.headers(),
672
+ fromServiceWorker: r.fromServiceWorker(),
673
+ timing: { responseStart: t.responseStart, responseEnd: t.responseEnd },
674
+ remoteAddress: null,
675
+ body: () => r.body(),
676
+ });
677
+ });
678
+ break;
679
+ case 'requestfailed':
680
+ raw = ((r) => emit({ requestId: requestId(r), url: r.url(), errorText: r.failure()?.errorText ?? 'unknown' }));
681
+ break;
682
+ case 'requestfinished':
683
+ raw = ((r) => emit({ requestId: requestId(r), url: r.url() }));
684
+ break;
685
+ case 'framenavigated':
686
+ raw = ((f) => emit({ url: f.url(), isMainFrame: f.parentFrame() === null, frame: new PlaywrightFrame(f) }));
687
+ break;
688
+ case 'frameattached':
689
+ case 'framedetached':
690
+ raw = ((f) => emit({ frame: new PlaywrightFrame(f) }));
691
+ break;
692
+ case 'dialog':
693
+ raw = ((d) => emit(wrapDialog(d)));
694
+ break;
695
+ case 'download':
696
+ raw = ((d) => emit(new PlaywrightDownload(d)));
697
+ break;
698
+ case 'popup':
699
+ raw = ((p) => emit(PlaywrightPage.wrap(p)));
700
+ break;
701
+ case 'console':
702
+ raw = ((m) => {
703
+ const loc = m.location();
704
+ emit({ type: m.type(), text: m.text(), location: loc.url ? `${loc.url}:${loc.lineNumber}` : null });
705
+ });
706
+ break;
707
+ case 'pageerror':
708
+ raw = ((e) => emit({ message: e.message }));
709
+ break;
710
+ case 'websocket':
711
+ raw = ((ws) => emit(wrapWebSocket(ws)));
712
+ break;
713
+ case 'filechooser':
714
+ raw = ((fc) => emit(wrapFileChooser(fc)));
715
+ break;
716
+ case 'worker':
717
+ raw = ((w) => emit({ url: w.url() }));
718
+ break;
719
+ default:
720
+ name = event;
721
+ raw = (() => emit({}));
722
+ }
723
+ this.raw.on(name, raw);
724
+ return () => {
725
+ this.raw.off(name, raw);
726
+ };
727
+ }
728
+ }
729
+ const contextWrappers = new WeakMap();
730
+ class PlaywrightContext {
731
+ raw;
732
+ id = createId('pwctx', 5);
733
+ static wrap(ctx) {
734
+ let w = contextWrappers.get(ctx);
735
+ if (!w) {
736
+ w = new PlaywrightContext(ctx);
737
+ contextWrappers.set(ctx, w);
738
+ }
739
+ return w;
740
+ }
741
+ constructor(raw) {
742
+ this.raw = raw;
743
+ }
744
+ async newPage() {
745
+ return PlaywrightPage.wrap(await this.raw.newPage());
746
+ }
747
+ pages() {
748
+ return this.raw.pages().map((p) => PlaywrightPage.wrap(p));
749
+ }
750
+ async cookies(urls) {
751
+ return (await this.raw.cookies(urls));
752
+ }
753
+ addCookies(cookies) {
754
+ return this.raw.addCookies(cookies);
755
+ }
756
+ clearCookies(filter) {
757
+ return this.raw.clearCookies(filter);
758
+ }
759
+ setHTTPCredentials(credentials) {
760
+ return this.raw.setHTTPCredentials(credentials);
761
+ }
762
+ get credentials() {
763
+ const c = this.raw.credentials;
764
+ return {
765
+ install: () => c.install(),
766
+ create: (rpId, options) => c.create(rpId, options),
767
+ get: (filter) => c.get(filter),
768
+ delete: (id) => c.delete(id),
769
+ };
770
+ }
771
+ serviceWorkers() {
772
+ return this.raw.serviceWorkers().map((w) => ({ url: w.url() }));
773
+ }
774
+ onServiceWorker(listener) {
775
+ const raw = (w) => listener({ url: w.url() });
776
+ this.raw.on('serviceworker', raw);
777
+ return () => this.raw.off('serviceworker', raw);
778
+ }
779
+ async storageState(options = {}) {
780
+ return (await this.raw.storageState(options.indexedDB ? { indexedDB: true } : {}));
781
+ }
782
+ grantPermissions(permissions, origin) {
783
+ return this.raw.grantPermissions(permissions, origin ? { origin } : undefined);
784
+ }
785
+ setOffline(offline) {
786
+ return this.raw.setOffline(offline);
787
+ }
788
+ clearPermissions() {
789
+ return this.raw.clearPermissions();
790
+ }
791
+ setGeolocation(geolocation) {
792
+ return this.raw.setGeolocation(geolocation);
793
+ }
794
+ setExtraHTTPHeaders(headers) {
795
+ return this.raw.setExtraHTTPHeaders(headers);
796
+ }
797
+ setStorageState(state) {
798
+ return this.raw.setStorageState(state);
799
+ }
800
+ async addInitScript(script) {
801
+ await this.raw.addInitScript(script);
802
+ }
803
+ async exposeFunction(name, fn) {
804
+ await this.raw.exposeFunction(name, fn);
805
+ }
806
+ async routeFromHAR(path, options = {}) {
807
+ await this.raw.routeFromHAR(path, harReplayOptions(options));
808
+ }
809
+ get tracing() {
810
+ const t = this.raw.tracing;
811
+ return {
812
+ start: async (o) => {
813
+ await t.start(o);
814
+ },
815
+ startChunk: async (o) => {
816
+ await t.startChunk(o);
817
+ },
818
+ stopChunk: (path) => t.stopChunk(path ? { path } : undefined),
819
+ stop: (path) => t.stop(path ? { path } : undefined),
820
+ group: async (name) => {
821
+ await t.group(name);
822
+ },
823
+ groupEnd: () => t.groupEnd(),
824
+ startHar: async (path, o = {}) => {
825
+ await t.startHar(path, o);
826
+ },
827
+ stopHar: () => t.stopHar(),
828
+ };
829
+ }
830
+ async route(handler) {
831
+ await this.raw.route('**/*', (route) => applyRoute(route, handler));
832
+ }
833
+ onPage(listener) {
834
+ const raw = (p) => listener(PlaywrightPage.wrap(p));
835
+ this.raw.on('page', raw);
836
+ return () => this.raw.off('page', raw);
837
+ }
838
+ close() {
839
+ return this.raw.close();
840
+ }
841
+ }
842
+ function harReplayOptions(options) {
843
+ const o = { notFound: options.notFound ?? 'abort' };
844
+ if (options.url !== undefined)
845
+ o.url = options.url;
846
+ if (options.update)
847
+ o.update = true;
848
+ return o;
849
+ }
850
+ class PlaywrightBrowser {
851
+ raw;
852
+ engine;
853
+ processId;
854
+ id = createId('pwbrowser', 5);
855
+ constructor(raw, engine, processId) {
856
+ this.raw = raw;
857
+ this.engine = engine;
858
+ this.processId = processId;
859
+ }
860
+ get performanceTracing() {
861
+ if (this.engine !== 'chromium')
862
+ return null;
863
+ return {
864
+ start: (page, options = {}) => this.raw.startTracing(page ? page.raw : undefined, options),
865
+ stop: () => this.raw.stopTracing(),
866
+ };
867
+ }
868
+ version() {
869
+ return this.raw.version();
870
+ }
871
+ isConnected() {
872
+ return this.raw.isConnected();
873
+ }
874
+ async newContext(options = {}) {
875
+ const opts = { ...options };
876
+ return PlaywrightContext.wrap(await this.raw.newContext(opts));
877
+ }
878
+ contexts() {
879
+ return this.raw.contexts().map((c) => PlaywrightContext.wrap(c));
880
+ }
881
+ onDisconnected(listener) {
882
+ this.raw.on('disconnected', listener);
883
+ return () => this.raw.off('disconnected', listener);
884
+ }
885
+ close() {
886
+ return this.raw.close();
887
+ }
888
+ pid() {
889
+ return this.processId;
890
+ }
891
+ }
892
+ function screenOf(d) {
893
+ const screen = d.screen;
894
+ return screen ? { screen } : {};
895
+ }
896
+ /** A persistent-profile browser: exactly one context, owned by the profile directory. */
897
+ class PersistentBrowser {
898
+ ctx;
899
+ engine;
900
+ id = createId('pwbrowser', 5);
901
+ connected = true;
902
+ listeners = new Set();
903
+ constructor(ctx, engine) {
904
+ this.ctx = ctx;
905
+ this.engine = engine;
906
+ ctx.on('close', () => {
907
+ this.connected = false;
908
+ for (const l of this.listeners)
909
+ l();
910
+ });
911
+ }
912
+ performanceTracing = null;
913
+ version() {
914
+ return this.ctx.browser()?.version() ?? 'persistent';
915
+ }
916
+ isConnected() {
917
+ return this.connected;
918
+ }
919
+ newContext() {
920
+ return Promise.reject(new Error('A persistent-profile browser has a single context; open pages in it instead.'));
921
+ }
922
+ contexts() {
923
+ return this.connected ? [PlaywrightContext.wrap(this.ctx)] : [];
924
+ }
925
+ onDisconnected(listener) {
926
+ this.listeners.add(listener);
927
+ return () => this.listeners.delete(listener);
928
+ }
929
+ close() {
930
+ return this.ctx.close();
931
+ }
932
+ pid() {
933
+ return null;
934
+ }
935
+ }
936
+ function engineType(engine) {
937
+ switch (engine) {
938
+ case 'chromium':
939
+ return pw.chromium;
940
+ case 'firefox':
941
+ return pw.firefox;
942
+ case 'webkit':
943
+ return pw.webkit;
944
+ }
945
+ }
946
+ /** Playwright implementation of the engine adapter (Chromium, Firefox, WebKit). */
947
+ /** Path to the bundled playwright-core CLI (used by `bashirweb browser install`). */
948
+ export function playwrightCliPath() {
949
+ const req = createRequire(import.meta.url);
950
+ return join(dirname(req.resolve('playwright-core/package.json')), 'cli.js');
951
+ }
952
+ /**
953
+ * Makes a function safe to serialize into the page.
954
+ *
955
+ * Bundlers that preserve function names (esbuild/tsx/vite with `keepNames`) rewrite nested
956
+ * functions as `__name(fn, "name")`, referencing a helper that only exists in the bundle.
957
+ * Playwright serializes functions with `toString()`, so the helper would be undefined in the
958
+ * page. When that helper appears in the source we rebuild the function in Node with a local
959
+ * no-op `__name`. Evaluation still happens over the protocol, so page CSP is unaffected.
960
+ */
961
+ const portableCache = new WeakMap();
962
+ export function portableFunction(fn, params) {
963
+ const cached = portableCache.get(fn);
964
+ if (cached)
965
+ return cached;
966
+ let out = fn;
967
+ const src = Function.prototype.toString.call(fn);
968
+ if (src.includes('__name')) {
969
+ try {
970
+ out = new Function(...params, `const __name = (target) => target;\nreturn (${src})(${params.join(', ')});`);
971
+ }
972
+ catch {
973
+ out = fn; // e.g. method shorthand that is not a standalone expression; leave untouched
974
+ }
975
+ }
976
+ portableCache.set(fn, out);
977
+ return out;
978
+ }
979
+ export class PlaywrightEngineAdapter {
980
+ name = 'playwright';
981
+ supportedEngines = ['chromium', 'firefox', 'webkit'];
982
+ async launch(options) {
983
+ const type = engineType(options.engine);
984
+ // Firefox bypasses proxies for localhost unless hijacking is allowed (set in launchOptions), and
985
+ // Chromium refuses to run its sandbox as root (common in containers).
986
+ const launchOptions = this.launchOptions(options);
987
+ const browser = await type.launch(launchOptions);
988
+ return new PlaywrightBrowser(browser, options.engine, null);
989
+ }
990
+ launchOptions(options) {
991
+ const launchOptions = {
992
+ headless: options.headless,
993
+ args: options.args ?? [],
994
+ slowMo: options.slowMo ?? 0,
995
+ timeout: options.timeout ?? 30_000,
996
+ };
997
+ if (options.executablePath)
998
+ launchOptions.executablePath = options.executablePath;
999
+ if (options.channel)
1000
+ launchOptions.channel = options.channel;
1001
+ if (options.proxy)
1002
+ launchOptions.proxy = options.proxy;
1003
+ if (options.env)
1004
+ launchOptions.env = options.env;
1005
+ if (options.downloadsPath)
1006
+ launchOptions.downloadsPath = options.downloadsPath;
1007
+ if (options.engine === 'firefox' && options.proxy)
1008
+ launchOptions.firefoxUserPrefs = { 'network.proxy.allow_hijacking_localhost': true };
1009
+ if (options.engine === 'chromium' && process.platform === 'linux' && typeof process.getuid === 'function' && process.getuid() === 0)
1010
+ launchOptions.chromiumSandbox = false;
1011
+ return launchOptions;
1012
+ }
1013
+ async launchPersistent(options) {
1014
+ const ctx = await engineType(options.engine).launchPersistentContext(options.userDataDir, {
1015
+ ...this.launchOptions(options),
1016
+ ...options.context,
1017
+ });
1018
+ persistentEngines.set(ctx, options.engine);
1019
+ return { browser: new PersistentBrowser(ctx, options.engine), context: PlaywrightContext.wrap(ctx) };
1020
+ }
1021
+ devices() {
1022
+ return Object.entries(pw.devices).map(([name, d]) => ({
1023
+ name,
1024
+ userAgent: d.userAgent,
1025
+ viewport: d.viewport,
1026
+ ...screenOf(d),
1027
+ deviceScaleFactor: d.deviceScaleFactor,
1028
+ isMobile: d.isMobile,
1029
+ hasTouch: d.hasTouch,
1030
+ defaultBrowserType: d.defaultBrowserType,
1031
+ }));
1032
+ }
1033
+ async newApiRequest(options) {
1034
+ const o = {};
1035
+ if (options.proxy)
1036
+ o.proxy = options.proxy;
1037
+ if (options.storageState)
1038
+ o.storageState = options.storageState;
1039
+ if (options.userAgent)
1040
+ o.userAgent = options.userAgent;
1041
+ if (options.extraHTTPHeaders)
1042
+ o.extraHTTPHeaders = options.extraHTTPHeaders;
1043
+ const api = await pw.request.newContext(o);
1044
+ return {
1045
+ fetch: async (url, f) => {
1046
+ const req = { method: f.method, maxRedirects: f.maxRedirects ?? 0, failOnStatusCode: false };
1047
+ if (f.headers)
1048
+ req.headers = f.headers;
1049
+ if (f.data !== undefined)
1050
+ req.data = f.data;
1051
+ if (f.timeout !== undefined)
1052
+ req.timeout = f.timeout;
1053
+ if (f.ignoreHTTPSErrors)
1054
+ req.ignoreHTTPSErrors = true;
1055
+ const res = await api.fetch(url, req);
1056
+ try {
1057
+ return { url: res.url(), status: res.status(), statusText: res.statusText(), headers: res.headers(), body: await res.body() };
1058
+ }
1059
+ finally {
1060
+ await res.dispose();
1061
+ }
1062
+ },
1063
+ storageState: async () => (await api.storageState()),
1064
+ cookies: async (urls) => (await api.cookies(urls)),
1065
+ addCookies: (cookies) => api.addCookies(cookies),
1066
+ clearCookies: (filter) => api.clearCookies(filter),
1067
+ dispose: () => api.dispose(),
1068
+ };
1069
+ }
1070
+ async connect(endpoint, options) {
1071
+ const type = engineType(options.engine);
1072
+ const browser = options.engine === 'chromium' && /^https?:/.test(endpoint)
1073
+ ? await type.connectOverCDP(endpoint, { timeout: options.timeout ?? 30_000, headers: options.headers ?? {} })
1074
+ : await type.connect(endpoint, { timeout: options.timeout ?? 30_000, headers: options.headers ?? {} });
1075
+ return new PlaywrightBrowser(browser, options.engine, null);
1076
+ }
1077
+ executablePath(engine) {
1078
+ try {
1079
+ const p = engineType(engine).executablePath();
1080
+ return p && existsSync(p) ? p : null;
1081
+ }
1082
+ catch {
1083
+ return null;
1084
+ }
1085
+ }
1086
+ }
1087
+ //# sourceMappingURL=playwright.js.map