testsurfer 0.1.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +52 -149
  2. package/dist/browser.d.ts +135 -1
  3. package/dist/browser.js +378 -2
  4. package/dist/browser.js.map +1 -1
  5. package/dist/cli.d.ts +16 -0
  6. package/dist/cli.js +140 -0
  7. package/dist/cli.js.map +1 -0
  8. package/dist/client.d.ts +12 -2
  9. package/dist/client.js +73 -4
  10. package/dist/client.js.map +1 -1
  11. package/dist/diff.d.ts +19 -0
  12. package/dist/diff.js +116 -0
  13. package/dist/diff.js.map +1 -0
  14. package/dist/events.d.ts +386 -0
  15. package/dist/events.js +1035 -0
  16. package/dist/events.js.map +1 -0
  17. package/dist/expect.d.ts +135 -26
  18. package/dist/expect.js +634 -130
  19. package/dist/expect.js.map +1 -1
  20. package/dist/frame.d.ts +88 -0
  21. package/dist/frame.js +194 -0
  22. package/dist/frame.js.map +1 -0
  23. package/dist/global.d.ts +12 -0
  24. package/dist/global.js +136 -0
  25. package/dist/global.js.map +1 -0
  26. package/dist/hooks.d.ts +28 -0
  27. package/dist/hooks.js +48 -0
  28. package/dist/hooks.js.map +1 -0
  29. package/dist/index.d.ts +22 -3
  30. package/dist/index.js +21 -3
  31. package/dist/index.js.map +1 -1
  32. package/dist/injected.d.ts +15 -0
  33. package/dist/injected.js +2025 -0
  34. package/dist/injected.js.map +1 -0
  35. package/dist/locator.d.ts +374 -86
  36. package/dist/locator.js +845 -244
  37. package/dist/locator.js.map +1 -1
  38. package/dist/media.d.ts +15 -0
  39. package/dist/media.js +83 -0
  40. package/dist/media.js.map +1 -0
  41. package/dist/net.d.ts +110 -0
  42. package/dist/net.js +498 -0
  43. package/dist/net.js.map +1 -0
  44. package/dist/page.d.ts +448 -5
  45. package/dist/page.js +1187 -31
  46. package/dist/page.js.map +1 -1
  47. package/dist/png.d.ts +28 -0
  48. package/dist/png.js +197 -0
  49. package/dist/png.js.map +1 -0
  50. package/dist/pwconfig.d.ts +66 -0
  51. package/dist/pwconfig.js +77 -0
  52. package/dist/pwconfig.js.map +1 -0
  53. package/dist/register.d.ts +6 -0
  54. package/dist/register.js +9 -0
  55. package/dist/register.js.map +1 -0
  56. package/dist/request.d.ts +29 -0
  57. package/dist/request.js +75 -0
  58. package/dist/request.js.map +1 -0
  59. package/dist/runner.d.ts +99 -15
  60. package/dist/runner.js +354 -58
  61. package/dist/runner.js.map +1 -1
  62. package/dist/screenshot.d.ts +35 -0
  63. package/dist/screenshot.js +171 -0
  64. package/dist/screenshot.js.map +1 -0
  65. package/dist/selector.d.ts +55 -0
  66. package/dist/selector.js +208 -0
  67. package/dist/selector.js.map +1 -0
  68. package/dist/selectors.d.ts +13 -0
  69. package/dist/selectors.js +16 -0
  70. package/dist/selectors.js.map +1 -0
  71. package/dist/serialize.d.ts +17 -0
  72. package/dist/serialize.js +149 -0
  73. package/dist/serialize.js.map +1 -0
  74. package/dist/shim.d.ts +15 -0
  75. package/dist/shim.js +211 -0
  76. package/dist/shim.js.map +1 -0
  77. package/dist/testinfo.d.ts +62 -0
  78. package/dist/testinfo.js +23 -0
  79. package/dist/testinfo.js.map +1 -0
  80. package/dist/values.d.ts +67 -0
  81. package/dist/values.js +293 -0
  82. package/dist/values.js.map +1 -0
  83. package/package.json +10 -3
  84. package/skills/testsurfer/SKILL.md +55 -0
