"use strict";
const { createHash, randomUUID } = require("node:crypto");
const { appendFileSync, closeSync, fsyncSync, mkdirSync, openSync, statSync, writeFileSync } = require("node:fs");
const { relative, resolve, sep } = require("node:path");
const { Buffer } = require("node:buffer");
const runtime =
globalThis.__SUPERCOV_DIRECT_RUNTIME__ ??
(typeof process !== "undefined" ? process.__SUPERCOV_DIRECT_RUNTIME__ : undefined);
const evidenceDirectory = process.env.SUPERCOV_EVIDENCE_DIR;
function digest(value) {
return createHash("sha256").update(value).digest("hex").slice(0, 24);
}
function localFile(path) {
return relative(process.cwd(), path).split(sep).join("/");
}
function testIdentity(testFile, fullName, occurrence = 0) {
return `jest:${digest(`${testFile}\0${fullName}${occurrence ? `\0${occurrence}` : ""}`)}`;
}
function currentDeclaration() {
const symbol = Object.getOwnPropertySymbols(globalThis)
.find(key => key.description === "JEST_STATE_SYMBOL");
const state = symbol && globalThis[symbol];
if (!state?.currentlyRunningTest || !state.rootDescribeBlock) return undefined;
const names = new Map();
let found;
function visit(block, parents) {
for (const child of block.children ?? []) {
if (child.type === "describeBlock") visit(child, [...parents, child.name]);
else if (child.type === "test") {
const name = [...parents, child.name].join(" ");
const occurrence = names.get(name) ?? 0;
names.set(name, occurrence + 1);
if (child === state.currentlyRunningTest)
found = {
occurrence,
retry: Math.max((child.invocations ?? 1) - 1, 0),
path: [...parents, child.name],
};
}
}
}
visit(state.rootDescribeBlock, []);
return found;
}
const KINDS = [
["unit", /(^|[/_.-])unit([/_.-]|$)/i],
["component", /(^|[/_.-])(component|components|ct)([/_.-]|$)/i],
["integration", /(^|[/_.-])(integration|int)([/_.-]|$)/i],
["e2e", /(^|[/_.-])(e2e|end-to-end|offline|online)([/_.-]|$)/i],
];
function provenance(testFile) {
const explicit = process.env.SUPERCOV_TEST_KIND?.trim();
if (explicit)
return { runner: "jest", kind: explicit.toLowerCase(), source: "explicit" };
const kind = KINDS.find(([, pattern]) => pattern.test(testFile))?.[0];
return kind
? { runner: "jest", kind, source: "path" }
: { runner: "jest", kind: "unit", source: "runner-default" };
}
let journal;
function writeEvidence(payload) {
const line = `${JSON.stringify(payload)}\n`;
if (journal) {
let size = -1;
try {
size = statSync(journal.path).size;
}
catch {
}
if (size !== journal.size)
journal = undefined;
}
if (!journal) {
const directory = resolve(process.cwd(), evidenceDirectory);
mkdirSync(directory, { recursive: true });
const writer = (process.env.SUPERCOV_EXECUTION_LOG_SHARD ?? `pid-${process.pid}`).replace(/[^A-Za-z0-9_-]/g, "_");
journal = { path: resolve(directory, `jest-worker-${writer}-${randomUUID()}.mcdc.jsonl`), size: 0 };
}
if (process.env.SUPERCOV_DURABLE_EVIDENCE_EACH_TEST === "1") {
const descriptor = openSync(journal.path, "a", 0o600);
try {
writeFileSync(descriptor, line);
fsyncSync(descriptor);
}
finally {
closeSync(descriptor);
}
}
else {
appendFileSync(journal.path, line, { mode: 0o600 });
}
journal.size += Buffer.byteLength(line);
}
if (runtime && evidenceDirectory && typeof beforeEach === "function" && typeof afterAll === "function") {
runtime.enableRuntimeSnapshotEvidence();
const attempts = new Map();
const emittedSetupFiles = new Set();
let active;
beforeEach(() => {
flushActive();
const state = expect.getState();
const testFile = localFile(state.testPath ?? "unknown");
if (!emittedSetupFiles.has(testFile)) {
emittedSetupFiles.add(testFile);
const setupSnapshot = runtime.coverageSnapshot();
if (setupSnapshot.hits.length || setupSnapshot.decisions.length) {
writeEvidence({
testId: `jest:${digest(testFile)}:setup`,
test: `${testFile} > module setup`,
testFile,
title: "module setup",
retry: 0,
status: "passed",
provenance: provenance(testFile),
role: "setup",
runtime: [setupSnapshot],
browser: [],
server: [],
});
}
}
const fullName = state.currentTestName ?? "test";
const declaration = currentDeclaration();
const testId = testIdentity(testFile, fullName, declaration?.occurrence);
const retry = declaration?.retry ?? attempts.get(testId) ?? 0;
attempts.set(testId, retry + 1);
const testKey = digest(testId);
const scope = {
version: 1,
runId: process.env.SUPERCOV_RUN_ID ?? "unscoped",
workerId: `jest-${process.env.JEST_WORKER_ID ?? process.pid}`,
testId,
testKey,
retry,
attemptId: `${testKey}-${retry}`,
};
const name = declaration?.path?.join(" > ") ?? fullName;
active = { scope, testFile, fullName, name, retry };
runtime.activateCoverageScope(scope);
runtime.resetCoverage(testId);
});
function flushActive() {
const current = active;
active = undefined;
if (!current)
return;
const { scope } = current;
writeEvidence({
testId: scope.testId,
scope,
test: current.name,
testFile: current.testFile,
title: current.name,
retry: current.retry,
status: "unknown",
provenance: provenance(current.testFile),
phases: runtime.takeNodeAssertionPhases(scope),
runtime: [runtime.coverageSnapshot()],
browser: [],
server: [],
});
runtime.resetCoverage();
runtime.activateCoverageScope();
}
afterAll(flushActive);
}