var __defProp = Object.defineProperty; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; // The runtime runs inside the application under test, and its tests may // pollute Object.prototype on purpose: axios's set `Object.prototype.get`, and // a descriptor that inherits `get` makes defineProperty throw "Getter must be a // function", failing tests that pass without Supercov. Every descriptor here has // no prototype, and spreading copies values rather than descriptors. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { __proto__: null, enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; var __spreadProps = (a, b) => __spreadValues(a, b); // Buffer as it was when Supercov loaded. Tests replace globals -- axios's set // `globalThis.Buffer = undefined` to check it copes -- and the runtime runs // inside those tests; it must not fail where the application does not. var capturedBuffer = typeof Buffer === "undefined" ? void 0 : Buffer; // dist/transport.js var COVERAGE_SCOPE_HEADER = "x-supercov-scope"; var COVERAGE_PHASE_HEADER = "x-supercov-phase"; var COVERAGE_SCOPE_COOKIE = "__supercov_scope"; var COVERAGE_PHASE_COOKIE = "__supercov_phase"; var COVERAGE_SCOPE_SITE_COOKIE = "__supercov_scope_site"; var COVERAGE_PHASE_SITE_COOKIE = "__supercov_phase_site"; var COVERAGE_CARRIER_ENV = "SUPERCOV_CONTEXT"; var DEFAULT_SERVER_EVIDENCE_ROOT = "/tmp/supercov-server-evidence"; function configuredServerEvidenceRoot() { var _a8; const configured = typeof process !== "undefined" ? (_a8 = process.env) == null ? void 0 : _a8["SUPERCOV_SERVER_EVIDENCE_ROOT"] : void 0; return configured ? configured : DEFAULT_SERVER_EVIDENCE_ROOT; } function nonEmpty(value) { return typeof value === "string" && value.length > 0; } function safeKey(value) { return /^[a-zA-Z0-9_-]+$/.test(value); } function pathComponent(value) { const safe = value.replace(/[^a-zA-Z0-9_-]/g, "_"); return safe || "unscoped"; } function encodeCoverageScope(scope) { return new URLSearchParams({ v: String(scope.version), r: scope.runId, w: scope.workerId, t: scope.testId, k: scope.testKey, a: String(scope.retry), i: scope.attemptId }).toString(); } function decodeCoverageScope(encoded) { if (!encoded) return void 0; try { const values = new URLSearchParams(encoded); const runId = values.get("r"); const workerId = values.get("w"); const testId2 = values.get("t"); const testKey = values.get("k"); const attemptId = values.get("i"); const retry = Number(values.get("a")); if (values.get("v") !== "1" || !nonEmpty(runId) || !nonEmpty(workerId) || !nonEmpty(testId2) || !nonEmpty(testKey) || !safeKey(testKey) || !nonEmpty(attemptId) || !safeKey(attemptId) || !Number.isSafeInteger(retry) || retry < 0) return void 0; return { version: 1, runId, workerId, testId: testId2, testKey, retry, attemptId }; } catch (e) { return void 0; } } function encodeCoverageCarrier(carrier) { return capturedBuffer.from(JSON.stringify(carrier), "utf8").toString("base64url"); } function decodeCoverageCarrier(encoded) { if (!encoded) return void 0; try { const value = JSON.parse(capturedBuffer.from(encoded, "base64url").toString("utf8")); if (value.version !== 1) return void 0; if (value.scope) { const roundTrip = decodeCoverageScope(encodeCoverageScope(value.scope)); if (!roundTrip) return void 0; } if (value.phaseId !== void 0 && value.phaseId.length === 0) return void 0; return value; } catch (e) { return void 0; } } function serverRunEvidenceDirectory(runId, root = configuredServerEvidenceRoot()) { return `${root.replace(/\/+$/, "")}/${pathComponent(runId)}`; } function serverEvidenceDirectory(scope, root = configuredServerEvidenceRoot()) { return `${serverRunEvidenceDirectory(scope.runId, root)}/attempts`; } function serverEvidencePath(scope, root = configuredServerEvidenceRoot()) { return `${serverEvidenceDirectory(scope, root)}/${pathComponent(scope.attemptId)}.jsonl`; } // A scope's evidence directory and file, made once per scope and root: a // server works them out for every record it writes, thousands per test. var scopedEvidenceLocations = /* @__PURE__ */ new WeakMap(); function scopedEvidenceLocation(scope) { const root = configuredServerEvidenceRoot(); const known = scopedEvidenceLocations.get(scope); if (known !== void 0 && known.root === root) return known; const location = { root, directory: serverEvidenceDirectory(scope, root), path: serverEvidencePath(scope, root) }; scopedEvidenceLocations.set(scope, location); return location; } function backgroundEvidenceDirectory(runId, root = configuredServerEvidenceRoot()) { return `${serverRunEvidenceDirectory(runId, root)}/background`; } function backgroundEvidencePath(runId, processId = typeof process === "undefined" ? "unknown" : String(process.pid), root = configuredServerEvidenceRoot()) { return `${backgroundEvidenceDirectory(runId, root)}/${pathComponent(processId)}.jsonl`; } // dist/runtime.js // The collections a probe records into, called through the built-in methods // as they were when the runtime loaded: a test that spies on // Map.prototype.set counts the calls its own code makes, and Supercov's // first hits made three more, failing a test that passes without it. var builtinMapGet = Map.prototype.get; var builtinMapSet = Map.prototype.set; var builtinMapHas = Map.prototype.has; var builtinSetAdd = Set.prototype.add; var builtinSetHas = Set.prototype.has; var builtinWeakMapGet = WeakMap.prototype.get; var builtinWeakMapSet = WeakMap.prototype.set; var runtimeGlobal = globalThis; var runtimeInstanceToken = "__SUPERCOV_RUNTIME_INSTANCE__"; var runtimeInstance = runtimeInstanceToken === "__SUPERCOV_RUNTIME_INSTANCE__" ? "application" : runtimeInstanceToken; var _a; var isBrowser = !(typeof process !== "undefined" && typeof ((_a = process.versions) == null ? void 0 : _a.node) === "string"); var _a2; var testId = (_a2 = runtimeGlobal.__SUPERCOV_MCDC_TEST_ID__) != null ? _a2 : "unscoped"; var storageKey = "__supercov_coverage_" + testId; var phaseStorageKey = "__supercov_phase"; var pendingDefaults = /* @__PURE__ */ new Map(); function vectorKey(vector) { return vector.values.map((value) => value === null ? "-" : value ? "T" : "F").join("") + ":" + (vector.outcome ? "T" : "F"); } function getFs() { if (isBrowser || typeof process === "undefined") return void 0; try { const getBuiltinModule = process.getBuiltinModule; return getBuiltinModule == null ? void 0 : getBuiltinModule("node:fs"); } catch (e) { return void 0; } } function emptyEventLog() { return { type: [], id: [], vector: [], timestampMs: [], phaseId: [], environment: [] }; } // The events as they were recorded, each the object hitEvent or // decisionEvent built, in their key order. function eventObjects(log) { const events = new Array(log.id.length); for (let position = 0; position < events.length; position += 1) { const phaseId = log.phaseId[position]; events[position] = log.type[position] === "hit" ? hitEvent(log.id[position], log.timestampMs[position], phaseId, log.environment[position]) : decisionEvent(log.id[position], log.vector[position], log.timestampMs[position], phaseId, log.environment[position]); } return events; } function createState() { var _a8, _b, _c, _d; const state2 = { decisions: /* @__PURE__ */ new Map(), hits: /* @__PURE__ */ new Set(), // The events as columns, one entry per event: a first hit of every point // of every test was an object of its own, millions on a large suite, // turned into columns again for the evidence (eventColumns). eventLog: emptyEventLog(), // Per value-position logical expression (`a && b`, `a || b`, `a ?? b`): the distinct // (right operand evaluated?, result truthy?) pairs seen, keyed by branch id. logicals: /* @__PURE__ */ new Map(), // The events already recorded, by phase: a hit by its id, anything else // by its type and what tells it apart (eventSeen). eventKeys: /* @__PURE__ */ new Map(), bufferedAttempts: /* @__PURE__ */ new Set(), serverBuffers: /* @__PURE__ */ new Map(), persistedServerRecords: /* @__PURE__ */ new Set(), backgroundBuffers: /* @__PURE__ */ new Map(), backgroundWriters: /* @__PURE__ */ new Map(), backgroundShardSizes: /* @__PURE__ */ new Map(), backgroundDescriptors: /* @__PURE__ */ new Map(), pendingBackgroundAppends: /* @__PURE__ */ new Map(), backgroundSequence: 0, runtimeSnapshots: false, assertionPhases: /* @__PURE__ */ new Map(), // Each registered file, held weakly where the engine can: only the // epochs' wrap below reads them, to clear what live files remember. probeV2Files: /* @__PURE__ */ new Set(), probeV2FilesSweepAt: 1024, // `e` is the epoch: every statement probe reads it by name, and a // minifier keeps a property's name, so it is one letter in every bundle. probeV2Clock: { e: Number.NaN, fast: false }, probeV2ContextEpochs: /* @__PURE__ */ new Map(), probeV2NextEpoch: 1, probeV2HookInstalled: false, pendingServerAppends: /* @__PURE__ */ new Map(), createdEvidenceDirectories: /* @__PURE__ */ new Set(), serverFlushScheduled: false, serverExitHookInstalled: false, serverTransportFailure: void 0 }; if (!isBrowser) return state2; try { const stored = JSON.parse((_a8 = localStorage.getItem(storageKey)) != null ? _a8 : "{}"); for (const snapshot of (_b = stored.decisions) != null ? _b : []) { state2.decisions.set(snapshot.id, { id: snapshot.id, vectors: new Map(snapshot.vectors.map((vector) => [vectorKey(vector), vector])) }); } for (const id of (_c = stored.hits) != null ? _c : []) state2.hits.add(id); for (const event of (_d = stored.events) != null ? _d : []) recordEvent(state2, event.type, event.id, event.vector, event.timestampMs, event.phaseId, event.environment); } catch (e) { } return state2; } var _a3; var runtimeStates = (_a3 = runtimeGlobal.__SUPERCOV_MCDC_STATES__) != null ? _a3 : /* @__PURE__ */ new Map(); runtimeGlobal.__SUPERCOV_MCDC_STATES__ = runtimeStates; var _a4; var state = (_a4 = runtimeStates.get(runtimeInstance)) != null ? _a4 : createState(); runtimeStates.set(runtimeInstance, state); function createServerPhaseStorage() { var _a8; if (isBrowser || typeof process === "undefined") return void 0; try { const getBuiltinModule = process.getBuiltinModule; const AsyncLocalStorage = (_a8 = getBuiltinModule == null ? void 0 : getBuiltinModule("node:async_hooks")) == null ? void 0 : _a8.AsyncLocalStorage; return AsyncLocalStorage ? new AsyncLocalStorage() : void 0; } catch (e) { return void 0; } } var _a5; var serverPhaseStorages = (_a5 = runtimeGlobal.__SUPERCOV_SERVER_PHASE_STORAGES__) != null ? _a5 : /* @__PURE__ */ new Map(); runtimeGlobal.__SUPERCOV_SERVER_PHASE_STORAGES__ = serverPhaseStorages; var _a6; var serverPhaseStorage = (_a6 = serverPhaseStorages.get(runtimeInstance)) != null ? _a6 : createServerPhaseStorage(); if (serverPhaseStorage) serverPhaseStorages.set(runtimeInstance, serverPhaseStorage); function probeV2ContextKey(context) { var _a8, _b; const phase = (_a8 = context.phaseId) != null ? _a8 : "unscoped"; if (!context.scope) { const runId = typeof process !== "undefined" ? process.env["SUPERCOV_RUN_ID"] : void 0; return `background\0${(_b = runId != null ? runId : runtimeGlobal.__SUPERCOV_MCDC_TEST_ID__) != null ? _b : testId}\0${phase}`; } return `scope\0${attemptKey(context.scope)}\0${phase}`; } function activateProbeV2Key(key, force = false) { let epoch = force ? void 0 : builtinMapGet.call(state.probeV2ContextEpochs, key); if (epoch === void 0) { state.probeV2NextEpoch += 1; if (state.probeV2NextEpoch >= 4294967295) { state.probeV2NextEpoch = 1; state.probeV2ContextEpochs.clear(); state.probeV2EpochGeneration = (state.probeV2EpochGeneration || 0) + 1; for (const held of state.probeV2Files) { const file = typeof held.deref === "function" ? held.deref() : held; if (file === void 0) continue; file.hitEpochs.fill(0); for (const vectors of file.decisionEpochs) { if (vectors.size === void 0) vectors.fill(0); else vectors.clear(); } } } epoch = state.probeV2NextEpoch; builtinMapSet.call(state.probeV2ContextEpochs, key, epoch); } state.probeV2Clock.e = epoch; return epoch; } // The async hook activates the current request's context before every // callback the server runs, and building its key and looking it up was most of // a Next server's time in the hook. A request's context object is never // changed once made, and its key is made of it alone, so each keeps the epoch // it was given until the epochs are cleared. // Every copy of the runtime in a process shares one state, and the hook is the // first copy's, so the cache and its generation live on that state too: a // reset from another copy has to reach them. var emptyProbeV2Context = Object.freeze({}); function activateProbeV2Context(context) { // Work no request owns is keyed by the test running when it runs, which // changes under the same context: only a request's context keeps its epoch. if (!context.scope) return activateProbeV2Key(probeV2ContextKey(context)); if (state.probeV2ContextEpochCache === void 0) { state.probeV2ContextEpochCache = /* @__PURE__ */ new WeakMap(); state.probeV2EpochGeneration = 0; } const cached = builtinWeakMapGet.call(state.probeV2ContextEpochCache, context); if (cached !== void 0 && cached.generation === state.probeV2EpochGeneration) { state.probeV2Clock.e = cached.epoch; return cached.epoch; } const epoch = activateProbeV2Key(probeV2ContextKey(context)); builtinWeakMapSet.call(state.probeV2ContextEpochCache, context, { generation: state.probeV2EpochGeneration, epoch }); return epoch; } // While the speed benchmark times a run: how often a server's async hook ran // and how often a probe then had to work out its context, said once when the // process ends. var serverTiming = !isBrowser && typeof process !== "undefined" && process.env && process.env["SUPERCOV_PHASE_TIMING"] === "1" ? { asyncHookCallbacks: 0, contextResolutions: 0 } : void 0; if (serverTiming) { try { process.once("exit", () => { if (serverTiming.asyncHookCallbacks || serverTiming.contextResolutions) process.stderr.write(`[supercov-timing] server ${process.pid} asyncHookCallbacks=${serverTiming.asyncHookCallbacks} contextResolutions=${serverTiming.contextResolutions}\n`); }); } catch (e) { } } // The context the async hook leaves to a callback's first probe: the // request's store, or else the one the environment carries. function resolveProbeV2Epoch() { var _a8, _b; if (serverTiming) serverTiming.contextResolutions += 1; return activateProbeV2Context((_b = (_a8 = serverPhaseStorage == null ? void 0 : serverPhaseStorage.getStore()) != null ? _a8 : environmentRequestContext()) != null ? _b : emptyProbeV2Context); } // A statement probe trusts the clock's epoch with no check of `fast`: while // the clock is not fast -- no async hook keeps it -- its epoch is NaN wherever // instrumented code can run, which no recorded epoch equals, so every probe // takes the slow path and works out its context there, as it did when probes // checked `fast` first. What sets the epoch while not fast restores it before // instrumented code runs, or does not set it. function withProbeV2Context(context, callback) { if (!state.probeV2Clock.fast) return callback(); const previous = state.probeV2Clock.e; activateProbeV2Context(context); try { return callback(); } finally { state.probeV2Clock.e = previous; } } function installProbeV2AsyncHook() { var _a8; if (isBrowser || state.probeV2HookInstalled || typeof process === "undefined") return; try { const getBuiltinModule = process.getBuiltinModule; const createHook = (_a8 = getBuiltinModule == null ? void 0 : getBuiltinModule("node:async_hooks")) == null ? void 0 : _a8.createHook; if (!createHook) return; const epochs = []; createHook({ // NaN, which no epoch equals: the callback's first probe works out // its context. Most callbacks a server or a test runner runs reach no // instrumented code, and working it out here, for every one, read the // environment twice and built a key each time: on a Next app's suite, // more of the server's time than any of Supercov's other work. before() { if (serverTiming) serverTiming.asyncHookCallbacks += 1; epochs.push(state.probeV2Clock.e); state.probeV2Clock.e = NaN; }, after() { var _a9; state.probeV2Clock.e = (_a9 = epochs.pop()) != null ? _a9 : state.probeV2Clock.e; } }).enable(); state.probeV2HookInstalled = true; state.probeV2Clock.fast = true; } catch (e) { } } runtimeGlobal.__SUPERCOV_ACTIVATE_PROBE_CONTEXT__ = (browserTestId, browserPhaseId) => { state.probeV2Clock.fast = true; activateProbeV2Key(`browser\0${browserTestId}\0${browserPhaseId != null ? browserPhaseId : "unscoped"}`); }; function decisionSnapshot() { return [...state.decisions.values()].map((decision) => ({ id: decision.id, vectors: [...decision.vectors.values()] })); } function logicalSnapshot() { return [...state.logicals.entries()].map(([id, vectors]) => ({ id, vectors: [...vectors.values()] })); } function coverageSnapshot() { return { decisions: decisionSnapshot(), hits: [...state.hits], events: eventObjects(state.eventLog), logicals: logicalSnapshot() }; } // coverageSnapshot as snapshots.mjs's columnarEvents gives it, built from the // columns the events are kept in rather than from an object per event. function coverageSnapshotColumns() { const log = state.eventLog; const decisions = decisionSnapshot(); const hits = [...state.hits]; const logicals = logicalSnapshot(); if (log.id.length === 0) return { decisions, hits, events: [], logicals }; const tables = { types: /* @__PURE__ */ new Map(), phases: /* @__PURE__ */ new Map(), environments: /* @__PURE__ */ new Map() }; const index = (table, value) => { let found = table.get(value); if (found === void 0) { found = table.size; table.set(value, found); } return found; }; // An event that is one of the hits names it by its position in `hits` // (snapshots.mjs's columnarEvents says why). const hitAt = /* @__PURE__ */ new Map(); for (let position = 0; position < hits.length; position += 1) hitAt.set(hits[position], position); const columns = { id: [], type: [], phase: [], environment: [], t: [], vector: {} }; let previous = 0; for (let position = 0; position < log.id.length; position += 1) { const id = log.id[position]; const at = hitAt.get(id); columns.id.push(at === void 0 ? id : at); const phaseId = log.phaseId[position]; columns.type.push(index(tables.types, log.type[position])); // An event built without a phase -- phaseId falsy -- has none. columns.phase.push(phaseId ? index(tables.phases, phaseId) : -1); columns.environment.push(index(tables.environments, log.environment[position])); columns.t.push(log.timestampMs[position] - previous); previous = log.timestampMs[position]; if (log.type[position] !== "hit") columns.vector[position] = log.vector[position]; } return { decisions, hits, logicals, eventColumns: { types: [...tables.types.keys()], phases: [...tables.phases.keys()], environments: [...tables.environments.keys()], ...columns } }; } function resetCoverage(testId2) { state.decisions.clear(); state.hits.clear(); state.eventLog = emptyEventLog(); state.logicals.clear(); state.eventKeys.clear(); state.probeV2ContextEpochs.clear(); state.probeV2EpochGeneration = (state.probeV2EpochGeneration || 0) + 1; activateProbeV2Key(`reset\0${state.probeV2NextEpoch}`, true); if (!state.probeV2Clock.fast) state.probeV2Clock.e = NaN; if (testId2) runtimeGlobal.__SUPERCOV_MCDC_TEST_ID__ = testId2; if (isBrowser) { try { localStorage.removeItem(storageKey); } catch (e) { } } } runtimeGlobal.__SUPERCOV_MCDC_SNAPSHOT__ = decisionSnapshot; runtimeGlobal.__SUPERCOV_COVERAGE_SNAPSHOT__ = coverageSnapshot; // A snapshot as the text the Playwright collector reads back. Its events // become rows over one table of the strings they repeat -- point ids, phase // ids, kinds -- each row in the key order of its event (`shapes`), and its // hits indexes into the same table; snapshots.mjs's expandSnapshot gives // back what JSON.parse of the whole would have. A large frontend's page // holds tens of thousands of events, each naming its point, phase and // environment in full, read back at the end of every test and from every // page that leaves: relaying them cost the browser's own process more than // its renderers spent running the app. function compactSnapshotText(snapshot) { if (!snapshot || typeof snapshot !== "object" || !Array.isArray(snapshot.events) || !Array.isArray(snapshot.hits)) return JSON.stringify(snapshot); const strings = []; const stringIndexes = /* @__PURE__ */ new Map(); const intern = (value) => { let index = stringIndexes.get(value); if (index === void 0) { index = strings.length; strings.push(value); stringIndexes.set(value, index); } return index; }; const shapes = []; const shapeIndexes = /* @__PURE__ */ new Map(); const rows = []; for (let position = 0; position < snapshot.events.length; position += 1) { const event = snapshot.events[position]; if (!event || typeof event !== "object" || Array.isArray(event)) return JSON.stringify(snapshot); const fields = []; const values = []; const keys = Object.keys(event); for (let index = 0; index < keys.length; index += 1) { const value = event[keys[index]]; // What JSON.stringify leaves out of an object. if (value === void 0 || typeof value === "function" || typeof value === "symbol") continue; if (typeof value === "string") { fields.push(`s${keys[index]}`); values.push(intern(value)); } else { fields.push(`v${keys[index]}`); values.push(value); } } const name = fields.join("\0"); let shape = shapeIndexes.get(name); if (shape === void 0) { shape = shapes.length; shapes.push(fields); shapeIndexes.set(name, shape); } rows.push(shape); for (let index = 0; index < values.length; index += 1) rows.push(values[index]); } const hits = []; for (let index = 0; index < snapshot.hits.length; index += 1) { if (typeof snapshot.hits[index] !== "string") return JSON.stringify(snapshot); hits.push(intern(snapshot.hits[index])); } const rest = {}; const keys = Object.keys(snapshot); for (let index = 0; index < keys.length; index += 1) { if (keys[index] !== "events" && keys[index] !== "hits") rest[keys[index]] = snapshot[keys[index]]; } return JSON.stringify({ supercovCompactSnapshot: 1, order: keys, rest, strings, shapes, rows, hits }); } runtimeGlobal.__SUPERCOV_COMPACT_SNAPSHOT__ = compactSnapshotText; runtimeGlobal.__SUPERCOV_RESET__ = resetCoverage; // A dedicated worker blocked in `Atomics.wait` runs no evaluation, so the // test runner could not read its evidence and reported the test as a lower // bound: Actual's database worker waits that way between every query. The // worker pushes its evidence to its pages instead, on a BroadcastChannel, // each time it is about to block with something recorded since its last // push; a worker that wakes and records something new says its push is no // longer current. A page keeps the latest push of each worker, and the runner // reads that when the worker itself does not answer: complete when current. var workerEvidenceChannelName = "__supercov_worker_evidence__"; var workerEvidence = null; function workerEvidenceChanged() { if (workerEvidence === null || workerEvidence.changed) return; workerEvidence.changed = true; if (!workerEvidence.pushed) return; workerEvidence.pushed = false; try { workerEvidence.channel.postMessage({ token: workerEvidence.token, current: false }); } catch (e) { } } function pushWorkerEvidence() { if (workerEvidence === null || workerEvidence.pushed) return; workerEvidence.changed = false; workerEvidence.pushed = true; try { workerEvidence.channel.postMessage({ token: workerEvidence.token, url: workerEvidence.url, current: true, snapshot: coverageSnapshot() }); } catch (e) { workerEvidence.pushed = false; } } (function installWorkerEvidenceTransport() { if (!isBrowser || typeof BroadcastChannel !== "function") return; if (typeof WorkerGlobalScope === "function" && runtimeGlobal instanceof WorkerGlobalScope) { if (typeof Atomics !== "object" || typeof Atomics.wait !== "function" || runtimeGlobal.__SUPERCOV_WORKER_TOKEN__) return; try { const token = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`; const url = runtimeGlobal.location ? String(runtimeGlobal.location.href) : ""; workerEvidence = { channel: new BroadcastChannel(workerEvidenceChannelName), token, url, changed: true, pushed: false }; runtimeGlobal.__SUPERCOV_WORKER_TOKEN__ = token; const wait = Atomics.wait; Atomics.wait = function wait2(typedArray, index, value, timeout) { pushWorkerEvidence(); return Reflect.apply(wait, Atomics, arguments); }; } catch (e) { workerEvidence = null; } return; } if (typeof document === "undefined" || runtimeGlobal.__SUPERCOV_WORKER_EVIDENCE__) return; const received = /* @__PURE__ */ new Map(); try { const channel = new BroadcastChannel(workerEvidenceChannelName); channel.onmessage = (event) => { const message = event.data; if (!message || typeof message.token !== "string") return; const pushed = received.get(message.token); if (message.current) received.set(message.token, { url: message.url, snapshot: message.snapshot, current: true }); else if (pushed) pushed.current = false; }; } catch (e) { return; } runtimeGlobal.__SUPERCOV_WORKER_EVIDENCE__ = () => Array.from(received, ([token, pushed]) => ({ token, url: pushed.url, current: pushed.current, snapshot: pushed.snapshot })); })(); var persistBrowserListenersInstalled = false; // How much evidence the document holds. Every part of it only grows until a // reset, so the same size twice is the same evidence. function evidenceSize() { let size = state.hits.size + state.eventLog.id.length; for (const decision of state.decisions.values()) size += decision.vectors.size; for (const vectors of state.logicals.values()) size += vectors.size; return size; } // The evidence's size when this document gave it to the Playwright collector // on the way out. Its next document need not inherit it then: carried through // localStorage as well, every page of a test parsed all the evidence of the // pages before it on load and wrote it all again on leaving, a test of thirty // pages paying for the first one thirty times, and the collector merged the // same evidence once per page. What runs after the hand-over -- the rest of a // handler that set `location.href`, a render it started -- is still carried. var handedOverSize = -1; function persistBrowserNow() { if (!isBrowser) return; try { if (handedOverSize === evidenceSize()) localStorage.removeItem(storageKey); else localStorage.setItem(storageKey, JSON.stringify(coverageSnapshot())); } catch (e) { } } // The Playwright collector's binding takes the evidence of a document that // is about to leave. localStorage gives it to the next document only on the // same origin: a click that sent the page to another one (an admin's // masquerade link, a sign-in redirect) lost every hit it made. Called from // `pagehide` the binding never reached the collector; from `beforeunload` // it does. function handOverBrowser() { try { if (typeof runtimeGlobal.__supercovLeaving === "function") { runtimeGlobal.__supercovLeaving(compactSnapshotText(coverageSnapshot())); handedOverSize = evidenceSize(); } } catch (e) { } } function persistBrowser() { if (!isBrowser) return; // Persistence exists so evidence survives navigation, so it is written // when the page leaves. Written after every macrotask that recorded // anything, the whole snapshot was serialized again and again: a large // instrumented frontend doubled a Playwright suite's time. A page the // test closes is read by the collector before it closes. if (persistBrowserListenersInstalled) return; persistBrowserListenersInstalled = true; try { addEventListener("beforeunload", handOverBrowser); // An iframe the page removes (a client-side navigation away from the // page that held it, an embed closed) gets no `beforeunload`: what it ran // went with it, though the test clicked in it. Its `pagehide` reaches the // collector, unlike a top-level document's. if (typeof window !== "undefined" && window !== window.top) addEventListener("pagehide", handOverBrowser); addEventListener("pagehide", persistBrowserNow); addEventListener("visibilitychange", () => { if (typeof document !== "undefined" && document.visibilityState === "hidden") persistBrowserNow(); }); } catch (e) { } } function attemptKey(scope) { return `${scope.runId}\0${scope.workerId}\0${scope.attemptId}`; } // An attempt's file says its scope once per writing process: each line // without one is of the scope of the line before it in the same file. var scopedPathsWritten = /* @__PURE__ */ new Set(); function serverLine(record, path) { if (!path) return JSON.stringify(record); const { scope, ...line } = record; if (scope && !scopedPathsWritten.has(path)) { scopedPathsWritten.add(path); line.scope = scope; } return JSON.stringify(line); } function serverRecordKey(record) { var _a8; const suffix = record.type === "decision" ? `${record.id}:${vectorKey(record.vector)}` : record.id; // Each request that names no test keeps its own first hits: the report // credits them to the test running when it came, and a later request's // work belongs to whichever test was running then. const request = record.request ? `request-${record.request}:` : ""; return `${request}${(_a8 = record.phaseId) != null ? _a8 : "unscoped"}:${record.type}:${suffix}`; } // Notes, once per test attempt, that this process served a request naming // it. A request here that names no test is credited by time only among the // attempts this process served: with a server per worker, the worker's test, // whatever the other workers run meanwhile. function noteServedAttempt(scope) { if (!state.servedAttempts) state.servedAttempts = /* @__PURE__ */ new Set(); const key = attemptKey(scope); if (state.servedAttempts.has(key)) return; state.servedAttempts.add(key); const fs = getFs(); if (!fs) return; try { appendDurableBackgroundRecord(fs, scope.runId, { type: "served", id: scope.attemptId, timestampMs: Date.now() }); } catch (e) { } } // Numbers the requests a server handles that name no test. function nextUnscopedRequest() { state.unscopedRequests = (state.unscopedRequests || 0) + 1; return state.unscopedRequests; } function beginBufferedServerEvidence(scope) { if (isBrowser) return; switchWasmOwner(scope); const key = attemptKey(scope); state.bufferedAttempts.add(key); if (!state.serverBuffers.has(key)) state.serverBuffers.set(key, { scope, directory: serverEvidenceDirectory(scope), path: serverEvidencePath(scope), records: /* @__PURE__ */ new Map() }); } function flushBufferedServerEvidence(scope) { if (isBrowser) return void 0; switchWasmOwner(void 0); const key = attemptKey(scope); state.bufferedAttempts.delete(key); const buffered = state.serverBuffers.get(key); if (!buffered) return void 0; state.serverBuffers.delete(key); const fs = getFs(); if (!fs || buffered.records.size === 0) return void 0; try { makeEvidenceDirectory(fs, buffered.directory); fs.appendFileSync(buffered.path, [...buffered.records.values()].map((record) => serverLine(record, buffered.path)).join("\n") + "\n"); return buffered.path; } catch (e) { return void 0; } } function enableRuntimeSnapshotEvidence() { state.runtimeSnapshots = true; } function flushAllBufferedServerEvidence() { for (const buffered of [...state.serverBuffers.values()]) flushBufferedServerEvidence(buffered.scope); for (const runId of [...state.backgroundBuffers.keys()]) flushBufferedBackgroundEvidence(runId); } function flushBufferedBackgroundEvidence(runId) { if (isBrowser) return void 0; const records = state.backgroundBuffers.get(runId); if (!records || records.size === 0) return void 0; return state.backgroundWriters.get(runId); } function writeExclusiveBackgroundRecord(fs, runId, writer, initialSequence, payload) { let sequence = initialSequence; for (let attempt = 0; attempt < 1e4; attempt += 1) { const candidate = backgroundEvidencePath(runId, `${writer}-${sequence++}`); try { fs.writeFileSync(candidate, payload, { flag: "wx" }); return sequence; } catch (error) { if (error.code === "EEXIST") continue; throw error; } } throw Object.assign(new Error("Could not allocate a collision-free Supercov background evidence record"), { code: "SUPERCOV_BACKGROUND_COLLISION_LIMIT" }); } function backgroundWriterToken() { try { const getBuiltinModule = process.getBuiltinModule; const crypto = getBuiltinModule == null ? void 0 : getBuiltinModule("node:crypto"); if (crypto) return crypto.randomBytes(4).toString("hex"); } catch (e) { } return Math.floor(Math.random() * 4294967295).toString(16); } // Background records -- every first hit under tap, AVA or Mocha, and code run // outside any test -- are written once per event-loop turn, as a test's own // records are, and on exit and the terminating signals. Written one by one // they cost lru-cache's 10 ms TTL test a write and a stat for each of the 132 // first hits in its window, and the test missed its deadline under load. A // process killed in the middle of a turn loses that turn's records. function appendDurableBackgroundRecord(fs, runId, record) { const records = state.backgroundBuffers.get(runId) != null ? state.backgroundBuffers.get(runId) : /* @__PURE__ */ new Map(); const key = serverRecordKey(record); if (records.has(key)) return state.backgroundWriters.get(runId); if (state.serverTransportFailure) throw state.serverTransportFailure; records.set(key, record); state.backgroundBuffers.set(runId, records); let pending = state.pendingBackgroundAppends.get(runId); if (!pending) { pending = []; state.pendingBackgroundAppends.set(runId, pending); } pending.push(JSON.stringify(record) + "\n"); if (pending.length >= 2048) flushServerAppends(); else scheduleServerFlush(); return state.backgroundWriters.get(runId); } function flushBackgroundAppends(fs) { for (const [runId, lines] of state.pendingBackgroundAppends) { state.pendingBackgroundAppends.delete(runId); try { if (!fs) throw new Error("node:fs is unavailable"); writeBackgroundLines(fs, runId, lines.join("")); } catch (cause) { const failure = cause instanceof Error && cause.code === "SUPERCOV_EVIDENCE_TRANSPORT_FAILED" ? cause : serverTransportError(runId, cause); state.serverTransportFailure = failure; throw failure; } } } // In a container Supercov's `docker` launcher mounts the run's directory // into, its user (root) owns what it creates there, and the run, outside, // could not remove what went in it. There each directory made is opened to // all. function makeEvidenceDirectory(fs, directory) { const first = fs.mkdirSync(directory, { recursive: true }); markContainerWriting(fs); if (!first || typeof process === "undefined" || !process.env || process.env.SUPERCOV_CONTAINER !== "1") return; let current = first; const opened = [current]; for (const part of directory.slice(first.length).split(/[\\/]/).filter(Boolean)) { current = `${current}/${part}`; opened.push(current); } for (const made of opened) { try { fs.chmodSync(made, 0o777); } catch (e) { } } } // A container Supercov's relay measured says, once, that its evidence could // be written: one that never does -- a server stopped at its first probe, a // directory it may not write -- is named when the run ends. function markContainerWriting(fs) { const mark = typeof process !== "undefined" && process.env ? process.env.SUPERCOV_CONTAINER_MARK : void 0; if (!mark || state.containerMarked) return; state.containerMarked = true; try { fs.mkdirSync(mark.slice(0, mark.lastIndexOf("/")), { recursive: true }); fs.writeFileSync(mark, "", { mode: 0o666 }); fs.chmodSync(mark, 0o666); } catch (e) { } } function writeBackgroundLines(fs, runId, payload) { var _a8; const directory = backgroundEvidenceDirectory(runId); if (!state.createdEvidenceDirectories.has(directory)) { makeEvidenceDirectory(fs, directory); state.createdEvidenceDirectories.add(directory); } let path = state.backgroundWriters.get(runId); // A pid is not an identity: pool VMs restored from one snapshot run clones // of this very process, same pid and same cached shard path, and their // appends over a shared mount tear each other's lines. The shard name gets // a fresh random token, and an append that finds the file a different size // than this writer left it has met a clone: it moves to a new shard. if (path) { let currentSize = -1; try { currentSize = fs.statSync(path).size; } catch (e) { } if (currentSize !== (state.backgroundShardSizes.has(path) ? state.backgroundShardSizes.get(path) : -1)) { closeBackgroundShard(fs, path); path = void 0; } } if (!path) { const shard = (_a8 = process.env["SUPERCOV_EXECUTION_LOG_SHARD"]) != null ? _a8 : "process"; const writer = `${shard}-${process.pid}-${backgroundWriterToken()}`; const nextSequence = writeExclusiveBackgroundRecord(fs, runId, writer, state.backgroundSequence, payload); state.backgroundSequence = nextSequence; path = backgroundEvidencePath(runId, `${writer}-${nextSequence - 1}`); state.backgroundWriters.set(runId, path); state.backgroundShardSizes.set(path, capturedBuffer.byteLength(payload)); return; } let descriptor = state.backgroundDescriptors.get(path); if (descriptor === void 0) { descriptor = fs.openSync(path, "a"); state.backgroundDescriptors.set(path, descriptor); } const bytes = capturedBuffer.from(payload); for (let written = 0; written < bytes.length; ) written += fs.writeSync(descriptor, bytes, written, bytes.length - written); state.backgroundShardSizes.set(path, (state.backgroundShardSizes.get(path) || 0) + bytes.length); } function closeBackgroundShard(fs, path) { const descriptor = state.backgroundDescriptors.get(path); if (descriptor === void 0) return; state.backgroundDescriptors.delete(path); try { fs.closeSync(descriptor); } catch (e) { } } var _a7; // Evidence buffered for the current turn is lost when a signal ends the // process, because "exit" does not run for one -- and killing a child in // teardown is exactly how a suite stops a gateway it started. Flush on the // terminating signals as well as on exit. // // Exactly one listener per signal serves every flusher: two of our own would // each see a sibling listener, neither would judge itself alone, and a // signalled process would stay alive. Having flushed, restore what the signal // would have done -- if nothing else is listening the program expected to die, // so re-raise with our listener gone; if the program installed its own handler // it deliberately suppressed that default and we must not exit on its behalf. function flushOnTermination(flush) { var _a9; if (typeof process === "undefined") return; const flushers = (_a9 = runtimeGlobal.__SUPERCOV_TERMINATION_FLUSHERS__) != null ? _a9 : /* @__PURE__ */ new Set(); runtimeGlobal.__SUPERCOV_TERMINATION_FLUSHERS__ = flushers; flushers.add(flush); if (runtimeGlobal.__SUPERCOV_TERMINATION_INSTALLED__) return; runtimeGlobal.__SUPERCOV_TERMINATION_INSTALLED__ = true; const drain = () => { var _a10; for (const value of (_a10 = runtimeGlobal.__SUPERCOV_TERMINATION_FLUSHERS__) != null ? _a10 : []) { try { value(); } catch (e) { } } }; try { process.on("exit", drain); } catch (e) { } // `process.execve` replaces the process with another program: no "exit" // runs, and what this one buffered would go with it. A cache front end // that hands itself over to the runner's Node lost every line it ran. try { const execve = process.execve; if (typeof execve === "function") { process.execve = function supercovExecve() { drain(); return execve.apply(this, arguments); }; } } catch (e) { } const signals = ["SIGTERM", "SIGINT", "SIGHUP", "SIGBREAK"]; for (const signal of signals) { try { process.on(signal, () => { drain(); if (process.listenerCount(signal) <= 1) { process.removeAllListeners(signal); process.kill(process.pid, signal); } }); } catch (e) { } } // A listener keeps nothing alive, and a signal a process sends itself is // handled on a later turn of its event loop: `process.kill(process.pid, // "SIGTERM")` as a script's last line exited 0, once nothing else held the // loop open, where alone it ended by the signal. A signal to itself that // only this listener would take is drained and left to act at once. try { const kill = process.kill; const numbered = { 1: "SIGHUP", 2: "SIGINT", 15: "SIGTERM", 21: "SIGBREAK" }; process.kill = function supercovKill(pid, signal) { const name = signal === void 0 ? "SIGTERM" : typeof signal === "number" ? numbered[signal] : signal; if (Number(pid) === process.pid && signals.indexOf(name) >= 0 && process.listenerCount(name) <= 1) { drain(); process.removeAllListeners(name); } return kill.apply(this, arguments); }; } catch (e) { } } // Rust compiled to wasm and measured by the Rust frontend keeps what it ran // in the module's memory, behind `__supercov_region_`. When the run // measures such a crate (SUPERCOV_WASM_REGIONS, or the page flag the // Playwright fixture sets), every instance the process or page creates is // remembered, and its regions are taken -- copied and cleared -- at each // test's edges: what was taken belongs to the test that just ended, or to no // test. The Rust run reads the takes and credits each to its test. var WASM_REGION_PREFIX = "__supercov_region_"; function wasmRegionsWanted() { if (runtimeGlobal.__SUPERCOV_WASM_REGIONS__ === true) return true; return typeof process !== "undefined" && process.env != null && process.env.SUPERCOV_WASM_REGIONS === "1"; } function installWasmRegistry() { if (runtimeGlobal.__SUPERCOV_WASM_REGISTRY__ || typeof WebAssembly === "undefined" || !wasmRegionsWanted()) return; runtimeGlobal.__SUPERCOV_WASM_REGISTRY__ = true; if (!runtimeGlobal.__supercovWasm) runtimeGlobal.__supercovWasm = []; registerWasmRealm(runtimeGlobal); } /** Remember the instances another realm creates too: Jest runs each test file in a context with a `WebAssembly` of its own. */ function registerWasmRealm(realm) { if (!runtimeGlobal.__SUPERCOV_WASM_REGISTRY__ || !realm || !realm.WebAssembly) return; // By the `WebAssembly` itself: a flag on the realm's global would show // through in a context that exposes the outer globals, as Jest's does. if (!runtimeGlobal.__supercovWasmRealms) runtimeGlobal.__supercovWasmRealms = new WeakSet(); const wasm = realm.WebAssembly; if (runtimeGlobal.__supercovWasmRealms.has(wasm)) return; runtimeGlobal.__supercovWasmRealms.add(wasm); const instances = runtimeGlobal.__supercovWasm; const Instance = wasm.Instance; function Recorded(module, imports) { const instance = new Instance(module, imports); instances.push(instance); return instance; } Recorded.prototype = Instance.prototype; try { wasm.Instance = Recorded; } catch (e) { } ["instantiate", "instantiateStreaming"].forEach(function(name) { const original = wasm[name]; if (typeof original !== "function") return; try { wasm[name] = function() { return original.apply(wasm, arguments).then(function(result) { instances.push(result instanceof Instance ? result : result.instance); return result; }); }; } catch (e) { } }); } installWasmRegistry(); function wasmBase64(bytes) { if (typeof Buffer !== "undefined") return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64"); let text = ""; for (let index = 0; index < bytes.length; index += 32768) text += String.fromCharCode.apply(null, bytes.subarray(index, Math.min(bytes.length, index + 32768))); return btoa(text); } /** Each instrumented crate's region: its header and the pages a probe touched since the last take, then cleared. A region with nothing new is left out, but for the first take, which carries what `cfg!` said of the crate's gates. */ function takeWasmRegions() { const out = []; const instances = runtimeGlobal.__supercovWasm; if (!instances) return out; if (!runtimeGlobal.__supercovWasmTaken) runtimeGlobal.__supercovWasmTaken = new WeakSet(); const seen = runtimeGlobal.__supercovWasmTaken; for (const instance of instances) { const exports = instance && instance.exports; if (!exports || !exports.memory) continue; for (const name of Object.keys(exports)) { if (name.indexOf(WASM_REGION_PREFIX) !== 0) continue; try { const crate = name.slice(WASM_REGION_PREFIX.length); const packed = BigInt.asUintN(64, BigInt(exports[name]())); const at = Number(packed >> BigInt(32)); const length = Number(packed & BigInt(4294967295)); if (!length) continue; const view = new DataView(exports.memory.buffer, at, length); const first = !seen.has(exports); if (!first && view.getUint32(40, true) === 0 && view.getUint32(44, true) === 0) continue; seen.add(exports); const bytes = new Uint8Array(exports.memory.buffer, at, length); const bodyAt = view.getUint32(32, true); const segments = [[0, wasmBase64(bytes.subarray(0, bodyAt))]]; for (let page = 0; bodyAt + page * 4096 < length; page++) { if (bytes[128 + (page >> 3)] & 1 << (page & 7)) { const from = bodyAt + page * 4096; segments.push([from, wasmBase64(bytes.subarray(from, Math.min(length, from + 4096)))]); } } out.push([crate, length, segments]); const clear = exports["__supercov_clear_" + crate]; if (typeof clear === "function") clear(); } catch (e) { } } } return out; } /** Write a take, owned by an attempt or by no test, where the Rust run reads it. */ function appendWasmRecord(attemptId, regions) { if (isBrowser || !regions || regions.length === 0) return; const fs = getFs(); if (!fs) return; try { const directory = configuredServerEvidenceRoot() + "/wasm"; makeEvidenceDirectory(fs, directory); if (!state.wasmFile) state.wasmFile = directory + "/" + process.pid + "-" + Math.random().toString(36).slice(2) + ".jsonl"; fs.appendFileSync(state.wasmFile, JSON.stringify({ owner: attemptId || null, regions }) + "\n"); } catch (e) { } } /** The test whose wasm work is being recorded changes: what was recorded until now is the previous owner's. */ function switchWasmOwner(scope) { if (!runtimeGlobal.__SUPERCOV_WASM_REGISTRY__ || isBrowser) return; const owner = state.wasmOwner || null; state.wasmOwner = scope && scope.attemptId ? scope.attemptId : null; appendWasmRecord(owner, takeWasmRegions()); } if (!isBrowser) { const flushers = (_a7 = runtimeGlobal.__SUPERCOV_BUFFER_FLUSHERS__) != null ? _a7 : /* @__PURE__ */ new Set(); runtimeGlobal.__SUPERCOV_BUFFER_FLUSHERS__ = flushers; flushers.add(flushAllBufferedServerEvidence); flushers.add(function() { switchWasmOwner(void 0); }); if (!runtimeGlobal.__SUPERCOV_BUFFER_EXIT_INSTALLED__) { flushOnTermination(() => { var _a8; for (const flush of (_a8 = runtimeGlobal.__SUPERCOV_BUFFER_FLUSHERS__) != null ? _a8 : []) flush(); }); runtimeGlobal.__SUPERCOV_BUFFER_EXIT_INSTALLED__ = true; } } function serverTransportError(runId, cause) { const detail = cause instanceof Error ? cause.message : String(cause); const failure = new Error(`Supercov could not persist coverage evidence for run ${runId}: ${detail}`); failure.code = "SUPERCOV_EVIDENCE_TRANSPORT_FAILED"; failure.cause = cause; return failure; } function flushServerAppends() { const pending = state.pendingServerAppends; if (pending.size === 0 && state.pendingBackgroundAppends.size === 0) return; const fs = getFs(); flushBackgroundAppends(fs); for (const [path, entry] of pending) { pending.delete(path); try { if (!fs) throw new Error("node:fs is unavailable"); if (!state.createdEvidenceDirectories.has(entry.directory)) { makeEvidenceDirectory(fs, entry.directory); state.createdEvidenceDirectories.add(entry.directory); } fs.appendFileSync(path, entry.lines.join("")); } catch (cause) { const failure = serverTransportError(entry.runId, cause); state.serverTransportFailure = failure; throw failure; } } } function enqueueServerAppend(directory, path, line, runId) { // Fail closed with the original context: after one transport failure the // very next probe re-raises it synchronously. if (state.serverTransportFailure) throw state.serverTransportFailure; const entry = state.pendingServerAppends.get(path); if (entry) { entry.lines.push(line); if (entry.lines.length >= 2048) flushServerAppends(); } else { state.pendingServerAppends.set(path, { directory, runId, lines: [line] }); } scheduleServerFlush(); } function scheduleServerFlush() { if (!state.serverExitHookInstalled && typeof process !== "undefined") { state.serverExitHookInstalled = true; try { flushOnTermination(flushServerAppends); } catch (e) { } } // One synchronous write per event-loop turn instead of one per probe: a // request handler's burst of first-touch records becomes a single append // that is still on disk before the process yields past this turn. if (!state.serverFlushScheduled) { state.serverFlushScheduled = true; queueMicrotask(() => { state.serverFlushScheduled = false; flushServerAppends(); }); } } function appendServer(record) { var _a8, _b, _c, _d; if (state.runtimeSnapshots) { const timestampMs = (_a8 = record.timestampMs) != null ? _a8 : Date.now(); if (record.type === "decision") recordBrowserEvent("decision", record.id, record.vector, timestampMs, record.phaseId, "server"); else recordBrowserEvent("hit", record.id, void 0, timestampMs, record.phaseId, "server"); return; } const fs = getFs(); if (!fs) return; const context = currentRequestContext(); const scope = context.scope; const runId = (_b = scope == null ? void 0 : scope.runId) != null ? _b : typeof process !== "undefined" ? process.env["SUPERCOV_RUN_ID"] : void 0; if (!runId) return; try { const location = scope ? scopedEvidenceLocation(scope) : void 0; const directory = location == null ? void 0 : location.directory; const path = location == null ? void 0 : location.path; // Work done while handling a request that named no test -- a webhook a // mock server sends -- says so, with the request's number. const stored = serverPhaseStorage == null ? void 0 : serverPhaseStorage.getStore(); const unscopedRequest = !scope && stored && stored.request ? { request: stored.request } : {}; const serialized = __spreadValues(__spreadValues(__spreadValues({}, record), scope ? { scope } : {}), unscopedRequest); if (scope && state.bufferedAttempts.has(attemptKey(scope))) { const key = attemptKey(scope); const buffered = (_c = state.serverBuffers.get(key)) != null ? _c : { scope, directory, path, records: /* @__PURE__ */ new Map() }; buffered.records.set(serverRecordKey(serialized), serialized); state.serverBuffers.set(key, buffered); return; } const deduplicationKey = scope && serialized.phaseId ? `${attemptKey(scope)}:${serverRecordKey(serialized)}` : void 0; if (deduplicationKey && state.persistedServerRecords.has(deduplicationKey)) return; if (!path) { appendDurableBackgroundRecord(fs, runId, serialized); return; } enqueueServerAppend(directory, path, serverLine(serialized, path) + "\n", runId); if (deduplicationKey) state.persistedServerRecords.add(deduplicationKey); } catch (cause) { if (cause instanceof Error && cause.code === "SUPERCOV_EVIDENCE_TRANSPORT_FAILED") throw cause; throw serverTransportError(runId, cause); } } // The context a parent process gave this one, in SUPERCOV_CONTEXT: read on // every first hit, and fixed for the process's life. Supercov only ever gives // it to a child, at spawn, so it is read once per environment object: a // read of process.env, an interceptor, on every first hit of a large suite's // tests was the runtime's largest cost. A suite that swaps process.env for // another object is read again. var decodedEnvironmentCarrier = { env: void 0, context: void 0 }; function environmentRequestContext() { if (isBrowser || typeof process === "undefined") return void 0; const env = process.env; if (env === decodedEnvironmentCarrier.env) return decodedEnvironmentCarrier.context; const carrier = decodeCoverageCarrier(env[COVERAGE_CARRIER_ENV]); const context = carrier ? __spreadValues(__spreadValues({}, carrier.scope ? { scope: carrier.scope } : {}), carrier.phaseId ? { phaseId: carrier.phaseId } : {}) : void 0; decodedEnvironmentCarrier = { env, context }; return context; } function currentRequestContext() { const stored = serverPhaseStorage == null ? void 0 : serverPhaseStorage.getStore(); if (stored !== void 0) { if (stored.scope || stored.phaseId) return stored; return runtimeGlobal.__SUPERCOV_ACTIVE_SCOPE__ ? { scope: runtimeGlobal.__SUPERCOV_ACTIVE_SCOPE__ } : {}; } const environment = environmentRequestContext(); if ((environment == null ? void 0 : environment.scope) || (environment == null ? void 0 : environment.phaseId)) return environment; return runtimeGlobal.__SUPERCOV_ACTIVE_SCOPE__ ? { scope: runtimeGlobal.__SUPERCOV_ACTIVE_SCOPE__ } : {}; } function activateCoverageScope(scope) { switchWasmOwner(scope); if (scope) runtimeGlobal.__SUPERCOV_ACTIVE_SCOPE__ = scope; else delete runtimeGlobal.__SUPERCOV_ACTIVE_SCOPE__; activateProbeV2Context(scope ? { scope } : {}); } function coverageCarrier() { const context = currentRequestContext(); return __spreadValues(__spreadValues({ version: 1 }, context.scope ? { scope: context.scope } : {}), context.phaseId ? { phaseId: context.phaseId } : {}); } function withCoverageCarrier(carrier, callback) { const decoded = typeof carrier === "string" ? decodeCoverageCarrier(carrier) : carrier; if (!serverPhaseStorage || !decoded) return callback(); const context = __spreadValues(__spreadValues({}, decoded.scope ? { scope: decoded.scope } : {}), decoded.phaseId ? { phaseId: decoded.phaseId } : {}); return serverPhaseStorage.run(context, () => withProbeV2Context(context, callback)); } function assertionPhaseState(scope) { const key = attemptKey(scope); const existing = state.assertionPhases.get(key); if (existing) { if (existing.phaseIds == null) existing.phaseIds = new Set(existing.phases.filter(phase => phase.kind === "assertion").map(phase => phase.id)); return existing; } const created = { counter: 0, phases: [], phaseIds: new Set() }; state.assertionPhases.set(key, created); return created; } function finishAssertionPhase(phase, error) { phase.endedAtMs = Date.now(); phase.status = error === void 0 ? "passed" : "failed"; if (error !== void 0) phase.error = error instanceof Error ? error.message : String(error); } const INSTRUMENTATION_FRAME = /[\\/]\.supercov[\\/](?:node_modules[\\/])?(?:playwright|nodeTest|vitest|runtime|launchSupervisor|nodeAssert|nodeAssertStrict|nodeAssertAdapter|register|resolve-loader)\.(?:js|mjs)(?::|\))/u; // A lexical wrapper runs the assertion in a function of its own, so its // stack had two frames where the author wrote one: the function Supercov // added, at the assertion, and below the runtime's frames the function the // author wrote, at the wrapper. Vitest printed both, `:12:35` and `:12:1`. // They are one frame again: the author's function, where the assertion is. // // The runtime's frames are not always one run. `node:assert` called through // its module is wrapped a second time, so an assertion that fails there has // frames of the runtime above the added function too, and Node's own frame // for `AsyncLocalStorage.run` lies among those below it: Mocha printed the // added function, that frame and the author's function, three for one. const NODE_FRAME = /^\s*at .*\(?node:internal\//u; const CARRIER_FRAME = /^\s*at AsyncLocalStorage\.run \(node:internal\//u; // An error keeps as many frames as `Error.stackTraceLimit` says, ten unless // someone changed it, counted from where it was made. The runtime's frames // were counted among them, so the author's own fell off the end: a failed // `node:assert` under node:test kept the function Supercov added and lost // the test's, and a test's stack lost the runner's frames below it. While // the runtime's frames are on the stack there is room for them, and what is // left when they are taken out is cut to the length the author asked for. const OWN_ROOM = 24; function withStackRoom(callback) { const limit = Error.stackTraceLimit; if (typeof limit !== "number" || !Number.isFinite(limit) || limit <= 0) return callback(); Error.stackTraceLimit = limit + OWN_ROOM; try { return callback(); } finally { // Unless the code it ran set a limit of its own. if (Error.stackTraceLimit === limit + OWN_ROOM) Error.stackTraceLimit = limit; } } function withinStackLimit(lines) { const limit = Error.stackTraceLimit; if (typeof limit !== "number" || !Number.isFinite(limit) || limit < 0) return lines; let frames = 0; return lines.filter((line) => !/^\s*at /.test(line) || ++frames <= limit); } function cleanInstrumentationStack(error, lexical = false) { if (!error || typeof error !== "object" || typeof error.stack !== "string") return error; const lines = error.stack.split("\n"); const hidden = lines.map((line, index) => index > 0 && INSTRUMENTATION_FRAME.test(line)); if (!hidden.includes(true)) return error; const frame = /^(\s*at (?:async )?)(?:(.*?) \()?(.*?:\d+:\d+)\)?$/; const file = (location) => location.replace(/:\d+:\d+$/, ""); // The function Supercov added is the frame above a run of the runtime's // that ends at a frame of the same file: the author's. let merged; let at = -1; for (let start = 2; lexical && !merged && start < lines.length; start += 1) { if (!hidden[start] || hidden[start - 1]) continue; let last = start; for (let index = start; index < lines.length && (hidden[index] || NODE_FRAME.test(lines[index])); index += 1) { if (hidden[index]) last = index; } const added = frame.exec(lines[start - 1]); const written = last + 1 < lines.length ? frame.exec(lines[last + 1]) : null; // Both are frames of the author's file, or the error is another's. A name // on the added one comes from a source map (Jest names a frame by what is // called at its position), and it is the name the author's line would // have; the function Supercov added has none of its own. if (added && written && file(added[3]) === file(written[3])) { const named = added[2] !== void 0 && added[2] !== ""; at = start - 1; merged = { last: last + 1, text: named || written[2] === void 0 ? lines[at] : `${written[1]}${written[2]} (${added[3]})` }; } start = last; } const visible = lines.flatMap((line, index) => { if (merged && index === at) return [merged.text]; if (merged && index > at && index <= merged.last) return []; // Node's frame for running code under Supercov goes with the runtime's // frames around it. if (CARRIER_FRAME.test(line) && (hidden[index - 1] || hidden[index + 1])) return []; return hidden[index] ? [] : [line]; }); try { error.stack = withinStackLimit(visible).join("\n"); } catch (e) { } return error; } function withNodeAssertionPhase(operation, source, callback) { var _a8; const lexical = typeof source === "string"; const context = currentRequestContext(); const scope = context.scope; // No test is known to be running: a runner Supercov has no adapter in, such // as Jest started from another tool's process. The assertion still fails // with the frames its author would see. if (!scope) { try { return withStackRoom(callback); } catch (error) { throw cleanInstrumentationStack(error, lexical); } } // A lexically instrumented occurrence is an authored assertion site in its // own right, even when it runs inside another assertion's callback: the // validator passed to assert.throws is the ordinary case, and its inner // assertions are what claim *what* the error says. Skipping every nested // phase left those with no passing occurrence, so they could never earn // credit however carefully they were mapped. // // What must still be skipped is the same call seen twice -- the module proxy // firing inside the lexical wrapper. That path has no lexical source and // arrives as a lazy stack fallback, so the shape of `source` tells them // apart without comparing coordinates the transform has moved. const nested = context.phaseId && assertionPhaseState(scope).phaseIds.has(context.phaseId); if (nested && typeof source !== "string") return callback(); // A lexical occurrence already identifies its source. Stack fallback is lazy // and qualified so transformed coordinates cannot impersonate original ones. if (typeof source === "function") source = source(); const bridged = (_a8 = runtimeGlobal.__SUPERCOV_ASSERTION_PHASE_BRIDGE__) == null ? void 0 : _a8.call(runtimeGlobal, operation, source, callback); if (bridged == null ? void 0 : bridged.handled) return bridged.value; const attempt = assertionPhaseState(scope); const phase = __spreadProps(__spreadValues({ id: `${scope.attemptId}:assertion:${++attempt.counter}`, kind: "assertion", operation }, source ? { source } : {}), { startedAtMs: Date.now() }); attempt.phases.push(phase); attempt.phaseIds.add(phase.id); const phaseObserver = runtimeGlobal.__SUPERCOV_ASSERTION_PHASE_STARTED__; if (phaseObserver) phaseObserver(scope, phase); try { const result = withStackRoom(() => withCoverageCarrier({ version: 1, scope, phaseId: phase.id }, callback)); if (result && typeof result.then === "function") return Promise.resolve(result).then((value) => { finishAssertionPhase(phase); return value; }, (error) => { finishAssertionPhase(phase, error); throw cleanInstrumentationStack(error, lexical); }); finishAssertionPhase(phase); return result; } catch (error) { finishAssertionPhase(phase, error); throw cleanInstrumentationStack(error, lexical); } } // Callee binding preserves receiver, getter/evaluation order, spreads and the // original await/yield placement. Only the matcher call opens the phase. function bindNodeAssertionPhase(operation, source, target, property = null) { const callback = property === null ? target : target[property]; const receiver = property === null ? undefined : target; return (...args) => withNodeAssertionPhase(operation, source, () => Reflect.apply(callback, receiver, args)); } // withCoverageCarrier for code that runs in place rather than in a callback: // the carrier holds until the returned function restores what it replaced. // Opened and restored within one synchronous run, it is what run() does. function enterCoverageCarrier(carrier) { if (!serverPhaseStorage) return () => { }; const previousStore = serverPhaseStorage.getStore(); const previousEpoch = state.probeV2Clock.e; const fast = state.probeV2Clock.fast; const context = __spreadValues(__spreadValues({}, carrier.scope ? { scope: carrier.scope } : {}), carrier.phaseId ? { phaseId: carrier.phaseId } : {}); serverPhaseStorage.enterWith(context); if (fast) activateProbeV2Context(context); return () => { serverPhaseStorage.enterWith(previousStore); if (fast) state.probeV2Clock.e = previousEpoch; }; } var inertAssertionPhase = { close: (value) => value, fail: (error) => error }; // The phase withNodeAssertionPhase runs its callback in, opened before a // TypeScript assertion's operands and closed after its call. The rewrite calls // the assertion in place because TypeScript narrows nothing into a callback: // `prior < id` under `if (prior !== undefined)`, an evolving `const ids = []` // and an `asserts` signature all failed to typecheck once wrapped in one. function openNodeAssertionPhase(operation, source) { var _a8; const context = currentRequestContext(); const scope = context.scope; if (!scope) return inertAssertionPhase; const nested = context.phaseId && assertionPhaseState(scope).phaseIds.has(context.phaseId); if (nested && typeof source !== "string") return inertAssertionPhase; if (typeof source === "function") source = source(); let carrier; let finish; let release; const bridged = (_a8 = runtimeGlobal.__SUPERCOV_ASSERTION_PHASE_OPENER__) == null ? void 0 : _a8.call(runtimeGlobal, operation, source); if (bridged) { ({ carrier, finish, release } = bridged); } else { const attempt = assertionPhaseState(scope); const phase = __spreadProps(__spreadValues({ id: `${scope.attemptId}:assertion:${++attempt.counter}`, kind: "assertion", operation }, source ? { source } : {}), { startedAtMs: Date.now() }); attempt.phases.push(phase); attempt.phaseIds.add(phase.id); const phaseObserver = runtimeGlobal.__SUPERCOV_ASSERTION_PHASE_STARTED__; if (phaseObserver) phaseObserver(scope, phase); carrier = { version: 1, scope, phaseId: phase.id }; finish = (error) => finishAssertionPhase(phase, error); } const restore = enterCoverageCarrier(carrier); let open = true; const settle = () => { if (!open) return false; open = false; restore(); release == null ? void 0 : release(); return true; }; return { close(value) { if (!settle()) return value; if (value && typeof value.then === "function") return Promise.resolve(value).then((resolved) => { finish(); return resolved; }, (error) => { finish(error); throw cleanInstrumentationStack(error); }); finish(); return value; }, fail(error) { if (settle()) finish(error); return cleanInstrumentationStack(error); } }; } function takeNodeAssertionPhases(scope) { var _a8, _b; const key = attemptKey(scope); const phases = (_b = (_a8 = state.assertionPhases.get(key)) == null ? void 0 : _a8.phases) != null ? _b : []; state.assertionPhases.delete(key); return phases; } function bindCoverageContext(callback, carrier = coverageCarrier()) { return function boundCoverageContext(...args) { return withCoverageCarrier(carrier, () => Reflect.apply(callback, this, args)); }; } function coverageContextHeaders() { const context = currentRequestContext(); if (!context.scope) return {}; return __spreadValues({ [COVERAGE_SCOPE_HEADER]: encodeCoverageScope(context.scope) }, context.phaseId ? { [COVERAGE_PHASE_HEADER]: context.phaseId } : {}); } function coverageContextEnvironment() { return { [COVERAGE_CARRIER_ENV]: encodeCoverageCarrier(coverageCarrier()) }; } function installServerFetchPropagation() { if (isBrowser || runtimeGlobal.__SUPERCOV_FETCH_PATCHED__ || typeof globalThis.fetch !== "function") return; const originalFetch = globalThis.fetch.bind(globalThis); globalThis.fetch = ((input, init) => { var _a8; const coverage = coverageContextHeaders(); if (Object.keys(coverage).length === 0) return originalFetch(input, init); const headers = new Headers((_a8 = init == null ? void 0 : init.headers) != null ? _a8 : input instanceof Request ? input.headers : void 0); for (const [name, value] of Object.entries(coverage)) headers.set(name, value); return originalFetch(input, __spreadProps(__spreadValues({}, init), { headers })); }); runtimeGlobal.__SUPERCOV_FETCH_PATCHED__ = true; } installServerFetchPropagation(); // util.promisify(exec) and util.promisify(execFile) resolve { stdout, stderr } // through a function Node keeps on the original, and that function calls the // original. A wrapper carries its own, which calls the wrapper, or a promisified // call resolves the bare stdout string and skips the wrapper. const promisifyCustom = Symbol.for("nodejs.util.promisify.custom"); function keepPromisifiedShape(original, wrapper) { if (typeof original[promisifyCustom] !== "function") return wrapper; Object.defineProperty(wrapper, promisifyCustom, { configurable: true, value: (...args) => { let settle, reject; const promise = new Promise((ok, fail) => { settle = ok; reject = fail; }); promise.child = wrapper(...args, (error, stdout, stderr) => { if (error !== null) { error.stdout = stdout; error.stderr = stderr; reject(error); } else settle({ stdout, stderr }); }); return promise; } }); return wrapper; } function installServerChildPropagation() { var _a8; if (isBrowser || runtimeGlobal.__SUPERCOV_CHILD_PATCHED__ || typeof process === "undefined") return; const getBuiltinModule = process.getBuiltinModule; const child = getBuiltinModule == null ? void 0 : getBuiltinModule("node:child_process"); if (!child) return; const mutableChild = child; // (file, args?, options?, callback?): options follow an argument list, or an // explicit null or undefined in its place. exec itself calls execFile as // (file, options, callback), and that object is the options, not a list. const optionIndex = (method, args) => { if (method === "spawn" || method === "spawnSync" || method === "fork" || method === "execFile" || method === "execFileSync") return Array.isArray(args[1]) || args[1] == null && args.length > 2 ? 2 : 1; return 1; }; for (const method of [ "exec", "execFile", "execFileSync", "execSync", "fork", "spawn", "spawnSync" ]) { const original = mutableChild[method]; if (typeof original !== "function") continue; mutableChild[method] = keepPromisifiedShape(original, function(...args) { var _a9; const index = optionIndex(method, args); const existing = args[index] && typeof args[index] === "object" ? args[index] : {}; // An env the caller passed is the child's whole environment -- execa's // extendEnv: false keeps the parent's CI out of chalk's fixtures -- so // only the carrier joins it. Without one, the child inherits ours. const options = __spreadProps(__spreadValues({}, existing), { env: __spreadValues(__spreadValues({}, (_a9 = existing.env) != null ? _a9 : process.env), coverageContextEnvironment()) }); const scoped = [...args]; if (typeof scoped[index] === "function") scoped.splice(index, 0, options); else scoped[index] = options; return Reflect.apply(original, child, scoped); }); } const moduleBuiltin = getBuiltinModule == null ? void 0 : getBuiltinModule("node:module"); (_a8 = moduleBuiltin == null ? void 0 : moduleBuiltin.syncBuiltinESMExports) == null ? void 0 : _a8.call(moduleBuiltin); runtimeGlobal.__SUPERCOV_CHILD_PATCHED__ = true; } installServerChildPropagation(); /** * Phase ids are minted as `:phase:`, so a phase can be checked * against the attempt it claims to belong to without a lookup. */ function phaseBelongsToAttempt(phaseId, attemptId) { return typeof phaseId === "string" && typeof attemptId === "string" && attemptId.length > 0 && phaseId.startsWith(`${attemptId}:`); } function currentPhaseId() { if (runtimeGlobal.__SUPERCOV_PHASE_ID__) return runtimeGlobal.__SUPERCOV_PHASE_ID__; if (!isBrowser) { // Async work an earlier test started -- a stream, a socket, a timer -- // keeps that test's context and can run after the next test has begun. // Its phase belongs to the earlier attempt, and tagging this test's // evidence with it made the whole run unreadable ("unknown frontend phase // reference"): axios's HTTP/2 upload tests did it three times in 2,201. // Where the process knows which test is running, only that test's phases // are honoured; a server process, which learns its test from the request, // keeps the carried phase. const context = currentRequestContext(); const active = runtimeGlobal.__SUPERCOV_ACTIVE_SCOPE__; if (context.phaseId && active && !phaseBelongsToAttempt(context.phaseId, active.attemptId)) return void 0; return context.phaseId; } try { // The stored phase is per origin, so in a browser context that outlives // its test (a persistent profile shared by a whole worker) it still holds // the previous test's last phase when the next test's document loads. A // phase from another attempt would tag this test's evidence with a phase // it never reported, which the archive rightly rejects; only a phase of // the current attempt is honoured. const local = localStorage.getItem(phaseStorageKey); const attemptId = runtimeGlobal.__SUPERCOV_MCDC_TEST_ID__ != null ? runtimeGlobal.__SUPERCOV_MCDC_TEST_ID__ : testId; if (local && phaseBelongsToAttempt(local, attemptId)) return local; return void 0; } catch (e) { return void 0; } } function requestHeaders(value) { if (!value || typeof value !== "object") return void 0; const directHeaders = value.headers; const request = directHeaders && typeof directHeaders === "object" ? value : value.request; if (!request || typeof request !== "object") return void 0; const headers = request.headers; if (!headers || typeof headers !== "object") return void 0; const get = headers.get; if (typeof get === "function") return { get(name) { return Reflect.apply(get, headers, [name]); } }; const values = headers; return Object.keys(values).length > 0 ? { get(name) { var _a8; return (_a8 = values[name]) != null ? _a8 : values[name.toLowerCase()]; } } : void 0; } function requestCoverageContext(value) { var _a8, _b; const headers = requestHeaders(value); if (!headers) return void 0; const rawCookie = headers.get("cookie"); const cookies = /* @__PURE__ */ new Map(); if (typeof rawCookie === "string") { for (const part of rawCookie.split(";")) { const separator = part.indexOf("="); if (separator < 0) continue; const name = part.slice(0, separator).trim(); const encoded = part.slice(separator + 1).trim(); try { cookies.set(name, decodeURIComponent(encoded)); } catch (e) { } } } // A frame of the app on another of its hosts carries only the cookies // made to cross sites. const encodedScope = (_a8 = headers.get(COVERAGE_SCOPE_HEADER)) != null ? _a8 : cookies.has(COVERAGE_SCOPE_COOKIE) ? cookies.get(COVERAGE_SCOPE_COOKIE) : cookies.get(COVERAGE_SCOPE_SITE_COOKIE); const rawPhaseId = (_b = headers.get(COVERAGE_PHASE_HEADER)) != null ? _b : cookies.has(COVERAGE_PHASE_COOKIE) ? cookies.get(COVERAGE_PHASE_COOKIE) : cookies.get(COVERAGE_PHASE_SITE_COOKIE); const scope = decodeCoverageScope(typeof encodedScope === "string" ? encodedScope : void 0); // The phase cookie outlives a test in a shared browser context just like // the stored phase does (see currentPhaseId); a request carrying a scope // and a phase from different attempts keeps the scope and drops the phase. const phaseId = typeof rawPhaseId === "string" && rawPhaseId.length > 0 && (!scope || phaseBelongsToAttempt(rawPhaseId, scope.attemptId)) ? rawPhaseId : void 0; return __spreadValues(__spreadValues({}, scope ? { scope } : {}), phaseId ? { phaseId } : {}); } // Keep connection ownership on the emitter, without changing listener // identity (removeListener/off and once still see the original callbacks). if (runtimeGlobal.__SUPERCOV_EMITTER_CONTEXT_MAPS__ == null) runtimeGlobal.__SUPERCOV_EMITTER_CONTEXT_MAPS__ = new Map(); const emitterContextMaps = runtimeGlobal.__SUPERCOV_EMITTER_CONTEXT_MAPS__; const emitterCoverageContexts = emitterContextMaps.get(runtimeInstance) || new WeakMap(); emitterContextMaps.set(runtimeInstance, emitterCoverageContexts); if (runtimeGlobal.__SUPERCOV_EMITTER_PATCHED_INSTANCES__ == null) runtimeGlobal.__SUPERCOV_EMITTER_PATCHED_INSTANCES__ = new Set(); const patchedEmitterInstances = runtimeGlobal.__SUPERCOV_EMITTER_PATCHED_INSTANCES__; // Which tests this process served, and when it served a request that named // none, in the file `register.mjs` named for it: the project files it loaded // and read are reached by those tests, and a change to one is a change for // them alone (`tests affected`, `merge`). Its CommonJS modules are noted // here, once each, as requests come; the loader notes its ES modules. var supportNoted = { served: new Set(), modules: new Set(), lastUnscoped: 0 }; function noteSupport(scope) { const file = typeof process !== "undefined" && process.env ? process.env.__SUPERCOV_SUPPORT_FILE : void 0; if (!file) return; const fs = getFs(); if (!fs) return; const lines = []; if (scope) { if (!supportNoted.served.has(scope.testId)) { supportNoted.served.add(scope.testId); lines.push({ served: scope.testId }); } } else { const now = Date.now(); if (now - supportNoted.lastUnscoped >= 5) { supportNoted.lastUnscoped = now; lines.push({ unscoped: now }); } } try { const moduleBuiltin = typeof process.getBuiltinModule === "function" ? process.getBuiltinModule("node:module") : void 0; const cache = moduleBuiltin && moduleBuiltin._cache; const root = process.env.SUPERCOV_PROJECT_ROOT; // The in-thread module hooks count every load (resolve-loader.mjs): a // cache nothing was loaded into since the last request holds nothing // new. Listing a Next server's thousands of keys on every request was // the most of its time any of Supercov's code took. Without the count // (off-thread hooks), every request looks. const loads = runtimeGlobal.__SUPERCOV_MODULE_LOADS__; const unchanged = typeof loads === "number" && loads === supportNoted.loads; supportNoted.loads = loads; if (cache && root && !unchanged) { for (const name of Object.keys(cache)) { // Each is looked at once, whether it is noted or not. if (supportNoted.modules.has(name)) continue; supportNoted.modules.add(name); // The copy lives under `.supercov/`: the project root decides. const inside = name.indexOf(root) === 0 ? name.slice(root.length).replace(/^[\\/]/, "") : ""; if (inside === "" || /^\.supercov[\\/]/.test(inside) || /(?:^|[\\/])node_modules[\\/]/.test(inside)) continue; lines.push({ loaded: name }); } } } catch (e) { } if (lines.length === 0) return; try { fs.appendFileSync(file, lines.map((line) => JSON.stringify(line)).join("\n") + "\n"); } catch (e) { } } function installNodeRequestPropagation() { if (isBrowser || patchedEmitterInstances.has(runtimeInstance) || typeof process === "undefined") return; const builtin = (name) => typeof process.getBuiltinModule === "function" ? process.getBuiltinModule(name) : void 0; const events = builtin("node:events"); const http = builtin("node:http"); const https = builtin("node:https"); const EventEmitter = events && events.EventEmitter; const Server = http && http.Server; const SecureServer = https && https.Server; if (!EventEmitter) return; const original = EventEmitter.prototype.emit; // The test a request is for, worked out once, from whichever sees it first. const requestContexts = new WeakMap(); const owningRequest = (server, request, response) => { if (requestContexts.has(request)) return requestContexts.get(request); let context = emitterCoverageContexts.get(server); // HTTP headers establish ownership even when Express/SDK listeners and // the server process were created by a shared before hook. const incoming = requestCoverageContext(request); noteSupport(incoming && incoming.scope); if (incoming) context = incoming.scope ? incoming : context != null ? context : currentRequestContext(); if (incoming && incoming.scope) noteServedAttempt(incoming.scope); // A request that names no test, to a server no test owns, is numbered: // the report credits its work to the test running when it came. if (incoming && serverPhaseStorage && !(context && (context.scope || context.phaseId))) context = { request: nextUnscopedRequest() }; // Node emits a request's body and its response's events outside the // handler's context, so a handler that reads the body -- `req.on('end')` // -- ran as no test's. The request and response carry it with them. if (incoming && context) { for (const emitter of [request, response]) { if (emitter && typeof emitter === "object" && typeof emitter.emit === "function") emitterCoverageContexts.set(emitter, context); } } if (request && typeof request === "object") requestContexts.set(request, incoming ? context : void 0); return incoming ? context : void 0; }; // Node publishes every request here before it emits it. An `emit` of the // server's own, defined before this patch by a preload that called the // emit it found, hid every request from the patch below, and what ran on // the request's events -- a page rendered as the response went out -- // was credited to no test. Nothing hides this channel. try { const channels = builtin("node:diagnostics_channel"); if (channels && typeof channels.subscribe === "function") channels.subscribe("http.server.request.start", (message) => { if (message && message.request) owningRequest(message.server, message.request, message.response); }); } catch {} EventEmitter.prototype.emit = function(event, ...args) { let context = emitterCoverageContexts.get(this); if ((event === "request" || event === "upgrade") && ((Server && this instanceof Server) || (SecureServer && this instanceof SecureServer))) { const owner = owningRequest(this, args[0], args[1]); if (owner) context = owner; } const invoke = () => Reflect.apply(original, this, [event, ...args]); try { if (context && context.request && !context.scope) return serverPhaseStorage.run(context, () => withProbeV2Context(context, invoke)); return context ? withCoverageCarrier({ version: 1, ...context }, invoke) : invoke(); } finally { if (event === "close") emitterCoverageContexts.delete(this); } }; patchedEmitterInstances.add(runtimeInstance); } installNodeRequestPropagation(); function withRequestPhase(handler, event) { if (!serverPhaseStorage) return handler; const registeredContext = currentRequestContext(); return function coverageRequestPhase(...args) { var _a8, _b, _c, _d; const requestContext = args.map((argument) => requestCoverageContext(argument)).find((context2) => context2 !== void 0); // An untagged request to a test-owned server must not erase that server's // owner. Shared servers have no captured test scope and stay unattributed. const inheritedContext = requestContext && requestContext.scope ? {} : registeredContext.scope ? registeredContext : requestContext === void 0 ? currentRequestContext() : {}; const context = __spreadValues(__spreadValues({}, ((_a8 = requestContext == null ? void 0 : requestContext.scope) != null ? _a8 : inheritedContext.scope) ? { scope: (_b = requestContext == null ? void 0 : requestContext.scope) != null ? _b : inheritedContext.scope } : {}), ((_c = requestContext == null ? void 0 : requestContext.phaseId) != null ? _c : inheritedContext.phaseId) ? { phaseId: (_d = requestContext == null ? void 0 : requestContext.phaseId) != null ? _d : inheritedContext.phaseId } : {}); if (requestContext !== void 0 && !context.scope) context.request = nextUnscopedRequest(); const invoke = () => { if (event === "connection" && context.scope && args[0] && typeof args[0] === "object" && typeof args[0].emit === "function") emitterCoverageContexts.set(args[0], context); return Reflect.apply(handler, this, args); }; return requestContext !== void 0 || context.scope || context.phaseId ? serverPhaseStorage.run(context, () => withProbeV2Context(context, invoke)) : invoke(); }; } // Whether `event` was already recorded, recording it if not. Kept per phase, // so a first hit looks up its id alone: one key joining the phase, the type // and the id was built and hashed for every first hit of every test. function eventSeen(seen, type, id, vector, phaseId) { const phase = phaseId != null ? phaseId : "unscoped"; let keys = builtinMapGet.call(seen, phase); if (keys === void 0) { keys = /* @__PURE__ */ new Set(); builtinMapSet.call(seen, phase, keys); } const key = type === "hit" ? id : `${type}\0${type === "decision" ? `${id}:${vectorKey(vector)}` : id}`; if (builtinSetHas.call(keys, key)) return true; builtinSetAdd.call(keys, key); return false; } // The phase eventSeen keys an event under: an event object built without a // falsy phase (hitEvent, decisionEvent) had none, which is "unscoped". function phaseEventKey(phaseId) { return phaseId ? phaseId : void 0; } // An event's fields into the columns, unless it was recorded already; what // hitEvent or decisionEvent would build of them is what coverageSnapshot // gives back. function recordEvent(into, type, id, vector, timestampMs, phaseId, environment) { if (eventSeen(into.eventKeys, type, id, vector, phaseEventKey(phaseId))) return false; const log = into.eventLog; log.type[log.type.length] = type; log.id[log.id.length] = id; log.vector[log.vector.length] = vector; log.timestampMs[log.timestampMs.length] = timestampMs; log.phaseId[log.phaseId.length] = phaseId; log.environment[log.environment.length] = environment; return true; } function recordBrowserEvent(type, id, vector, timestampMs, phaseId, environment) { if (!recordEvent(state, type, id, vector, timestampMs, phaseId, environment)) return false; workerEvidenceChanged(); return true; } // A hit is recorded once per context, as a statement probe's is: selections, // optional chains, defaults and loops reach here on every evaluation, and // each built and serialized its record before the transport dropped it as a // repeat. function coverageHit(id) { const clock = state.probeV2Clock; if (clock.fast && state.hitEpochs !== void 0 && builtinMapGet.call(state.hitEpochs, id) === clock.e) return; recordCoverageHit(id); } // resetCoverage forces a fresh epoch, so a hit skipped above was recorded in // this epoch after the last reset and is in state.hits already. function recordCoverageHit(id) { builtinSetAdd.call(state.hits, id); const clock = state.probeV2Clock; let epoch = clock.e; if (!clock.fast) { const previousEpoch = clock.e; activateProbeV2Context(currentRequestContext()); epoch = clock.e; clock.e = previousEpoch; } else if (epoch !== epoch) { epoch = resolveProbeV2Epoch(); } if (!state.hitEpochs) state.hitEpochs = /* @__PURE__ */ new Map(); if (builtinMapGet.call(state.hitEpochs, id) === epoch) return; builtinMapSet.call(state.hitEpochs, id, epoch); const timestampMs = Date.now(); const phaseId = currentPhaseId(); if (isBrowser) { if (recordBrowserEvent("hit", id, void 0, timestampMs, phaseId, "browser")) persistBrowser(); } else if (state.runtimeSnapshots) { // What appendServer does with a snapshot-kept run's record, without the // record: an object built per first hit only to be read once. recordBrowserEvent("hit", id, void 0, timestampMs, phaseId, "server"); } else { appendServer(phaseId ? { type: "hit", id, timestampMs, phaseId } : { type: "hit", id, timestampMs }); } } // A first hit's event, built as one literal in the order the spread helpers // gave its keys: they walked every key of three objects for each first hit // of every statement in every test. function hitEvent(id, timestampMs, phaseId, environment) { return phaseId ? { type: "hit", id, timestampMs, phaseId, environment } : { type: "hit", id, timestampMs, environment }; } function decisionEvent(id, vector, timestampMs, phaseId, environment) { return phaseId ? { type: "decision", id, vector, timestampMs, phaseId, environment } : { type: "decision", id, vector, timestampMs, environment }; } // A module carries the key of its table of ids, which the manifest holds, and // how many points and decisions it numbers: evidence names a probe by the key // and its place, `~p.` or `~d.`, and the report reads // the id there. A place whose id an earlier place has is named as that one, // as it was one id: a selection's two short outcomes are one point. function probeAliases(flat) { const aliases = /* @__PURE__ */ new Map(); for (let index = 0; flat && index + 1 < flat.length; index += 2) aliases.set(flat[index], flat[index + 1]); return aliases; } function probePlaceName(names, aliases, count, kind, key, place) { if (!(place >= 0 && place < count)) return void 0; let name = names[place]; if (name === void 0) { const first = builtinMapGet.call(aliases, place); name = names[place] = first === void 0 ? `~${kind}${key}.${place}` : probePlaceName(names, aliases, count, kind, key, first); } return name; } function probePointName(file, place) { return probePlaceName(file.pointNames, file.pointAliases, file.pointCount, "p", file.key, place); } function probeDecisionName(file, place) { return probePlaceName(file.decisionNames, file.decisionAliases, file.decisionWidths.length, "d", file.key, place); } function registerProbeV2(definition) { var _a8, _b; const pointCount = definition.points; const file = { key: definition.key, pointCount, pointNames: [], pointAliases: probeAliases(definition.pointAliases), decisionNames: [], decisionAliases: probeAliases(definition.decisionAliases), decisionWidths: definition.decisionWidths, clock: state.probeV2Clock, hitEpochs: new Uint32Array(pointCount), // A narrow decision's vectors in an array, a wide one's in a Map, told // apart by `size`, which only the Map has: `instanceof Uint32Array` read // the global on every evaluation, and under Vitest's jsdom environment // each read is a getter call, most of a canvas app's measured unit time. decisionEpochs: definition.decisionWidths.map((width) => width <= 6 ? new Uint32Array(2 * 3 ** width) : /* @__PURE__ */ new Map()), pendingDefaults: new Uint32Array(definition.defaultCount || 0), // A selection's outcomes -- short falsy, short truthy, right falsy, right // truthy -- are four consecutive points per site from the first index. selectionPoints: definition.selectionPoints, // What selectEndV2 and selectNextV2 read, for each tree of more than two // leaves. selectionSteps: (definition.selectionTrees || []).map((tree) => tree[0]), selectionChoices: (definition.selectionTrees || []).map((tree) => tree[1]), none: optionalCallEmptySpread }; rememberProbeV2File(file); // What a probe calls: this file's hit, by place alone. Outside a loop the // probe is the call alone and this makes its check, so it stays small // enough for V8 to inline where the code is hot. The epoch is NaN wherever // the clock is not fast, which no recorded epoch equals, so the check needs // no `fast` of its own (coverageHitV2's). const hitEpochs = file.hitEpochs; const clock = file.clock; file.hit = (index) => { if (hitEpochs[index] !== clock.e) recordCoverageHitV2(file, index); }; if (isBrowser) { state.probeV2Clock.fast = true; activateProbeV2Key(`browser\0${(_a8 = runtimeGlobal.__SUPERCOV_MCDC_TEST_ID__) != null ? _a8 : testId}\0${(_b = runtimeGlobal.__SUPERCOV_PHASE_ID__) != null ? _b : "unscoped"}`); } else { installProbeV2AsyncHook(); // The hook sets the epoch when an async callback begins. Code that runs // before any did -- a script's own top level -- found it NaN, which no // epoch equals, so every probe there took the slow path every time: a // million-iteration loop ran 1,700 times slower than without Supercov. if (state.probeV2Clock.fast && Number.isNaN(state.probeV2Clock.e)) activateProbeV2Context(currentRequestContext()); } return file; } // Vitest evaluates a module again for every test file, and each evaluation // registers its file anew: held strongly, every evaluation's arrays stayed // alive for the worker's life, and the collector walked them all. A file no // module holds runs no probe, so the wrap has nothing of it to clear, and the // set is swept of them as it doubles. function rememberProbeV2File(file) { const files = state.probeV2Files; if (typeof WeakRef !== "function") { files.add(file); return; } files.add(new WeakRef(file)); if (files.size < state.probeV2FilesSweepAt) return; for (const held of files) { if (held.deref() === void 0) files.delete(held); } state.probeV2FilesSweepAt = Math.max(1024, 2 * files.size); } // Every repeat of a probe in the same context ends at the first check, so it // stays small enough for V8 to inline into the instrumented function; the // rest runs once per context. minimatch's backtracking guard test needs a // pathological match inside a second, and the full body in every call put it // at ten times the uninstrumented time. function coverageHitV2(file, index) { const clock = file.clock; if (clock.fast && file.hitEpochs[index] === clock.e) return; recordCoverageHitV2(file, index); } function recordCoverageHitV2(file, index) { const id = probePointName(file, index); if (!id) return; const fallbackEpoch = !file.clock.fast; const previousEpoch = file.clock.e; if (fallbackEpoch) activateProbeV2Context(currentRequestContext()); else if (previousEpoch !== previousEpoch) resolveProbeV2Epoch(); try { const epoch = file.clock.e; if (file.hitEpochs[index] === epoch) return; file.hitEpochs[index] = epoch; // New in this context for this file: recordCoverageHit makes the check // coverageHit would, across files and aliases, without a second lookup. recordCoverageHit(id); const selections = file.selectionPoints; if (selections !== void 0 && index >= selections[0] && index < selections[0] + 4 * selections[1]) recordLogicalOutcome(id, index - selections[0] & 3); } finally { if (fallbackEpoch) file.clock.e = previousEpoch; } } function decodeProbeV2Vector(conditionCount, encoded, outcome) { if (!Number.isSafeInteger(conditionCount) || conditionCount < 0 || conditionCount > 32 || !Number.isSafeInteger(encoded) || encoded < 0) return void 0; const values = []; let remaining = encoded; for (let index = 0; index < conditionCount; index += 1) { const digit = remaining % 3; values[index] = digit === 0 ? null : digit === 2; remaining = Math.floor(remaining / 3); } return remaining === 0 ? { values, outcome } : void 0; } function mcdcEndV2(file, decisionIndex, encoded, value) { // Nothing evaluated: a decision used as a value in a tree whose evaluation // never reached it. Every evaluation evaluates its first condition. if (encoded === 0) return value; const clock = file.clock; if (clock.fast) { const seen = file.decisionEpochs[decisionIndex]; if (seen !== void 0 && seen.size === void 0 && seen[encoded * 2 + (value ? 1 : 0)] === clock.e) return value; } return recordMcdcEndV2(file, decisionIndex, encoded, value); } function recordMcdcEndV2(file, decisionIndex, encoded, value) { const id = probeDecisionName(file, decisionIndex); if (!id || !Number.isSafeInteger(encoded) || encoded < 0) return value; const outcome = Boolean(value); const vectorIndex = encoded * 2 + (outcome ? 1 : 0); if (!Number.isSafeInteger(vectorIndex)) return value; const fallbackEpoch = !file.clock.fast; const previousEpoch = file.clock.e; if (fallbackEpoch) activateProbeV2Context(currentRequestContext()); else if (previousEpoch !== previousEpoch) resolveProbeV2Epoch(); try { const epoch = file.clock.e; const seen = file.decisionEpochs[decisionIndex]; if (!seen) return value; if (seen.size === void 0) { if (seen[vectorIndex] === epoch) return value; seen[vectorIndex] = epoch; } else { if (builtinMapGet.call(seen, vectorIndex) === epoch) return value; builtinMapSet.call(seen, vectorIndex, epoch); } if (!builtinMapHas.call(state.decisions, id)) builtinMapSet.call(state.decisions, id, { id, vectors: /* @__PURE__ */ new Map() }); const vector = decodeProbeV2Vector(file.decisionWidths[decisionIndex], encoded, outcome); return vector ? mcdcEnd({ id, values: vector.values }, value) : value; } finally { if (fallbackEpoch) file.clock.e = previousEpoch; } } function selectionBegin(shortId, rightId) { return { shortId, rightId, rightEvaluated: false }; } function applyInferredName(value, inferredName) { if (inferredName && typeof value === "function" && value.name === "") { Object.defineProperty(value, "name", { __proto__: null, value: inferredName, configurable: true }); } return value; } var hostNamesParenthesizedAssignments = (() => { let candidate; candidate = function() { }; return candidate.name === "candidate"; })(); function parenthesizedAssignmentValue(value, inferredName) { return hostNamesParenthesizedAssignments ? applyInferredName(value, inferredName) : value; } function selectionRight(frame, value, inferredName) { frame.rightEvaluated = true; return applyInferredName(value, inferredName); } var selectionOutcomeKeys = ["SF", "ST", "RF", "RT"]; var selectionBranchIds = /* @__PURE__ */ new Map(); function selectionEnd(frame, value) { const right = frame.rightEvaluated; coverageHit(right ? frame.rightId : frame.shortId); recordSelectionOutcome(frame.shortId, (right ? 2 : 0) + (value ? 1 : 0)); return value; } // Per-operand outcomes for the verifier: which side was selected and whether // the result is truthy. With the operator (known from the manifest) this gives // each operand's outcome. The branch id is cut from the outcome's id -- its // short or right id, which share it -- once, not on every evaluation. function recordSelectionOutcome(id, outcome) { let branchId = selectionBranchIds.get(id); if (branchId === void 0) { const separator = id.lastIndexOf(":"); branchId = separator > 0 ? id.slice(0, separator) : null; selectionBranchIds.set(id, branchId); } if (branchId !== null) recordLogicalOutcome(branchId, outcome); } // The outcomes of a selection by its branch id, or by the name of its point // that was hit, whose branch the report reads from the point's id. function recordLogicalOutcome(branchId, outcome) { let vectors = builtinMapGet.call(state.logicals, branchId); if (!vectors) { vectors = /* @__PURE__ */ new Map(); builtinMapSet.call(state.logicals, branchId, vectors); } const key = selectionOutcomeKeys[outcome]; if (!builtinMapHas.call(vectors, key)) { builtinMapSet.call(vectors, key, { right: outcome >= 2, truthy: (outcome & 1) === 1 }); workerEvidenceChanged(); } } // A JSX expression container has nowhere to put a statement and cannot hold a // bare comma operator, so a rendered expression carries its probe as a call // that returns the value through. Like optionalSelect, it records after the // value evaluates: an expression that throws is reported unevaluated rather // than covered. function renderedValueV2(file, index, value) { coverageHitV2(file, index); return value; } function optionalSelect(shortId, continuedId, value) { coverageHit(value === null || value === void 0 ? shortId : continuedId); return value; } // `a || b` (kind 0), `a && b` (1), `a ?? b` (2), with the program's own // operator between the two calls: the left operand records its short outcome // when it decides the result -- truthy, falsy, present -- and the right one // whether it came out truthy. The outcomes are the selection's four points. function selectShortV2(file, first, value, kind) { if (kind === 0 ? value : kind === 1 ? !value : value !== null && value !== void 0) coverageHitV2(file, value ? first + 1 : first); return value; } function selectRightV2(file, first, value) { coverageHitV2(file, value ? first + 3 : first + 2); return value; } // A leaf of nested selections, `(a && b) || c`: the program's operators stay // between the leaves, so a coverage tool the tests run flattens them into the // one branch it reads without Supercov. Each step after the value names a // selection above the leaf, nearest first, as `first * 4 + code`: code 3 when // the leaf is on its right side, which records that side's outcome, and the // operator's kind (0 `||`, 1 `&&`, 2 `??`) when on its left, which records the // short outcome when the value decides it; otherwise the selection goes on to // its right side, and the leaf decides nothing further up. function selectPathV2(file, value) { for (let index = 2; index < arguments.length; index += 1) { const step = arguments[index]; const code = step & 3; const first = (step - code) / 4; if (code === 3) coverageHitV2(file, value ? first + 3 : first + 2); else if (code === 0 ? value : code === 1 ? !value : value !== null && value !== void 0) coverageHitV2(file, value ? first + 1 : first); else break; } return value; } // A selection tree whose leaves stay the program's own expressions: each is // the last operand of a comma that names it in the site's frame, so a type // checker reading the instrumented copy narrows through `a && a.b` as it does // in the source, and the tree's value is recorded here, once, for the leaf // that produced it. What a leaf before the last decided on the way is known // from where evaluation went next, and is recorded there as plain hits. // Two leaves: the left one is last only when it decided the result. function selectEnd2V2(file, first, value, right) { coverageHitV2(file, first + (right ? 2 : 0) + (value ? 1 : 0)); return value; } // More: the leaf's steps, the ones selectPathV2 takes as arguments, come from // the file's table, whose entry for a tree is `[steps of each leaf, for each // leaf the points each leaf before it has decided by then]`. function selectEndV2(file, tree, value, leaf) { const steps = file.selectionSteps[tree][leaf]; for (let index = 0; index < steps.length; index += 1) { const step = steps[index]; const code = step & 3; const first = (step - code) / 4; if (code === 3) coverageHitV2(file, value ? first + 3 : first + 2); else if (code === 0 ? value : code === 1 ? !value : value !== null && value !== void 0) coverageHitV2(file, value ? first + 1 : first); else break; } return value; } // Where one of several leaves can come before a leaf, the frame says which. // Written out in the program as a choice, it would be a branch of the user's // line to a coverage tool the tests run. function selectNextV2(file, tree, from, to) { const points = file.selectionChoices[tree][to][from]; if (points) for (let index = 0; index < points.length; index += 1) coverageHitV2(file, points[index]); } // `x ||= y`, `x &&= y`, `x ??= y` keep their operator and their single // evaluation of the target: the right side goes through selectRightV2 (or the // named form, for an anonymous function the assignment would have named), and // a site temporary set to 1 after it tells the end whether the assignment was // skipped, which is then the short outcome for the value the target kept. function selectNamedRightV2(file, first, value, inferredName) { coverageHitV2(file, value ? first + 3 : first + 2); return applyInferredName(value, inferredName); } function selectAssignEndV2(file, first, value, right) { if (!right) coverageHitV2(file, value ? first + 1 : first); return value; } // `object?.member`: the short and continued outcomes are two V2 points. // Whether the previous optional link of the chain being evaluated cut it // short. In `a?.b?.c` the object of `?.c` is undefined when `a` is, though // `?.c` never ran: `?.b` says so here and `?.c` records nothing. `links` has // 1 when an earlier link of the chain runs first and 2 when a later one // follows. Every link with a later one writes this and that later one reads // and clears it, so code run in between -- a getter, a call -- that // evaluates chains of its own leaves it as it found it. 4 means the earlier // link is an optional call, whose frame `call` is 2 only if it went ahead. var optionalChainCut = false; function optionalSelectV2(file, first, value, links, call) { if (links & 1 && optionalChainCut || links & 4 && call !== 2) { optionalChainCut = (links & 2) !== 0; return value; } var nullish = value === null || value === void 0; coverageHitV2(file, nullish ? first : first + 1); optionalChainCut = nullish && (links & 2) !== 0; return value; } function optionalCallBegin(shortId, continuedId) { return { shortId, continuedId, reached: false, continued: false }; } function optionalCallReached(frame, value) { frame.reached = true; return value; } // Spread into an optional call's arguments to mark that the call went ahead: // it yields nothing, and allocates nothing per call. var optionalCallDone = { done: true, value: void 0 }; var optionalCallEmptyIterator = { next() { return optionalCallDone; } }; var optionalCallEmptySpread = { [Symbol.iterator]() { return optionalCallEmptyIterator; } }; function optionalCallContinued(frame) { frame.continued = true; return optionalCallEmptySpread; } function optionalCallEnd(frame, value) { if (frame.reached) coverageHit(frame.continued ? frame.continuedId : frame.shortId); return value; } // The site's state, read after the chain: 0 not reached, 1 reached and // short-circuited, 2 called. Short and continued are two V2 points. function optionalCallEndV2(file, first, value, state) { if (state) coverageHitV2(file, state === 2 ? first + 1 : first); return value; } function defaultSelected(defaultId, value, inferredName) { var _a8; pendingDefaults.set(defaultId, ((_a8 = pendingDefaults.get(defaultId)) != null ? _a8 : 0) + 1); return applyInferredName(value, inferredName); } function defaultEntered(defaultId, providedId) { var _a8; const pending = (_a8 = pendingDefaults.get(defaultId)) != null ? _a8 : 0; if (pending > 0) { pendingDefaults.set(defaultId, pending - 1); coverageHit(defaultId); } else { coverageHit(providedId); } } // The same count per default, in a slot of the file's typed array instead of // a Map keyed by the default's id, and the outcome recorded through the V2 // point check, which ends at one comparison once it fired in this context. // lru-cache's set and get destructure options with defaults: the Map and the // two calls behind each were a third of a hot loop. function defaultSelectedV2(file, slot, value, inferredName) { file.pendingDefaults[slot] += 1; return inferredName ? applyInferredName(value, inferredName) : value; } function defaultEnteredV2(file, slot, defaultPoint, providedPoint) { const pending = file.pendingDefaults; if (pending[slot] > 0) { pending[slot] -= 1; coverageHitV2(file, defaultPoint); } else { coverageHitV2(file, providedPoint); } } function tryBegin(successId, catchId) { return { successId, catchId, caught: false }; } function tryCatch(frame, value) { // Record the outcome the moment it is known, not when the construct is left. // The commit used to sit in the generated `finally`, and `process.exit()` in // a catch body skips `finally` -- so a catch that ran and whose statements // were credited was still reported as never entered. Statement probes fire // in place and survived, which is what made the report contradict itself. if (!frame.caught) { frame.caught = true; coverageHit(frame.catchId); } return value; } function tryEnd(frame) { // Completing without catching is only knowable here. if (!frame.caught) coverageHit(frame.successId); } function loopBegin(zeroId, enteredId) { return { zeroId, enteredId, entered: false }; } function loopEntered(frame) { // Same reason as tryCatch: a loop body that exits the process would // otherwise report zero iterations. Guarded so a loop still counts once, // however many times it iterates. if (!frame.entered) { frame.entered = true; coverageHit(frame.enteredId); } } function loopEnd(frame) { if (!frame.entered) coverageHit(frame.zeroId); } function mcdcBegin(id, width) { if (!state.decisions.has(id)) { state.decisions.set(id, { id, vectors: /* @__PURE__ */ new Map() }); } return { id, values: Array.from({ length: width }, () => null) }; } function mcdcCondition(frame, index, value) { frame.values[index] = Boolean(value); return value; } function mcdcEnd(frame, value) { const decision = builtinMapGet.call(state.decisions, frame.id); if (!decision) return value; const vector = { values: frame.values, outcome: Boolean(value) }; const key = vectorKey(vector); builtinMapSet.call(decision.vectors, key, vector); const timestampMs = Date.now(); const phaseId = currentPhaseId(); if (isBrowser) { if (recordBrowserEvent("decision", decision.id, vector, timestampMs, phaseId, "browser")) persistBrowser(); } else if (state.runtimeSnapshots) { recordBrowserEvent("decision", decision.id, vector, timestampMs, phaseId, "server"); } else { appendServer(phaseId ? { type: "decision", id: decision.id, vector, timestampMs, phaseId } : { type: "decision", id: decision.id, vector, timestampMs }); } return value; } const directRuntimeApi = { activateCoverageScope, beginBufferedServerEvidence, bindCoverageContext, coverageCarrier, coverageContextEnvironment, coverageContextHeaders, cleanInstrumentationStack, withStackRoom, coverageHit, coverageHitV2, coverageSnapshot, coverageSnapshotColumns, decodeProbeV2Vector, defaultEntered, defaultEnteredV2, defaultSelected, defaultSelectedV2, enableRuntimeSnapshotEvidence, flushBufferedBackgroundEvidence, flushBufferedServerEvidence, loopBegin, loopEnd, loopEntered, mcdcBegin, mcdcCondition, mcdcEnd, mcdcEndV2, optionalCallBegin, optionalCallContinued, optionalCallEnd, optionalCallReached, optionalCallEndV2, optionalSelect, optionalSelectV2, renderedValueV2, parenthesizedAssignmentValue, phaseBelongsToAttempt, registerProbeV2, resetCoverage, selectionBegin, selectionEnd, selectionRight, selectShortV2, selectRightV2, selectNamedRightV2, selectAssignEndV2, selectPathV2, selectEnd2V2, selectEndV2, selectNextV2, takeNodeAssertionPhases, takeWasmRegions, appendWasmRecord, registerWasmRealm, tryBegin, tryCatch, tryEnd, withCoverageCarrier, withNodeAssertionPhase, bindNodeAssertionPhase, openNodeAssertionPhase, withRequestPhase, writeExclusiveBackgroundRecord }; if (globalThis.__SUPERCOV_DIRECT_RUNTIME__ == null) globalThis.__SUPERCOV_DIRECT_RUNTIME__ = directRuntimeApi; if (typeof process !== "undefined" && process.__SUPERCOV_DIRECT_RUNTIME__ == null) process.__SUPERCOV_DIRECT_RUNTIME__ = directRuntimeApi; export { activateCoverageScope, beginBufferedServerEvidence, bindCoverageContext, coverageCarrier, coverageContextEnvironment, coverageContextHeaders, cleanInstrumentationStack, withStackRoom, coverageHit, coverageHitV2, coverageSnapshot, coverageSnapshotColumns, decodeProbeV2Vector, defaultEntered, defaultEnteredV2, defaultSelected, defaultSelectedV2, enableRuntimeSnapshotEvidence, flushBufferedBackgroundEvidence, flushBufferedServerEvidence, flushOnTermination, loopBegin, loopEnd, loopEntered, mcdcBegin, mcdcCondition, mcdcEnd, mcdcEndV2, optionalCallBegin, optionalCallContinued, optionalCallEnd, optionalCallReached, optionalCallEndV2, optionalSelect, optionalSelectV2, renderedValueV2, parenthesizedAssignmentValue, phaseBelongsToAttempt, registerProbeV2, resetCoverage, selectionBegin, selectionEnd, selectionRight, selectShortV2, selectRightV2, selectNamedRightV2, selectAssignEndV2, selectPathV2, selectEnd2V2, selectEndV2, selectNextV2, takeNodeAssertionPhases, takeWasmRegions, appendWasmRecord, registerWasmRealm, tryBegin, tryCatch, tryEnd, withCoverageCarrier, withNodeAssertionPhase, bindNodeAssertionPhase, openNodeAssertionPhase, withRequestPhase, writeExclusiveBackgroundRecord };