package/dist/events.js ADDED
@@ -0,0 +1,1035 @@
1
+ /**
2
+ * page.route() and page.on(), driven by the page shim (src/shim.ts).
3
+ *
4
+ * A poller on its own daemon connection takes the shim's queue every
5
+ * few milliseconds while the page has routes or listeners. It emits
6
+ * events and runs route handlers, then settles each held request in
7
+ * the page. Its own connection means a long call on the test's
8
+ * connection (a wait) cannot stall a request the page is waiting on.
9
+ */
10
+ import { readFile } from 'node:fs/promises';
11
+ import { brotliDecompressSync, gunzipSync, inflateSync } from 'node:zlib';
12
+ import { NetHub } from "./net.js";
13
+ /** Playwright-style glob: `**` any characters, `*` any but `/`, `{a,b}` alternatives. */
14
+ export function globToRegExp(glob) {
15
+ let out = '^';
16
+ let inGroup = false;
17
+ for (let i = 0; i < glob.length; i++) {
18
+ const c = glob[i];
19
+ if (c === '\\' && i + 1 < glob.length) {
20
+ // A backslash makes the next character literal (`index\\?hello`).
21
+ const next = glob[++i];
22
+ out += '\\^$.|?+()[]{}*'.includes(next) ? `\\${next}` : next;
23
+ }
24
+ else if (c === '*') {
25
+ if (glob[i + 1] === '*') {
26
+ out += '.*';
27
+ i++;
28
+ if (glob[i + 1] === '/') {
29
+ // `**/` also matches nothing, so `**/api` matches `/api`.
30
+ out += '/?';
31
+ i++;
32
+ }
33
+ }
34
+ else {
35
+ out += '[^/]*';
36
+ }
37
+ }
38
+ else if (c === '{') {
39
+ inGroup = true;
40
+ out += '(';
41
+ }
42
+ else if (c === '}' && inGroup) {
43
+ inGroup = false;
44
+ out += ')';
45
+ }
46
+ else if (c === ',' && inGroup) {
47
+ out += '|';
48
+ }
49
+ else if ('\\^$.|?+()[]'.includes(c)) {
50
+ out += `\\${c}`;
51
+ }
52
+ else {
53
+ out += c;
54
+ }
55
+ }
56
+ return new RegExp(`${out}$`);
57
+ }
58
+ export function urlMatches(matcher, url, baseURL) {
59
+ if (typeof matcher === 'function') {
60
+ try {
61
+ return matcher(new URL(url));
62
+ }
63
+ catch {
64
+ return false;
65
+ }
66
+ }
67
+ if (matcher instanceof RegExp)
68
+ return matcher.test(url);
69
+ let pattern = matcher;
70
+ if (baseURL && !/^[a-z]+:|^\*/i.test(pattern)) {
71
+ try {
72
+ pattern = new URL(pattern, baseURL).href;
73
+ }
74
+ catch {
75
+ /* keep as given */
76
+ }
77
+ }
78
+ if (!/[*{]/.test(pattern))
79
+ return url === pattern;
80
+ return globToRegExp(pattern).test(url);
81
+ }
82
+ /** A fetch or XHR the page made. */
83
+ export class Request {
84
+ info;
85
+ /** Set once the response (or failure) arrives. */
86
+ responseValue = null;
87
+ /** The frame that made the request. */
88
+ frameValue = null;
89
+ /** Redirect chain, when the proxy saw a 3xx before this request. */
90
+ redirectedFromValue = null;
91
+ redirectedToValue = null;
92
+ /** The route aborted it. */
93
+ abortedByRoute = false;
94
+ /** Proxy mode: the page's service worker handed it on; its response is fromServiceWorker(). */
95
+ viaServiceWorker = false;
96
+ frame() {
97
+ // Resolved on first use: an iframe's frame may not be listed yet when its request starts.
98
+ if (typeof this.frameValue === 'function') {
99
+ const f = this.frameValue();
100
+ if (f)
101
+ this.frameValue = f;
102
+ return f;
103
+ }
104
+ return this.frameValue;
105
+ }
106
+ failureText = null;
107
+ constructor(info) {
108
+ this.info = info;
109
+ }
110
+ /** The shim's id for this request. */
111
+ get id() {
112
+ return this.info.id;
113
+ }
114
+ url() {
115
+ return this.info.url;
116
+ }
117
+ method() {
118
+ return this.info.method;
119
+ }
120
+ headers() {
121
+ return { ...this.info.headers };
122
+ }
123
+ /** @internal setExtraHTTPHeaders() values join the request's headers. */
124
+ addHeader(name, value) {
125
+ this.info.headers[name.toLowerCase()] = value;
126
+ }
127
+ postData() {
128
+ return this.info.body;
129
+ }
130
+ postDataJSON() {
131
+ if (this.info.body === null)
132
+ return null;
133
+ const type = this.info.headers['content-type'] ?? '';
134
+ // A form body parses as name/value pairs, as in Playwright.
135
+ if (type.includes('application/x-www-form-urlencoded')) {
136
+ return Object.fromEntries(new URLSearchParams(this.info.body));
137
+ }
138
+ return JSON.parse(this.info.body);
139
+ }
140
+ /** `fetch`, `xhr`, or `document` for the main-frame navigation goto() returns. */
141
+ resourceType() {
142
+ return this.info.type;
143
+ }
144
+ isNavigationRequest() {
145
+ return this.info.navigation ?? this.info.type === 'document';
146
+ }
147
+ /** `main` or `sub` (an iframe), as far as the proxy can tell. */
148
+ frameKind() {
149
+ return this.info.frame ?? 'main';
150
+ }
151
+ headersArray() {
152
+ if (this.info.raw)
153
+ return this.info.raw.map((h) => ({ ...h }));
154
+ return Object.entries(this.info.headers).map(([name, value]) => ({ name, value }));
155
+ }
156
+ redirectedFrom() {
157
+ return this.redirectedFromValue;
158
+ }
159
+ redirectedTo() {
160
+ return this.redirectedToValue;
161
+ }
162
+ timing() {
163
+ return { startTime: 0, domainLookupStart: -1, domainLookupEnd: -1, connectStart: -1, secureConnectionStart: -1, connectEnd: -1, requestStart: -1, responseStart: -1, responseEnd: -1 };
164
+ }
165
+ async allHeaders() {
166
+ return this.headers();
167
+ }
168
+ async headerValue(name) {
169
+ return this.info.headers[name.toLowerCase()] ?? null;
170
+ }
171
+ /** The response, when it has arrived (no waiting). */
172
+ existingResponse() {
173
+ return this.responseValue;
174
+ }
175
+ async sizes() {
176
+ return { requestBodySize: this.postDataBuffer()?.length ?? 0, requestHeadersSize: -1, responseBodySize: -1, responseHeadersSize: -1 };
177
+ }
178
+ serviceWorker() {
179
+ return null;
180
+ }
181
+ postDataBuffer() {
182
+ if (this.info.bodyBytes !== undefined)
183
+ return this.info.bodyBytes;
184
+ return this.info.body === null ? null : Buffer.from(this.info.body);
185
+ }
186
+ failure() {
187
+ return this.failureText === null ? null : { errorText: this.failureText };
188
+ }
189
+ /** Proxy mode: response() waits for the response or the failure. */
190
+ awaitsResponse = false;
191
+ settled = false;
192
+ waiters = [];
193
+ /** @internal The response arrived, or the request failed or finished. */
194
+ markSettled() {
195
+ this.settled = true;
196
+ for (const w of this.waiters.splice(0))
197
+ w();
198
+ }
199
+ async response() {
200
+ if (this.responseValue || this.settled || !this.awaitsResponse)
201
+ return this.responseValue;
202
+ await new Promise((res) => this.waiters.push(res));
203
+ return this.responseValue;
204
+ }
205
+ }
206
+ /**
207
+ * Response metadata. The body is read on demand by fetching the URL
208
+ * again from the page (GET only), since it is not captured in flight.
209
+ */
210
+ export class Response {
211
+ req;
212
+ data;
213
+ /** Reads the body; set by whoever built the response. */
214
+ bodyLoader = null;
215
+ /** Headers in their original case and order (proxy mode). */
216
+ rawHeaders = null;
217
+ constructor(req, data) {
218
+ this.req = req;
219
+ this.data = data;
220
+ }
221
+ headersArray() {
222
+ if (this.rawHeaders)
223
+ return this.rawHeaders.map((h) => ({ ...h }));
224
+ return Object.entries(this.data.headers).map(([name, value]) => ({ name, value }));
225
+ }
226
+ async headersArrayAsync() {
227
+ return this.headersArray();
228
+ }
229
+ async headerValues(name) {
230
+ const n = name.toLowerCase();
231
+ return this.headersArray()
232
+ .filter((h) => h.name.toLowerCase() === n)
233
+ .map((h) => h.value);
234
+ }
235
+ /** Proxy mode: the page's service worker handed the request on (see PageEvents.netViaServiceWorker). */
236
+ viaServiceWorker = false;
237
+ fromServiceWorker() {
238
+ return this.viaServiceWorker;
239
+ }
240
+ httpVersion() {
241
+ return 'HTTP/1.1';
242
+ }
243
+ async serverAddr() {
244
+ return null;
245
+ }
246
+ async securityDetails() {
247
+ return null;
248
+ }
249
+ async allHeaders() {
250
+ return this.headers();
251
+ }
252
+ async headerValue(name) {
253
+ return this.data.headers[name.toLowerCase()] ?? null;
254
+ }
255
+ async body() {
256
+ if (this.data.status >= 300 && this.data.status < 400 && this.data.headers['location']) {
257
+ throw new Error('response.body: Response body is unavailable for redirect responses');
258
+ }
259
+ if (!this.bodyLoader) {
260
+ throw new Error('response.body: the body of this response was not captured');
261
+ }
262
+ const raw = await this.bodyLoader();
263
+ // The proxy keeps bodies as they came over the wire; the page saw them decoded.
264
+ const enc = (this.data.headers['content-encoding'] ?? '').toLowerCase().trim();
265
+ try {
266
+ if (enc === 'gzip' || enc === 'x-gzip')
267
+ return gunzipSync(raw);
268
+ if (enc === 'deflate')
269
+ return inflateSync(raw);
270
+ if (enc === 'br')
271
+ return brotliDecompressSync(raw);
272
+ }
273
+ catch {
274
+ /* not actually encoded; hand back what came */
275
+ }
276
+ return raw;
277
+ }
278
+ async text() {
279
+ return (await this.body()).toString('utf8');
280
+ }
281
+ async json() {
282
+ return JSON.parse(await this.text());
283
+ }
284
+ async finished() {
285
+ return null;
286
+ }
287
+ frame() {
288
+ return null;
289
+ }
290
+ url() {
291
+ return this.data.url;
292
+ }
293
+ status() {
294
+ return this.data.status;
295
+ }
296
+ statusText() {
297
+ return this.data.statusText;
298
+ }
299
+ ok() {
300
+ // Playwright counts status 0 (file: and data: URLs) as ok.
301
+ return this.data.status === 0 || (this.data.status >= 200 && this.data.status < 300);
302
+ }
303
+ headers() {
304
+ return { ...this.data.headers };
305
+ }
306
+ request() {
307
+ return this.req;
308
+ }
309
+ }
310
+ export class APIResponse {
311
+ data;
312
+ constructor(data) {
313
+ this.data = data;
314
+ }
315
+ url() {
316
+ return this.data.url;
317
+ }
318
+ status() {
319
+ return this.data.status;
320
+ }
321
+ statusText() {
322
+ return this.data.statusText;
323
+ }
324
+ ok() {
325
+ return this.data.status >= 200 && this.data.status < 300;
326
+ }
327
+ headers() {
328
+ return { ...this.data.headers };
329
+ }
330
+ async body() {
331
+ return this.data.body;
332
+ }
333
+ async text() {
334
+ return this.data.body.toString('utf8');
335
+ }
336
+ async json() {
337
+ return JSON.parse(this.data.body.toString('utf8'));
338
+ }
339
+ }
340
+ /**
341
+ * An `alert`, `confirm` or `prompt` the page is blocked on (proxy
342
+ * mode). A `dialog` listener must accept or dismiss it; with no
343
+ * listener it is dismissed, as in Playwright.
344
+ */
345
+ export class Dialog {
346
+ handled = false;
347
+ kind;
348
+ text;
349
+ defaultText;
350
+ pageValue;
351
+ answer;
352
+ constructor(kind, text, defaultText, page, answer) {
353
+ this.kind = kind;
354
+ this.text = text;
355
+ this.defaultText = defaultText;
356
+ this.pageValue = page;
357
+ this.answer = answer;
358
+ }
359
+ /** @internal Whether accept() or dismiss() ran. */
360
+ isHandled() {
361
+ return this.handled;
362
+ }
363
+ type() {
364
+ return this.kind;
365
+ }
366
+ message() {
367
+ return this.text;
368
+ }
369
+ defaultValue() {
370
+ return this.defaultText;
371
+ }
372
+ page() {
373
+ return this.pageValue;
374
+ }
375
+ async accept(promptText) {
376
+ if (this.handled)
377
+ throw new Error('dialog.accept: Cannot accept dialog which is already handled!');
378
+ this.handled = true;
379
+ await this.answer(true, promptText);
380
+ }
381
+ async dismiss() {
382
+ if (this.handled)
383
+ throw new Error('dialog.dismiss: Cannot dismiss dialog which is already handled!');
384
+ this.handled = true;
385
+ await this.answer(false);
386
+ }
387
+ }
388
+ /** A console argument, as a value already copied out of the page. */
389
+ export class ConsoleArg {
390
+ value;
391
+ constructor(value) {
392
+ this.value = value;
393
+ }
394
+ async jsonValue() {
395
+ return this.value;
396
+ }
397
+ async dispose() { }
398
+ toString() {
399
+ return this.value === undefined ? 'undefined' : typeof this.value === 'object' && this.value !== null ? 'JSHandle@object' : String(this.value);
400
+ }
401
+ }
402
+ export class ConsoleMessage {
403
+ kind;
404
+ message;
405
+ values;
406
+ owner;
407
+ constructor(kind, message, values = [], owner = null) {
408
+ this.kind = kind;
409
+ this.message = message;
410
+ this.values = values;
411
+ this.owner = owner;
412
+ }
413
+ /** The arguments passed to console.*, as handles whose jsonValue() is the value. */
414
+ args() {
415
+ return this.values.map((a) => new ConsoleArg(a.u ? undefined : a.v));
416
+ }
417
+ page() {
418
+ return this.owner;
419
+ }
420
+ location() {
421
+ return { url: '', lineNumber: 0, columnNumber: 0 };
422
+ }
423
+ /** `log`, `info`, `warning`, `error` or `debug`. */
424
+ type() {
425
+ return this.kind;
426
+ }
427
+ text() {
428
+ return this.message;
429
+ }
430
+ }
431
+ /** A request held by page.route(), waiting for the handler's decision. */
432
+ export class Route {
433
+ /** Set by the first decision; a second one is an error. */
434
+ handled = false;
435
+ /** fallback() was called: try the next matching handler. */
436
+ fellBack = null;
437
+ req;
438
+ settle;
439
+ fetchVia;
440
+ constructor(req, settle, fetchVia) {
441
+ this.req = req;
442
+ this.settle = settle;
443
+ this.fetchVia = fetchVia;
444
+ }
445
+ request() {
446
+ return this.req;
447
+ }
448
+ claim(what) {
449
+ if (this.handled)
450
+ throw new Error(`route.${what}: Route is already handled!`);
451
+ this.handled = true;
452
+ }
453
+ async fulfill(options = {}) {
454
+ const st = options.status ?? options.response?.status() ?? 200;
455
+ // WebKit cannot fulfill with a redirect; Playwright refuses it there too.
456
+ if (st >= 300 && st < 400)
457
+ throw new Error(`route.fulfill: Cannot fulfill with redirect status: ${st}`);
458
+ this.claim('fulfill');
459
+ const headers = {};
460
+ let status = options.status ?? 200;
461
+ let body = Buffer.alloc(0);
462
+ if (options.response) {
463
+ Object.assign(headers, options.response.headers());
464
+ status = options.status ?? options.response.status();
465
+ body = await options.response.body();
466
+ }
467
+ Object.assign(headers, options.headers ?? {});
468
+ if (options.json !== undefined) {
469
+ body = Buffer.from(JSON.stringify(options.json));
470
+ headers['content-type'] ??= 'application/json';
471
+ }
472
+ else if (options.path) {
473
+ body = await readFile(options.path);
474
+ }
475
+ else if (options.body !== undefined) {
476
+ body = Buffer.isBuffer(options.body) ? options.body : Buffer.from(options.body);
477
+ }
478
+ if (options.contentType)
479
+ headers['content-type'] = options.contentType;
480
+ // The page derives these from the body it is handed.
481
+ delete headers['content-length'];
482
+ delete headers['content-encoding'];
483
+ await this.settle({ kind: 'fulfill', status, headers, body: body.toString('base64') });
484
+ }
485
+ async continue(options = {}) {
486
+ this.claim('continue');
487
+ await this.settle({ kind: 'continue', ...overrides(options) });
488
+ }
489
+ async abort(errorCode = 'failed') {
490
+ this.claim('abort');
491
+ await this.settle({ kind: 'abort', error: errorCode });
492
+ }
493
+ /** Let the next matching handler decide (or the network, when none does). */
494
+ async fallback(options = {}) {
495
+ this.claim('fallback');
496
+ this.fellBack = options;
497
+ }
498
+ /** Perform the request for real and return the response, to modify and fulfill with. */
499
+ async fetch(options = {}) {
500
+ return this.fetchVia(options);
501
+ }
502
+ }
503
+ function overrides(o) {
504
+ const out = {};
505
+ if (o.url)
506
+ out['url'] = o.url;
507
+ if (o.method)
508
+ out['method'] = o.method;
509
+ if (o.headers)
510
+ out['headers'] = o.headers;
511
+ if (o.postData !== undefined)
512
+ out['body'] = Buffer.isBuffer(o.postData) ? o.postData.toString('utf8') : o.postData;
513
+ return out;
514
+ }
515
+ const POLL_MS = 15;
516
+ /** Per-page routing and event state. The Page owns one. */
517
+ export class PageEvents {
518
+ routes = [];
519
+ listeners = new Map();
520
+ requests = new Map();
521
+ pendingFetch = new Map();
522
+ timer = null;
523
+ poller = null;
524
+ pollerP = null;
525
+ routingOn = false;
526
+ host;
527
+ /** Routing default last given to new documents. */
528
+ routingDefault = false;
529
+ constructor(host) {
530
+ this.host = host;
531
+ }
532
+ get active() {
533
+ return this.routes.length > 0 || this.listeners.size > 0 || this.bindings.size > 0;
534
+ }
535
+ /** exposeBinding() callbacks by name; the page calls them through the shim queue. */
536
+ bindings = new Map();
537
+ /** Register a binding and return the page-side script that defines it. */
538
+ addBinding(name, fn) {
539
+ if (this.bindings.has(name))
540
+ throw new Error(`Function "${name}" has been already registered`);
541
+ this.bindings.set(name, fn);
542
+ const n = JSON.stringify(name);
543
+ return (`(function(){if(window.top!==window)return;var ts=window.__ts;if(!ts)return;` +
544
+ `window[${n}]=function(){var args=[].slice.call(arguments);return new Promise(function(res,rej){` +
545
+ `var id='b'+(++ts.seq);ts.wait[id]=function(d){if(d.ok)res(d.v);else rej(new Error(d.e));};` +
546
+ `var enc;try{enc=JSON.parse(JSON.stringify(args));}catch(e){enc=[];}` +
547
+ `ts.ev.push({t:'call',id:id,name:${n},args:enc});});};})();`);
548
+ }
549
+ bindingDepth = 0;
550
+ async runBinding(e) {
551
+ const fn = this.bindings.get(e.name ?? '');
552
+ let d;
553
+ this.bindingDepth++;
554
+ try {
555
+ d = { ok: true, v: fn ? await fn(...(e.args ?? [])) : undefined };
556
+ }
557
+ catch (err) {
558
+ d = { ok: false, e: err instanceof Error ? err.message : String(err) };
559
+ }
560
+ finally {
561
+ this.bindingDepth--;
562
+ }
563
+ if (d.v === undefined)
564
+ delete d.v;
565
+ await this.evalPage(`window.__ts ? window.__ts.settle(${JSON.stringify(e.id)}, ${JSON.stringify(d)}) : 'gone'`).catch(() => { });
566
+ }
567
+ get routing() {
568
+ return this.routes.length > 0 && !this.proxied;
569
+ }
570
+ addRoute(matcher, handler, times) {
571
+ // Later routes take precedence, as in Playwright.
572
+ this.routes.unshift({ matcher, handler, times });
573
+ }
574
+ removeRoutes(matcher, handler) {
575
+ this.routes = this.routes.filter((r) => {
576
+ if (matcher === undefined)
577
+ return false;
578
+ const same = r.matcher === matcher || String(r.matcher) === String(matcher);
579
+ return !(same && (handler === undefined || r.handler === handler));
580
+ });
581
+ }
582
+ on(name, fn) {
583
+ let set = this.listeners.get(name);
584
+ if (!set)
585
+ this.listeners.set(name, (set = new Set()));
586
+ set.add(fn);
587
+ }
588
+ off(name, fn) {
589
+ const set = this.listeners.get(name);
590
+ if (!set)
591
+ return;
592
+ set.delete(fn);
593
+ if (set.size === 0)
594
+ this.listeners.delete(name);
595
+ }
596
+ emit(name, arg) {
597
+ for (const fn of [...(this.listeners.get(name) ?? [])]) {
598
+ try {
599
+ fn(arg);
600
+ }
601
+ catch {
602
+ /* a throwing listener must not stop the poller */
603
+ }
604
+ }
605
+ }
606
+ /** Start or stop polling and tell the page whether to hold requests. */
607
+ hub = null;
608
+ /** Proxy mode: the session's network hub carries requests, responses and routes. */
609
+ get proxied() {
610
+ return this.host.proxied?.() ?? false;
611
+ }
612
+ // --- NetPage, for the hub -------------------------------------------
613
+ netEmit(name, arg) {
614
+ this.emit(name, arg);
615
+ }
616
+ netRoutes() {
617
+ return this.routes.length > 0 || Object.keys(this.host.extraHeaders?.() ?? {}).length > 0;
618
+ }
619
+ netExtraHeaders() {
620
+ return this.host.extraHeaders?.() ?? {};
621
+ }
622
+ netFrame(kind, url) {
623
+ if (kind === 'main')
624
+ return this.host.mainFrame?.() ?? null;
625
+ return this.host.childFrame?.(url) ?? null;
626
+ }
627
+ /**
628
+ * A request this page's service worker handed on: the page is
629
+ * controlled and the request comes from its document. WebKit sends
630
+ * the same headers either way, so this is as close as the proxy gets.
631
+ */
632
+ netViaServiceWorker(referer) {
633
+ if (!this.host.swControlled?.())
634
+ return false;
635
+ try {
636
+ return new URL(referer).origin === new URL(this.host.pageURL?.() ?? '').origin;
637
+ }
638
+ catch {
639
+ return false;
640
+ }
641
+ }
642
+ navAborted = false;
643
+ /** A route aborted the last main-frame navigation (read once). */
644
+ abortedNavigation() {
645
+ const v = this.navAborted;
646
+ this.navAborted = false;
647
+ return v;
648
+ }
649
+ netNavAborted() {
650
+ this.navAborted = true;
651
+ }
652
+ /** Proxy mode: the main document's response from the hub, redirect chain and all. */
653
+ async proxiedNavResponse() {
654
+ if (!this.hub)
655
+ return null;
656
+ // Reset in beforeNavigation(); the poll loop may already have seen it.
657
+ await this.hub.drainNow();
658
+ return this.hub.lastNav;
659
+ }
660
+ /** Proxy mode: make sure the hub is attached before a navigation, so it sees the document. */
661
+ async beforeNavigation() {
662
+ if (!this.proxied)
663
+ return;
664
+ this.attachHub();
665
+ this.hub.lastNav = null;
666
+ // Routes or extra headers set before the first page existed: hold requests now.
667
+ await this.hub.sync();
668
+ }
669
+ /** Proxy mode: join the session's hub now (a popup, before its first request). */
670
+ attachHub() {
671
+ if (this.hub)
672
+ return;
673
+ const { sessionId } = this.host.target();
674
+ this.hub = NetHub.for(sessionId, () => this.host.openPoller());
675
+ this.hub.attach(this);
676
+ }
677
+ netIsPopup() {
678
+ return this.host.isPopup?.() ?? false;
679
+ }
680
+ /** Report an event that is not network traffic (popup, close). */
681
+ emitPageEvent(name, arg) {
682
+ this.emit(name, arg);
683
+ }
684
+ /** Whether anyone listens for `name`. */
685
+ hasListeners(name) {
686
+ return (this.listeners.get(name)?.size ?? 0) > 0;
687
+ }
688
+ /**
689
+ * Shim mode: run this page's routes for a main-document navigation
690
+ * to `url`, which the in-page shim cannot see. A fulfilled document
691
+ * is loaded under `url` (vs goto --html); `continue` may change the
692
+ * URL; null means no route decided and the page navigates as usual.
693
+ */
694
+ async routeDocument(url) {
695
+ if (this.proxied || this.routes.length === 0)
696
+ return null;
697
+ const req = new Request({ id: 0, url, method: 'GET', headers: {}, body: null, type: 'document', navigation: true });
698
+ req.frameValue = this.host.mainFrame?.() ?? null;
699
+ let out = null;
700
+ const decide = {
701
+ fulfill: async (status, headers, body) => {
702
+ out = { kind: 'fulfill', status, headers, body, req };
703
+ },
704
+ continue: async (o) => {
705
+ out = { kind: 'continue', url: o.url ?? url };
706
+ },
707
+ abort: async () => {
708
+ out = { kind: 'abort' };
709
+ },
710
+ fetch: async (o) => {
711
+ const r = await fetch(o.url ?? url, {
712
+ method: o.method ?? 'GET',
713
+ headers: { ...this.netExtraHeaders(), ...(o.headers ?? {}) },
714
+ ...(o.postData !== undefined ? { body: o.postData } : {}),
715
+ redirect: 'follow',
716
+ });
717
+ const headers = {};
718
+ r.headers.forEach((v, k) => (headers[k] = v));
719
+ return new APIResponse({ status: r.status, statusText: r.statusText, headers, body: Buffer.from(await r.arrayBuffer()), url: r.url });
720
+ },
721
+ };
722
+ const handled = await this.netHandle(req, decide, {});
723
+ return handled ? out : null;
724
+ }
725
+ async netHandle(req, decide, fallthrough) {
726
+ for (const entry of [...this.routes]) {
727
+ // A handler unrouted by an earlier one no longer runs.
728
+ if (!this.routes.includes(entry))
729
+ continue;
730
+ // After fallback({ url }), later handlers see the new URL.
731
+ if (!urlMatches(entry.matcher, fallthrough.url ?? req.url(), this.host.baseURL))
732
+ continue;
733
+ if (entry.times !== null) {
734
+ entry.times -= 1;
735
+ if (entry.times <= 0)
736
+ this.routes = this.routes.filter((r) => r !== entry);
737
+ }
738
+ const route = new Route(req, async (d) => {
739
+ if (d.kind === 'fulfill') {
740
+ await decide.fulfill(d['status'], d['headers'], Buffer.from(String(d['body'] ?? ''), 'base64'));
741
+ }
742
+ else if (d.kind === 'abort') {
743
+ await decide.abort(String(d['error'] ?? 'failed'));
744
+ }
745
+ else {
746
+ const o = { ...fallthrough };
747
+ if (d['url'])
748
+ o.url = d['url'];
749
+ if (d['method'])
750
+ o.method = d['method'];
751
+ if (d['headers'])
752
+ o.headers = d['headers'];
753
+ if (d['body'] !== undefined)
754
+ o.postData = d['body'];
755
+ await decide.continue(o);
756
+ }
757
+ }, (opts) => decide.fetch({ ...fallthrough, ...opts }));
758
+ try {
759
+ await entry.handler(route, req);
760
+ }
761
+ catch (e) {
762
+ if (!route.handled)
763
+ await decide.abort('failed');
764
+ throw e;
765
+ }
766
+ if (route.fellBack) {
767
+ Object.assign(fallthrough, route.fellBack);
768
+ continue;
769
+ }
770
+ // A handler that returns without deciding leaves the request
771
+ // waiting, as in Playwright (it may decide later).
772
+ return true;
773
+ }
774
+ return false;
775
+ }
776
+ async sync() {
777
+ if (this.proxied) {
778
+ const { sessionId } = this.host.target();
779
+ if (this.active && !this.hub) {
780
+ this.hub = NetHub.for(sessionId, () => this.host.openPoller());
781
+ this.hub.attach(this);
782
+ }
783
+ await this.hub?.sync();
784
+ }
785
+ if (this.active)
786
+ await this.host.ensureShim();
787
+ if (this.routing !== this.routingDefault) {
788
+ // New documents read this before Node has seen them.
789
+ this.routingDefault = this.routing;
790
+ await this.host.addInitScript(`window.__tsRoutingDefault = ${this.routing};`);
791
+ }
792
+ const { pageId, sessionId } = this.host.target();
793
+ if (this.active && !this.timer) {
794
+ this.timer = setInterval(() => void this.tick(), POLL_MS);
795
+ this.timer.unref();
796
+ }
797
+ if (!this.active && this.timer) {
798
+ clearInterval(this.timer);
799
+ this.timer = null;
800
+ }
801
+ if (pageId && this.routingOn !== this.routing) {
802
+ const client = await this.client();
803
+ await client.call('vs_inspect', ['eval', pageId, `window.__ts ? window.__ts.setRouting(${this.routing}) : 'none'`], {
804
+ session: sessionId,
805
+ });
806
+ this.routingOn = this.routing;
807
+ }
808
+ }
809
+ /** A new document starts with routing off; the next sync turns it on again. */
810
+ documentChanged() {
811
+ this.routingOn = false;
812
+ }
813
+ closedEvents = false;
814
+ client() {
815
+ if (this.poller)
816
+ return Promise.resolve(this.poller);
817
+ this.pollerP ??= this.host.openPoller().then((c) => {
818
+ // Closed while the connection was opening: do not keep it.
819
+ if (this.closedEvents) {
820
+ c.close();
821
+ throw new Error('page closed');
822
+ }
823
+ return (this.poller = c);
824
+ });
825
+ return this.pollerP;
826
+ }
827
+ async evalPage(js) {
828
+ const { pageId, sessionId } = this.host.target();
829
+ if (!pageId)
830
+ return null;
831
+ const client = await this.client();
832
+ const resp = await client.call('vs_inspect', ['eval', pageId, `JSON.stringify(${js}) ?? "null"`], {
833
+ session: sessionId,
834
+ full: true,
835
+ });
836
+ const line = resp.body.find((l) => l.startsWith('result='));
837
+ return line === undefined ? null : JSON.parse(line.slice('result='.length));
838
+ }
839
+ tickP = null;
840
+ pendingBindings = [];
841
+ tick() {
842
+ this.tickP ??= this.drain().finally(() => {
843
+ this.tickP = null;
844
+ });
845
+ return this.tickP;
846
+ }
847
+ async drain() {
848
+ try {
849
+ const got = await this.evalPage(`window.__ts ? window.__ts.take() : null`);
850
+ if (!got)
851
+ return;
852
+ for (const e of got.ev)
853
+ this.onEvent(e);
854
+ for (const row of got.q)
855
+ void this.onHeld(row);
856
+ }
857
+ catch {
858
+ /* page closing or navigating; try again next tick */
859
+ }
860
+ }
861
+ get hasBindings() {
862
+ return this.bindings.size > 0;
863
+ }
864
+ /**
865
+ * Take the page's queue now and wait for the exposed functions it
866
+ * called, so a binding fired by an action has run when the action
867
+ * returns, as in Playwright.
868
+ */
869
+ async flush() {
870
+ await this.tick();
871
+ // A binding that itself calls into the page must not wait for itself.
872
+ if (this.bindingDepth > 0)
873
+ return;
874
+ const running = this.pendingBindings.splice(0);
875
+ await Promise.all(running);
876
+ }
877
+ onEvent(e) {
878
+ switch (e.t) {
879
+ case 'call':
880
+ this.pendingBindings.push(this.runBinding(e));
881
+ break;
882
+ case 'console':
883
+ this.emit('console', new ConsoleMessage(e.type ?? 'log', e.text ?? '', (e.args ?? [])));
884
+ break;
885
+ case 'pageerror': {
886
+ const err = new Error(e.message ?? '');
887
+ if (e.stack)
888
+ err.stack = e.stack;
889
+ this.emit('pageerror', err);
890
+ break;
891
+ }
892
+ case 'request': {
893
+ // In proxy mode the hub reports every request; the shim's copy would double it.
894
+ if (this.proxied)
895
+ break;
896
+ const req = new Request({
897
+ id: Number(e.id ?? 0),
898
+ url: e.url ?? '',
899
+ method: e.method ?? 'GET',
900
+ headers: e.headers ?? {},
901
+ body: e.body ?? null,
902
+ type: e.type ?? 'fetch',
903
+ });
904
+ this.requests.set(req.id, req);
905
+ this.emit('request', req);
906
+ break;
907
+ }
908
+ case 'response': {
909
+ if (this.proxied)
910
+ break;
911
+ const req = this.requests.get(Number(e.id ?? -1));
912
+ if (!req)
913
+ break;
914
+ const res = new Response(req, {
915
+ url: e.url ?? req.url(),
916
+ status: e.status ?? 0,
917
+ statusText: e.statusText ?? '',
918
+ headers: e.headers ?? {},
919
+ });
920
+ req.responseValue = res;
921
+ this.emit('response', res);
922
+ this.emit('requestfinished', req);
923
+ this.requests.delete(req.id);
924
+ break;
925
+ }
926
+ case 'requestfailed': {
927
+ if (this.proxied)
928
+ break;
929
+ const req = this.requests.get(Number(e.id ?? -1));
930
+ if (!req)
931
+ break;
932
+ req.failureText = e.failure ?? 'failed';
933
+ this.emit('requestfailed', req);
934
+ this.requests.delete(req.id);
935
+ break;
936
+ }
937
+ }
938
+ }
939
+ async settle(id, d) {
940
+ await this.evalPage(`window.__ts ? window.__ts.settle(${id}, ${JSON.stringify(d)}) : 'gone'`);
941
+ }
942
+ async onHeld(row) {
943
+ if (row.kind === 'fetched') {
944
+ const wait = this.pendingFetch.get(row.id);
945
+ this.pendingFetch.delete(row.id);
946
+ wait?.(row);
947
+ return;
948
+ }
949
+ const req = this.requests.get(row.id) ??
950
+ new Request({ id: row.id, url: row.url, method: row.method, headers: row.headers, body: row.body, type: row.type });
951
+ let continueWith = {};
952
+ for (const entry of [...this.routes]) {
953
+ if (!urlMatches(entry.matcher, req.url(), this.host.baseURL))
954
+ continue;
955
+ if (entry.times !== null) {
956
+ entry.times -= 1;
957
+ if (entry.times <= 0)
958
+ this.routes = this.routes.filter((r) => r !== entry);
959
+ }
960
+ const route = new Route(req, (d) => this.settle(row.id, d), (opts) => this.fetchFor(row.id, { ...continueWith, ...opts }));
961
+ try {
962
+ await entry.handler(route, req);
963
+ }
964
+ catch (e) {
965
+ if (!route.handled)
966
+ await this.settle(row.id, { kind: 'abort' });
967
+ throw e;
968
+ }
969
+ if (route.fellBack) {
970
+ continueWith = { ...continueWith, ...route.fellBack };
971
+ continue;
972
+ }
973
+ if (!route.handled)
974
+ await this.settle(row.id, { kind: 'continue', ...overrides(continueWith) });
975
+ return;
976
+ }
977
+ await this.settle(row.id, { kind: 'continue', ...overrides(continueWith) });
978
+ }
979
+ fetchFor(id, opts) {
980
+ return new Promise((resolve, reject) => {
981
+ this.pendingFetch.set(id, (row) => {
982
+ const r = row.response ?? {};
983
+ if (r.error) {
984
+ reject(new Error(`route.fetch failed: ${r.error}`));
985
+ return;
986
+ }
987
+ resolve(new APIResponse({
988
+ status: r.status ?? 0,
989
+ statusText: r.statusText ?? '',
990
+ headers: r.headers ?? {},
991
+ body: Buffer.from(r.body ?? '', 'base64'),
992
+ url: r.url ?? '',
993
+ }));
994
+ });
995
+ void this.settle(id, { kind: 'fetch', ...overrides(opts) });
996
+ });
997
+ }
998
+ /** Resolve with the first `name` event `predicate` accepts, or reject on timeout. */
999
+ waitFor(name, predicate, timeout) {
1000
+ return new Promise((resolve, reject) => {
1001
+ const fn = (arg) => {
1002
+ void Promise.resolve(predicate(arg)).then((ok) => {
1003
+ if (!ok)
1004
+ return;
1005
+ clearTimeout(timer);
1006
+ this.off(name, fn);
1007
+ void this.sync();
1008
+ resolve(arg);
1009
+ });
1010
+ };
1011
+ const timer = setTimeout(() => {
1012
+ this.off(name, fn);
1013
+ void this.sync();
1014
+ reject(new Error(`waiting for ${name} timed out after ${timeout}ms`));
1015
+ }, timeout);
1016
+ this.on(name, fn);
1017
+ void this.sync();
1018
+ });
1019
+ }
1020
+ close() {
1021
+ this.closedEvents = true;
1022
+ void this.pollerP?.then((c) => c.close(), () => { });
1023
+ this.hub?.detach(this);
1024
+ this.hub = null;
1025
+ if (this.timer)
1026
+ clearInterval(this.timer);
1027
+ this.timer = null;
1028
+ this.routes = [];
1029
+ this.listeners.clear();
1030
+ this.poller?.close();
1031
+ this.poller = null;
1032
+ this.pollerP = null;
1033
+ }
1034
+ }
1035
+ //# sourceMappingURL=events.js.map