supercov 0.0.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.
@@ -0,0 +1,1009 @@
1
+ import { createHash } from "node:crypto";
2
+ import childProcess from "node:child_process";
3
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import http from "node:http";
5
+ import https from "node:https";
6
+ import { syncBuiltinESMExports } from "node:module";
7
+ import { dirname, relative, resolve, sep } from "node:path";
8
+ import * as standardPlaywright from "@playwright/test";
9
+ import type {
10
+ APIRequestContext,
11
+ Browser,
12
+ BrowserContext,
13
+ CDPSession,
14
+ Page,
15
+ PlaywrightTestArgs,
16
+ PlaywrightWorkerArgs,
17
+ Route,
18
+ TestInfo,
19
+ TestType,
20
+ Worker,
21
+ } from "@playwright/test";
22
+ import type {
23
+ CoverageExecutionScope,
24
+ CoveragePhase,
25
+ CoverageRuntimeSnapshot,
26
+ McdcRawTestResult,
27
+ } from "./types.ts";
28
+ import { inferTestProvenance } from "./provenance.ts";
29
+ import {
30
+ COVERAGE_PHASE_HEADER,
31
+ COVERAGE_SCOPE_HEADER,
32
+ COVERAGE_CARRIER_ENV,
33
+ encodeCoverageCarrier,
34
+ encodeCoverageScope,
35
+ serverEvidenceDirectory,
36
+ serverEvidencePath,
37
+ } from "./transport.ts";
38
+
39
+ export * from "@playwright/test";
40
+
41
+ type PlaywrightAdapterModule = typeof standardPlaywright & {
42
+ offlineTest?: TestType<Record<string, unknown>, Record<string, unknown>>;
43
+ WebhookBodiesContract?: unknown;
44
+ };
45
+
46
+ const generatedTargetModule = "__SUPERCOV_PLAYWRIGHT_MODULE__";
47
+ const targetModule =
48
+ process.env["SUPERCOV_PLAYWRIGHT_MODULE"] ??
49
+ (generatedTargetModule.startsWith("__")
50
+ ? "@playwright/test"
51
+ : generatedTargetModule);
52
+ const adapter = (
53
+ targetModule === "@playwright/test"
54
+ ? standardPlaywright
55
+ : await import(targetModule)
56
+ ) as PlaywrightAdapterModule;
57
+ type BaseTestArgs = PlaywrightTestArgs & Record<string, unknown>;
58
+ type BaseWorkerArgs = PlaywrightWorkerArgs & Record<string, unknown>;
59
+
60
+ const base = (adapter.offlineTest ?? adapter.test) as TestType<
61
+ BaseTestArgs,
62
+ BaseWorkerArgs
63
+ >;
64
+ const baseExpect = adapter.expect;
65
+
66
+ const GENERATED_EVIDENCE_DIRECTORY =
67
+ "__SUPERCOV_EVIDENCE_DIRECTORY__";
68
+ const GENERATED_RUN_ID = "__SUPERCOV_RUN_ID__";
69
+ const PHASE_STORAGE_KEY = "__supercov_phase";
70
+ const ACTION_METHODS = new Set([
71
+ "blur",
72
+ "check",
73
+ "click",
74
+ "dblclick",
75
+ "dispatchEvent",
76
+ "dragTo",
77
+ "evaluate",
78
+ "evaluateHandle",
79
+ "fill",
80
+ "focus",
81
+ "goBack",
82
+ "goForward",
83
+ "goto",
84
+ "hover",
85
+ "press",
86
+ "reload",
87
+ "selectOption",
88
+ "setInputFiles",
89
+ "tap",
90
+ "type",
91
+ "uncheck",
92
+ ]);
93
+ const REQUEST_METHODS = new Set([
94
+ "delete",
95
+ "fetch",
96
+ "get",
97
+ "head",
98
+ "patch",
99
+ "post",
100
+ "put",
101
+ ]);
102
+
103
+ function isApiRequestContext(value: object): value is APIRequestContext {
104
+ const candidate = value as unknown as Record<string, unknown>;
105
+ return (
106
+ typeof candidate["fetch"] === "function" &&
107
+ typeof candidate["get"] === "function" &&
108
+ typeof candidate["post"] === "function" &&
109
+ typeof candidate["storageState"] === "function"
110
+ );
111
+ }
112
+
113
+ function callerSource(): string | undefined {
114
+ const stack = new Error().stack?.split("\n").slice(2) ?? [];
115
+ const candidate = stack.find(
116
+ (line) =>
117
+ /[/\\]tests[/\\]/.test(line) &&
118
+ !line.includes(".supercov") &&
119
+ !line.includes("node_modules"),
120
+ );
121
+ if (!candidate) return undefined;
122
+ return candidate
123
+ .trim()
124
+ .replace(/^at\s+/, "")
125
+ .replace("file:///workspace/", "")
126
+ .replace("/workspace/", "");
127
+ }
128
+
129
+ class CoveragePhaseController {
130
+ readonly phases: CoveragePhase[] = [];
131
+ private counter = 0;
132
+ private lastActionId: string | undefined;
133
+ private activePhaseId: string | undefined;
134
+ private readonly pages = new Set<Page>();
135
+ private readonly workers = new Set<Worker>();
136
+ private readonly contexts = new Set<BrowserContext>();
137
+ private readonly contextConfiguredHeaders = new Map<BrowserContext, Record<string, string>>();
138
+ private readonly contextRoutes = new Map<BrowserContext, (route: Route) => Promise<void>>();
139
+ private readonly cdpSessions = new Map<Page, CDPSession>();
140
+ private readonly newDocumentScriptIds = new Map<Page, string>();
141
+ private readonly pendingRegistrations = new Set<Promise<void>>();
142
+ private scriptUpdate: Promise<void> = Promise.resolve();
143
+ private readonly proxyCache = new WeakMap<object, object>();
144
+
145
+ // Parameter properties are stateful despite the base ESLint rule treating
146
+ // this as an empty constructor.
147
+ // eslint-disable-next-line no-useless-constructor
148
+ constructor(
149
+ readonly scope: CoverageExecutionScope,
150
+ private readonly configuredHeaders: Record<string, string> = {},
151
+ ) {}
152
+
153
+ allPages(): Page[] {
154
+ return [...this.pages];
155
+ }
156
+
157
+ allWorkers(): Worker[] {
158
+ return [...this.workers];
159
+ }
160
+
161
+ async registerPage(page: Page): Promise<void> {
162
+ if (this.pages.has(page)) return;
163
+ this.pages.add(page);
164
+ await this.registerContext(page.context());
165
+ const cdp = await page.context().newCDPSession(page).catch(() => undefined);
166
+ if (cdp) this.cdpSessions.set(page, cdp);
167
+ const phaseId = this.requestPhaseId();
168
+ if (phaseId) await this.activatePage(page, phaseId);
169
+ page.on("worker", (worker) => {
170
+ void this.registerWorker(worker);
171
+ });
172
+ for (const worker of page.workers()) void this.registerWorker(worker);
173
+ }
174
+
175
+ async registerContext(
176
+ context: BrowserContext,
177
+ configuredHeaders: Record<string, string> = this.configuredHeaders,
178
+ ): Promise<void> {
179
+ if (this.contexts.has(context)) return;
180
+ this.contexts.add(context);
181
+ this.contextConfiguredHeaders.set(context, configuredHeaders);
182
+ await context.addInitScript(
183
+ ({ attemptId, scopeHeader, scopeValue }) => {
184
+ (
185
+ globalThis as typeof globalThis & {
186
+ __SUPERCOV_MCDC_TEST_ID__?: string;
187
+ }
188
+ ).__SUPERCOV_MCDC_TEST_ID__ = attemptId;
189
+ try {
190
+ const originalFetch = globalThis.fetch?.bind(globalThis);
191
+ if (originalFetch) {
192
+ globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
193
+ const headers = new Headers(
194
+ init?.headers ??
195
+ (input instanceof Request ? input.headers : undefined),
196
+ );
197
+ headers.set(scopeHeader, scopeValue);
198
+ const phase = (
199
+ globalThis as typeof globalThis & {
200
+ __SUPERCOV_PHASE_ID__?: string;
201
+ }
202
+ ).__SUPERCOV_PHASE_ID__;
203
+ if (phase) headers.set("x-supercov-phase", phase);
204
+ return originalFetch(input, { ...init, headers });
205
+ }) as typeof globalThis.fetch;
206
+ }
207
+ } catch {
208
+ // Browser instrumentation must not change application behavior.
209
+ }
210
+ },
211
+ {
212
+ attemptId: this.scope.attemptId,
213
+ scopeHeader: COVERAGE_SCOPE_HEADER,
214
+ scopeValue: encodeCoverageScope(this.scope),
215
+ },
216
+ );
217
+ const attachPhase = async (route: Route): Promise<void> => {
218
+ const phaseId = this.requestPhaseId();
219
+ await route.continue({
220
+ headers: {
221
+ ...route.request().headers(),
222
+ [COVERAGE_SCOPE_HEADER]: encodeCoverageScope(this.scope),
223
+ ...(phaseId ? { [COVERAGE_PHASE_HEADER]: phaseId } : {}),
224
+ },
225
+ });
226
+ };
227
+ this.contextRoutes.set(context, attachPhase);
228
+ await context.route("**/*", attachPhase);
229
+ const register = (page: Page): void => {
230
+ const pending = this.registerPage(page).finally(() =>
231
+ this.pendingRegistrations.delete(pending),
232
+ );
233
+ this.pendingRegistrations.add(pending);
234
+ };
235
+ context.on("page", register);
236
+ context.on("serviceworker", (worker: Worker) => {
237
+ void this.registerWorker(worker);
238
+ });
239
+ for (const worker of context.serviceWorkers()) void this.registerWorker(worker);
240
+ await this.updateContextHeaders(context, this.requestPhaseId());
241
+ for (const page of context.pages()) register(page);
242
+ }
243
+
244
+ private async registerWorker(worker: Worker): Promise<void> {
245
+ if (this.workers.has(worker)) return;
246
+ this.workers.add(worker);
247
+ const phaseId = this.requestPhaseId();
248
+ await worker
249
+ .evaluate(
250
+ ({ attemptId, scopeHeader, scopeValue, phaseHeader, phase }) => {
251
+ (
252
+ globalThis as typeof globalThis & {
253
+ __SUPERCOV_MCDC_TEST_ID__?: string;
254
+ __SUPERCOV_PHASE_ID__?: string;
255
+ }
256
+ ).__SUPERCOV_MCDC_TEST_ID__ = attemptId;
257
+ if (phase)
258
+ (
259
+ globalThis as typeof globalThis & {
260
+ __SUPERCOV_PHASE_ID__?: string;
261
+ }
262
+ ).__SUPERCOV_PHASE_ID__ = phase;
263
+ const originalFetch = globalThis.fetch?.bind(globalThis);
264
+ if (!originalFetch) return;
265
+ globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
266
+ const headers = new Headers(
267
+ init?.headers ??
268
+ (input instanceof Request ? input.headers : undefined),
269
+ );
270
+ headers.set(scopeHeader, scopeValue);
271
+ if (phase) headers.set(phaseHeader, phase);
272
+ return originalFetch(input, { ...init, headers });
273
+ }) as typeof globalThis.fetch;
274
+ },
275
+ {
276
+ attemptId: this.scope.attemptId,
277
+ scopeHeader: COVERAGE_SCOPE_HEADER,
278
+ scopeValue: encodeCoverageScope(this.scope),
279
+ phaseHeader: COVERAGE_PHASE_HEADER,
280
+ phase: phaseId,
281
+ },
282
+ )
283
+ .catch(() => undefined);
284
+ }
285
+
286
+ async beginAction(operation: string): Promise<CoveragePhase> {
287
+ const phase = this.createPhase("action", operation);
288
+ this.lastActionId = phase.id;
289
+ this.activePhaseId = phase.id;
290
+ await this.activateInBrowser(phase.id);
291
+ return phase;
292
+ }
293
+
294
+ beginAssertion(operation: string): CoveragePhase {
295
+ const phase = this.createPhase("assertion", operation, this.lastActionId);
296
+ this.activePhaseId = phase.id;
297
+ // Playwright queues browser protocol commands in order. Starting this
298
+ // evaluation before an async locator assertion is sufficient to tag its
299
+ // polling work without turning synchronous expect matchers into promises.
300
+ void this.activateInBrowser(phase.id);
301
+ return phase;
302
+ }
303
+
304
+ requestPhaseId(): string | undefined {
305
+ return this.activePhaseId;
306
+ }
307
+
308
+ async dispose(): Promise<void> {
309
+ await Promise.all([...this.pendingRegistrations]);
310
+ await this.scriptUpdate;
311
+ for (const [page, cdp] of this.cdpSessions) {
312
+ const identifier = this.newDocumentScriptIds.get(page);
313
+ if (identifier) await cdp
314
+ .send("Page.removeScriptToEvaluateOnNewDocument", {
315
+ identifier,
316
+ })
317
+ .catch(() => undefined);
318
+ await cdp.detach().catch(() => undefined);
319
+ }
320
+ for (const [context, route] of this.contextRoutes)
321
+ await context.unroute("**/*", route).catch(() => undefined);
322
+ }
323
+
324
+ finish(phase: CoveragePhase, error?: unknown): void {
325
+ phase.endedAtMs = Date.now();
326
+ phase.status = error === undefined ? "passed" : "failed";
327
+ if (error !== undefined)
328
+ phase.error = error instanceof Error ? error.message : String(error);
329
+ }
330
+
331
+ wrap<T extends object>(target: T): T {
332
+ const cached = this.proxyCache.get(target);
333
+ if (cached) return cached as T;
334
+ const proxy = new Proxy(target, {
335
+ get: (object, property, receiver) => {
336
+ if (property === "then") return undefined;
337
+ // Playwright's locator matchers validate `receiver.constructor.name`.
338
+ // Preserve the native constructor rather than wrapping it as a method.
339
+ if (property === "constructor") return object.constructor;
340
+ const value = Reflect.get(object, property, receiver) as unknown;
341
+ if (typeof value !== "function") return value;
342
+ const method = String(property);
343
+ return (...args: unknown[]) => {
344
+ const isRequest = REQUEST_METHODS.has(method) &&
345
+ isApiRequestContext(object);
346
+ if (ACTION_METHODS.has(method) || isRequest) {
347
+ return (async () => {
348
+ const operation = `${object.constructor?.name ?? "Playwright"}.${method}`;
349
+ const phase = await this.beginAction(operation);
350
+ try {
351
+ const result = await Reflect.apply(
352
+ value as (...innerArgs: unknown[]) => unknown,
353
+ object,
354
+ isRequest ? this.scopeApiRequest(args) : args,
355
+ );
356
+ this.finish(phase);
357
+ return this.prepareResult(result);
358
+ } catch (error) {
359
+ this.finish(phase, error);
360
+ throw error;
361
+ }
362
+ })();
363
+ }
364
+ const invokedArgs =
365
+ method === "newContext" && object.constructor?.name === "Browser"
366
+ ? this.scopeBrowserContext(args)
367
+ : args;
368
+ const result = Reflect.apply(
369
+ value as (...innerArgs: unknown[]) => unknown,
370
+ object,
371
+ invokedArgs,
372
+ );
373
+ return this.wrapResult(result, method === "newContext" ? invokedArgs : undefined);
374
+ };
375
+ },
376
+ });
377
+ this.proxyCache.set(target, proxy);
378
+ return proxy;
379
+ }
380
+
381
+ private createPhase(
382
+ kind: CoveragePhase["kind"],
383
+ operation: string,
384
+ causedByPhaseId?: string,
385
+ ): CoveragePhase {
386
+ const source = callerSource();
387
+ const phase: CoveragePhase = {
388
+ id: `${this.scope.attemptId}:phase:${++this.counter}`,
389
+ kind,
390
+ operation,
391
+ ...(source ? { source } : {}),
392
+ ...(causedByPhaseId ? { causedByPhaseId } : {}),
393
+ startedAtMs: Date.now(),
394
+ };
395
+ this.phases.push(phase);
396
+ return phase;
397
+ }
398
+
399
+ private wrapResult(result: unknown, sourceArgs?: unknown[]): unknown {
400
+ if (result instanceof Promise)
401
+ return result.then((resolved) => this.prepareResult(resolved, sourceArgs));
402
+ if (
403
+ result === null ||
404
+ typeof result !== "object" ||
405
+ Array.isArray(result) ||
406
+ ArrayBuffer.isView(result)
407
+ )
408
+ return result;
409
+ return this.wrap(result);
410
+ }
411
+
412
+ private async prepareResult(
413
+ result: unknown,
414
+ sourceArgs?: unknown[],
415
+ ): Promise<unknown> {
416
+ if (
417
+ !result ||
418
+ typeof result !== "object" ||
419
+ Array.isArray(result) ||
420
+ ArrayBuffer.isView(result)
421
+ )
422
+ return result;
423
+ const candidate = result as Record<string, unknown>;
424
+ if (
425
+ typeof candidate["pages"] === "function" &&
426
+ typeof candidate["route"] === "function"
427
+ )
428
+ await this.registerContext(
429
+ result as BrowserContext,
430
+ ((sourceArgs?.[0] as { extraHTTPHeaders?: Record<string, string> } | undefined)
431
+ ?.extraHTTPHeaders ?? this.configuredHeaders),
432
+ );
433
+ if (
434
+ typeof candidate["frames"] === "function" &&
435
+ typeof candidate["context"] === "function"
436
+ )
437
+ await this.registerPage(result as Page);
438
+ return this.wrap(result);
439
+ }
440
+
441
+ private scopeApiRequest(args: unknown[]): unknown[] {
442
+ const scoped = [...args];
443
+ const optionIndex = 1;
444
+ const phaseId = this.requestPhaseId();
445
+ const coverageHeaders = {
446
+ [COVERAGE_SCOPE_HEADER]: encodeCoverageScope(this.scope),
447
+ ...(phaseId ? { [COVERAGE_PHASE_HEADER]: phaseId } : {}),
448
+ };
449
+ const options =
450
+ scoped[optionIndex] && typeof scoped[optionIndex] === "object"
451
+ ? (scoped[optionIndex] as { headers?: unknown })
452
+ : {};
453
+ scoped[optionIndex] = {
454
+ ...options,
455
+ headers: mergeRequestHeaders(
456
+ options.headers,
457
+ coverageHeaders,
458
+ ),
459
+ };
460
+ return scoped;
461
+ }
462
+
463
+ private scopeBrowserContext(args: unknown[]): unknown[] {
464
+ const scoped = [...args];
465
+ const options =
466
+ scoped[0] && typeof scoped[0] === "object"
467
+ ? (scoped[0] as { extraHTTPHeaders?: Record<string, string> })
468
+ : {};
469
+ scoped[0] = {
470
+ ...options,
471
+ extraHTTPHeaders: {
472
+ ...(options.extraHTTPHeaders ?? {}),
473
+ ...(activeCoverageHeaders() ?? {}),
474
+ },
475
+ };
476
+ return scoped;
477
+ }
478
+
479
+ private async activateInBrowser(phaseId: string): Promise<void> {
480
+ await Promise.all(
481
+ [...this.contexts].map((context) =>
482
+ this.updateContextHeaders(context, phaseId),
483
+ ),
484
+ );
485
+ await Promise.all(
486
+ [...this.pages].flatMap((page) => page.frames()).map((frame) =>
487
+ frame
488
+ .evaluate(
489
+ ({ id, storageKey }) => {
490
+ (
491
+ globalThis as typeof globalThis & {
492
+ __SUPERCOV_PHASE_ID__?: string;
493
+ }
494
+ ).__SUPERCOV_PHASE_ID__ = id;
495
+ try {
496
+ localStorage.setItem(storageKey, id);
497
+ } catch {
498
+ // Sandboxed/cross-origin frames may not expose localStorage.
499
+ }
500
+ },
501
+ { id: phaseId, storageKey: PHASE_STORAGE_KEY },
502
+ )
503
+ .catch(() => undefined),
504
+ ),
505
+ );
506
+ await Promise.all(
507
+ [...this.workers].map((worker) =>
508
+ worker
509
+ .evaluate((id) => {
510
+ (
511
+ globalThis as typeof globalThis & {
512
+ __SUPERCOV_PHASE_ID__?: string;
513
+ }
514
+ ).__SUPERCOV_PHASE_ID__ = id;
515
+ }, phaseId)
516
+ .catch(() => undefined),
517
+ ),
518
+ );
519
+ await Promise.all([...this.pages].map((page) => this.activatePage(page, phaseId)));
520
+ }
521
+
522
+ private async updateContextHeaders(
523
+ context: BrowserContext,
524
+ phaseId?: string,
525
+ ): Promise<void> {
526
+ await context
527
+ .setExtraHTTPHeaders({
528
+ ...(this.contextConfiguredHeaders.get(context) ?? this.configuredHeaders),
529
+ [COVERAGE_SCOPE_HEADER]: encodeCoverageScope(this.scope),
530
+ ...(phaseId ? { [COVERAGE_PHASE_HEADER]: phaseId } : {}),
531
+ })
532
+ .catch(() => undefined);
533
+ }
534
+
535
+ private async activatePage(page: Page, phaseId: string): Promise<void> {
536
+ const cdp = this.cdpSessions.get(page);
537
+ if (!cdp) return;
538
+ this.scriptUpdate = this.scriptUpdate.then(async () => {
539
+ const previous = this.newDocumentScriptIds.get(page);
540
+ if (previous) {
541
+ await cdp.send("Page.removeScriptToEvaluateOnNewDocument", {
542
+ identifier: previous,
543
+ }).catch(() => undefined);
544
+ }
545
+ const installed = (await cdp
546
+ .send("Page.addScriptToEvaluateOnNewDocument", {
547
+ source: `globalThis.__SUPERCOV_PHASE_ID__=${JSON.stringify(phaseId)};`,
548
+ runImmediately: true,
549
+ })
550
+ .catch(() => undefined)) as { identifier?: string } | undefined;
551
+ if (installed?.identifier)
552
+ this.newDocumentScriptIds.set(page, installed.identifier);
553
+ });
554
+ await this.scriptUpdate.catch(() => undefined);
555
+ }
556
+ }
557
+
558
+ let activeController: CoveragePhaseController | undefined;
559
+ const controllers = new Map<string, CoveragePhaseController>();
560
+
561
+ function activeCoverageHeaders(): Record<string, string> | undefined {
562
+ const controller = activeController;
563
+ if (!controller) return undefined;
564
+ const phaseId = controller.requestPhaseId();
565
+ return {
566
+ [COVERAGE_SCOPE_HEADER]: encodeCoverageScope(controller.scope),
567
+ ...(phaseId ? { [COVERAGE_PHASE_HEADER]: phaseId } : {}),
568
+ };
569
+ }
570
+
571
+ function mergeRequestHeaders(
572
+ existing: unknown,
573
+ coverage: Record<string, string>,
574
+ ): Record<string, unknown> {
575
+ if (existing instanceof Headers) {
576
+ return { ...Object.fromEntries(existing.entries()), ...coverage };
577
+ }
578
+ if (Array.isArray(existing)) {
579
+ const normalized: Record<string, unknown> = {};
580
+ for (let index = 0; index + 1 < existing.length; index += 2) {
581
+ normalized[String(existing[index])] = existing[index + 1];
582
+ }
583
+ return { ...normalized, ...coverage };
584
+ }
585
+ return {
586
+ ...(existing && typeof existing === "object" ? existing : {}),
587
+ ...coverage,
588
+ };
589
+ }
590
+
591
+ function scopedNodeRequestArguments(args: unknown[]): unknown[] {
592
+ const coverage = activeCoverageHeaders();
593
+ if (!coverage || args.length === 0) return args;
594
+ const scoped = [...args];
595
+ const first = scoped[0];
596
+ const startsWithUrl = typeof first === "string" || first instanceof URL;
597
+ const candidate = startsWithUrl ? scoped[1] : first;
598
+ const hasOptions =
599
+ candidate !== null &&
600
+ typeof candidate === "object" &&
601
+ !(candidate instanceof URL);
602
+ if (hasOptions) {
603
+ const index = startsWithUrl ? 1 : 0;
604
+ const options = candidate as { headers?: unknown };
605
+ scoped[index] = {
606
+ ...options,
607
+ headers: mergeRequestHeaders(options.headers, coverage),
608
+ };
609
+ } else if (startsWithUrl) {
610
+ scoped.splice(1, 0, { headers: coverage });
611
+ }
612
+ return scoped;
613
+ }
614
+
615
+ function installNodeRequestScopePropagation(): void {
616
+ const originalHttpRequest = http.request;
617
+ const originalHttpGet = http.get;
618
+ const originalHttpsRequest = https.request;
619
+ const originalHttpsGet = https.get;
620
+ http.request = ((...args: unknown[]) =>
621
+ Reflect.apply(originalHttpRequest, http, scopedNodeRequestArguments(args))) as typeof http.request;
622
+ http.get = ((...args: unknown[]) =>
623
+ Reflect.apply(originalHttpGet, http, scopedNodeRequestArguments(args))) as typeof http.get;
624
+ https.request = ((...args: unknown[]) =>
625
+ Reflect.apply(originalHttpsRequest, https, scopedNodeRequestArguments(args))) as typeof https.request;
626
+ https.get = ((...args: unknown[]) =>
627
+ Reflect.apply(originalHttpsGet, https, scopedNodeRequestArguments(args))) as typeof https.get;
628
+ // Existing ESM named imports such as `import { request } from "node:http"`
629
+ // must observe the patched CommonJS-compatible builtin exports too.
630
+ syncBuiltinESMExports();
631
+
632
+ if (typeof globalThis.fetch === "function") {
633
+ const originalFetch = globalThis.fetch.bind(globalThis);
634
+ globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
635
+ const coverage = activeCoverageHeaders();
636
+ if (!coverage) return originalFetch(input, init);
637
+ const headers = new Headers(
638
+ init?.headers ?? (input instanceof Request ? input.headers : undefined),
639
+ );
640
+ for (const [name, value] of Object.entries(coverage))
641
+ headers.set(name, value);
642
+ return originalFetch(input, { ...init, headers });
643
+ }) as typeof globalThis.fetch;
644
+ }
645
+ }
646
+
647
+ installNodeRequestScopePropagation();
648
+
649
+ function scopedChildOptions(
650
+ args: unknown[],
651
+ optionIndex: number,
652
+ ): unknown[] {
653
+ const controller = activeController;
654
+ if (!controller) return args;
655
+ const scoped = [...args];
656
+ const existing =
657
+ scoped[optionIndex] && typeof scoped[optionIndex] === "object"
658
+ ? (scoped[optionIndex] as { env?: NodeJS.ProcessEnv })
659
+ : {};
660
+ const options = {
661
+ ...existing,
662
+ env: {
663
+ ...process.env,
664
+ ...(existing.env ?? {}),
665
+ SUPERCOV_RUN_ID: controller.scope.runId,
666
+ [COVERAGE_CARRIER_ENV]: encodeCoverageCarrier({
667
+ version: 1,
668
+ scope: controller.scope,
669
+ ...(controller.requestPhaseId()
670
+ ? { phaseId: controller.requestPhaseId() }
671
+ : {}),
672
+ }),
673
+ },
674
+ };
675
+ if (typeof scoped[optionIndex] === "function")
676
+ scoped.splice(optionIndex, 0, options);
677
+ else scoped[optionIndex] = options;
678
+ return scoped;
679
+ }
680
+
681
+ function childOptionIndex(
682
+ method: string,
683
+ args: unknown[],
684
+ ): number {
685
+ if (method === "spawn" || method === "spawnSync" || method === "fork")
686
+ return Array.isArray(args[1]) ? 2 : 1;
687
+ if (method === "execFile" || method === "execFileSync")
688
+ return Array.isArray(args[1]) ? 2 : 1;
689
+ return 1;
690
+ }
691
+
692
+ function installChildProcessScopePropagation(): void {
693
+ for (const method of [
694
+ "exec",
695
+ "execFile",
696
+ "execFileSync",
697
+ "execSync",
698
+ "fork",
699
+ "spawn",
700
+ "spawnSync",
701
+ ] as const) {
702
+ const original = childProcess[method] as unknown as (
703
+ ...args: unknown[]
704
+ ) => unknown;
705
+ (childProcess as unknown as Record<string, unknown>)[method] = function (
706
+ ...args: unknown[]
707
+ ): unknown {
708
+ return Reflect.apply(
709
+ original,
710
+ childProcess,
711
+ scopedChildOptions(args, childOptionIndex(method, args)),
712
+ );
713
+ };
714
+ }
715
+ syncBuiltinESMExports();
716
+ }
717
+
718
+ installChildProcessScopePropagation();
719
+
720
+ function wrapMatchers<T extends object>(matchers: T, path = "expect"): T {
721
+ return new Proxy(matchers, {
722
+ get(target, property, receiver) {
723
+ const value = Reflect.get(target, property, receiver) as unknown;
724
+ const name = String(property);
725
+ if (value && typeof value === "object")
726
+ return wrapMatchers(value, `${path}.${name}`);
727
+ if (typeof value !== "function") return value;
728
+ return (...args: unknown[]) => {
729
+ const controller = activeController;
730
+ const phase = controller?.beginAssertion(`${path}.${name}`);
731
+ try {
732
+ const result = Reflect.apply(
733
+ value as (...innerArgs: unknown[]) => unknown,
734
+ target,
735
+ args,
736
+ );
737
+ if (result instanceof Promise) {
738
+ return result.then(
739
+ (resolved) => {
740
+ if (phase && controller) controller.finish(phase);
741
+ return resolved;
742
+ },
743
+ (error) => {
744
+ if (phase && controller) controller.finish(phase, error);
745
+ throw error;
746
+ },
747
+ );
748
+ }
749
+ if (phase && controller) controller.finish(phase);
750
+ return result;
751
+ } catch (error) {
752
+ if (phase && controller) controller.finish(phase, error);
753
+ throw error;
754
+ }
755
+ };
756
+ },
757
+ });
758
+ }
759
+
760
+ function wrapExpectCallable<T extends (...args: never[]) => unknown>(
761
+ callable: T,
762
+ ): T {
763
+ return new Proxy(callable, {
764
+ apply(target, thisArg, argumentsList) {
765
+ const result = Reflect.apply(target, thisArg, argumentsList) as unknown;
766
+ if (typeof result === "function") return wrapExpectCallable(result as T);
767
+ if (result && typeof result === "object") return wrapMatchers(result);
768
+ return result;
769
+ },
770
+ get(target, property, receiver) {
771
+ const value = Reflect.get(target, property, receiver) as unknown;
772
+ if (typeof value !== "function") return value;
773
+ return wrapExpectCallable(value.bind(target) as T);
774
+ },
775
+ });
776
+ }
777
+
778
+ export const expect = wrapExpectCallable(
779
+ baseExpect as unknown as (...args: never[]) => unknown,
780
+ ) as typeof baseExpect;
781
+
782
+ function currentRunId(): string {
783
+ return (
784
+ process.env["SUPERCOV_RUN_ID"] ??
785
+ (GENERATED_RUN_ID.startsWith("__") ? "unscoped" : GENERATED_RUN_ID)
786
+ );
787
+ }
788
+
789
+ function executionScope(testInfo: {
790
+ testId: string;
791
+ retry: number;
792
+ workerIndex: number;
793
+ }): CoverageExecutionScope {
794
+ const runId = currentRunId();
795
+ const workerId = `pid-${process.pid}-worker-${testInfo.workerIndex}`;
796
+ const testKey = createHash("sha256")
797
+ .update(testInfo.testId)
798
+ .digest("hex")
799
+ .slice(0, 24);
800
+ const attemptId = createHash("sha256")
801
+ .update(`${runId}\0${workerId}\0${testInfo.testId}\0${testInfo.retry}`)
802
+ .digest("hex")
803
+ .slice(0, 24);
804
+ return {
805
+ version: 1,
806
+ runId,
807
+ workerId,
808
+ testId: testInfo.testId,
809
+ testKey,
810
+ retry: testInfo.retry,
811
+ attemptId,
812
+ };
813
+ }
814
+
815
+ function readServerRecords(
816
+ scope: CoverageExecutionScope,
817
+ ): McdcRawTestResult["server"] {
818
+ try {
819
+ return readFileSync(serverEvidencePath(scope), "utf8")
820
+ .split("\n")
821
+ .filter(Boolean)
822
+ .flatMap((line) => {
823
+ try {
824
+ const record = JSON.parse(
825
+ line,
826
+ ) as McdcRawTestResult["server"][number];
827
+ return record.scope?.attemptId === scope.attemptId ? [record] : [];
828
+ } catch {
829
+ // Ignore a final partial line if the server was writing during collection.
830
+ return [];
831
+ }
832
+ });
833
+ } catch {
834
+ return [];
835
+ }
836
+ }
837
+
838
+ const instrumentedTest = base.extend<{ mcdcAutoCollect: void }>({
839
+ page: async ({ page }, use, testInfo) => {
840
+ const scope = executionScope(testInfo);
841
+ const configuredHeaders = Object.fromEntries(
842
+ Object.entries(testInfo.project.use.extraHTTPHeaders ?? {}).map(
843
+ ([name, value]) => [name, String(value)],
844
+ ),
845
+ );
846
+ const controller = new CoveragePhaseController(
847
+ scope,
848
+ configuredHeaders,
849
+ );
850
+ controllers.set(scope.attemptId, controller);
851
+ activeController = controller;
852
+ await controller.registerPage(page);
853
+ try {
854
+ await use(controller.wrap(page));
855
+ } finally {
856
+ await controller.dispose();
857
+ if (activeController === controller) activeController = undefined;
858
+ controllers.delete(scope.attemptId);
859
+ }
860
+ },
861
+ browser: [
862
+ async ({ browser }, use) => {
863
+ await use(
864
+ new Proxy(browser, {
865
+ get(target, property, receiver) {
866
+ const controller = activeController;
867
+ return controller
868
+ ? Reflect.get(controller.wrap(target), property, receiver)
869
+ : Reflect.get(target, property, receiver);
870
+ },
871
+ }) as Browser,
872
+ );
873
+ },
874
+ { scope: "worker" },
875
+ ],
876
+ request: async ({ request }, use) => {
877
+ await use(
878
+ new Proxy(request, {
879
+ get(target, property, receiver) {
880
+ const controller = activeController;
881
+ return controller
882
+ ? Reflect.get(controller.wrap(target), property, receiver)
883
+ : Reflect.get(target, property, receiver);
884
+ },
885
+ }) as APIRequestContext,
886
+ );
887
+ },
888
+ mcdcAutoCollect: [
889
+ async (
890
+ { page }: { page: Page },
891
+ use: (value: void) => Promise<void>,
892
+ testInfo: TestInfo,
893
+ ) => {
894
+ const scope = executionScope(testInfo);
895
+ const serverOutput = serverEvidencePath(scope);
896
+ mkdirSync(serverEvidenceDirectory(scope), { recursive: true });
897
+ rmSync(serverOutput, { force: true });
898
+
899
+ try {
900
+ await use();
901
+ } finally {
902
+ const controller = controllers.get(scope.attemptId);
903
+ const browser: CoverageRuntimeSnapshot[] = [];
904
+ const pages = controller?.allPages() ?? [page];
905
+ for (const currentPage of pages) {
906
+ for (const frame of currentPage.frames()) {
907
+ const frameSnapshot = await frame
908
+ .evaluate(() => {
909
+ const getSnapshot = (
910
+ globalThis as typeof globalThis & {
911
+ __SUPERCOV_COVERAGE_SNAPSHOT__?: () => CoverageRuntimeSnapshot;
912
+ }
913
+ ).__SUPERCOV_COVERAGE_SNAPSHOT__;
914
+ return getSnapshot?.() ?? { decisions: [], hits: [], events: [] };
915
+ })
916
+ .catch(
917
+ () =>
918
+ ({
919
+ decisions: [],
920
+ hits: [],
921
+ events: [],
922
+ }) as CoverageRuntimeSnapshot,
923
+ );
924
+ browser.push(frameSnapshot);
925
+ }
926
+ }
927
+ for (const worker of controller?.allWorkers() ?? []) {
928
+ const workerSnapshot = await worker
929
+ .evaluate(() => {
930
+ const getSnapshot = (
931
+ globalThis as typeof globalThis & {
932
+ __SUPERCOV_COVERAGE_SNAPSHOT__?: () => CoverageRuntimeSnapshot;
933
+ }
934
+ ).__SUPERCOV_COVERAGE_SNAPSHOT__;
935
+ return getSnapshot?.() ?? { decisions: [], hits: [], events: [] };
936
+ })
937
+ .catch(
938
+ () =>
939
+ ({
940
+ decisions: [],
941
+ hits: [],
942
+ events: [],
943
+ }) as CoverageRuntimeSnapshot,
944
+ );
945
+ browser.push(workerSnapshot);
946
+ }
947
+
948
+ const server = readServerRecords(scope);
949
+ // Emit an artifact even when this test touched no application source.
950
+ // A complete test-to-coverage matrix must also identify tests that are
951
+ // removable without changing coverage.
952
+ const outputPath = testInfo.outputPath("mcdc.json");
953
+ mkdirSync(dirname(outputPath), { recursive: true });
954
+ const testFile = relative(process.cwd(), testInfo.file)
955
+ .split(sep)
956
+ .join("/");
957
+ const payload: McdcRawTestResult = {
958
+ testId: testInfo.testId,
959
+ scope,
960
+ test: testInfo.titlePath.join(" > "),
961
+ testFile,
962
+ title: testInfo.title,
963
+ retry: testInfo.retry,
964
+ status: testInfo.status ?? "unknown",
965
+ expectedStatus: testInfo.expectedStatus,
966
+ provenance: inferTestProvenance({
967
+ runner: "playwright",
968
+ file: testFile,
969
+ project: testInfo.project.name,
970
+ explicitKind: process.env["SUPERCOV_TEST_KIND"],
971
+ }),
972
+ phases: controller?.phases ?? [],
973
+ browser,
974
+ server,
975
+ };
976
+ const serialized = `${JSON.stringify(payload)}\n`;
977
+ writeFileSync(outputPath, serialized);
978
+
979
+ // Pool runners may cycle-restore a VM immediately after Playwright
980
+ // exits, which can discard or overwrite the normal artifact copy.
981
+ // Write one uniquely named, one-shot evidence file to the runner's
982
+ // shared directory as well. No test streams into this path.
983
+ const evidenceDirectory =
984
+ process.env["SUPERCOV_EVIDENCE_DIR"] ??
985
+ (GENERATED_EVIDENCE_DIRECTORY.startsWith("__")
986
+ ? undefined
987
+ : GENERATED_EVIDENCE_DIRECTORY);
988
+ if (evidenceDirectory) {
989
+ const resolvedDirectory = resolve(process.cwd(), evidenceDirectory);
990
+ const safeTestId = testInfo.testId.replace(/[^a-zA-Z0-9_-]/g, "_");
991
+ const testEvidenceDirectory = resolve(
992
+ resolvedDirectory,
993
+ `${safeTestId}-${testInfo.retry}`,
994
+ );
995
+ mkdirSync(testEvidenceDirectory, { recursive: true });
996
+ writeFileSync(
997
+ resolve(testEvidenceDirectory, "mcdc.json"),
998
+ serialized,
999
+ );
1000
+ }
1001
+ }
1002
+ },
1003
+ { auto: true },
1004
+ ],
1005
+ });
1006
+
1007
+ export const test = instrumentedTest;
1008
+ export const offlineTest = instrumentedTest;
1009
+ export const WebhookBodiesContract = adapter.WebhookBodiesContract;