diff --git a/common/changes/@rushstack/heft-jest-plugin/user-yverupaka-jest-v8-coverage_2026-11-13-20-35-14.json b/common/changes/@rushstack/heft-jest-plugin/user-yverupaka-jest-v8-coverage_2026-11-13-20-35-14.json new file mode 100644 index 00000000000..477183b407e --- /dev/null +++ b/common/changes/@rushstack/heft-jest-plugin/user-yverupaka-jest-v8-coverage_2026-11-13-20-35-14.json @@ -0,0 +1,11 @@ +{ + "changes": [ + { + "comment": "Add standalone raw V8 coverage validation and per-script compaction.", + "type": "minor", + "packageName": "@rushstack/heft-jest-plugin" + } + ], + "packageName": "@rushstack/heft-jest-plugin", + "email": "59129034+yashwanth195@users.noreply.github.com" +} \ No newline at end of file diff --git a/common/config/rush/browser-approved-packages.json b/common/config/rush/browser-approved-packages.json index 9420e1c3669..b5aae93b73a 100644 --- a/common/config/rush/browser-approved-packages.json +++ b/common/config/rush/browser-approved-packages.json @@ -2,6 +2,10 @@ { "$schema": "https://developer.microsoft.com/json-schemas/rush/v5/approved-packages.schema.json", "packages": [ + { + "name": "@bcoe/v8-coverage", + "allowedCategories": [ "libraries" ] + }, { "name": "@fluentui/react", "allowedCategories": [ "libraries", "vscode-extensions" ] diff --git a/common/config/subspaces/build-tests-subspace/pnpm-lock.yaml b/common/config/subspaces/build-tests-subspace/pnpm-lock.yaml index 08f760e7c08..36264579258 100644 --- a/common/config/subspaces/build-tests-subspace/pnpm-lock.yaml +++ b/common/config/subspaces/build-tests-subspace/pnpm-lock.yaml @@ -329,7 +329,7 @@ packages: engines: {node: '>=6.9.0'} '@bcoe/v8-coverage@0.2.3': - resolution: {integrity: sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==} + resolution: {integrity: sha1-daLotRy3WKdVPWgEpZMteqznXDk=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz} '@emnapi/core@1.9.2': resolution: {integrity: sha1-OHAmXs/8c1LQHq1i2Ng9g1ii0DQ=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@emnapi/core/-/core-1.9.2.tgz} @@ -852,11 +852,11 @@ packages: engines: {node: '>=18.12'} '@pnpm/types@6.4.0': - resolution: {integrity: sha1-MSw78LQ7ADUIyyG9OBVAbqDztmk=, tarball: https://ms-feed-12.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@pnpm/types/-/types-6.4.0.tgz} + resolution: {integrity: sha1-MSw78LQ7ADUIyyG9OBVAbqDztmk=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@pnpm/types/-/types-6.4.0.tgz} engines: {node: '>=10.16'} '@pnpm/types@8.9.0': - resolution: {integrity: sha1-ljbV8GQnk0MvcmCbeUWMqb4EmwI=, tarball: https://ms-feed-12.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@pnpm/types/-/types-8.9.0.tgz} + resolution: {integrity: sha1-ljbV8GQnk0MvcmCbeUWMqb4EmwI=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@pnpm/types/-/types-8.9.0.tgz} engines: {node: '>=14.6'} '@pnpm/types@9.4.2': @@ -919,7 +919,7 @@ packages: resolution: {directory: ../../../heft-plugins/heft-api-extractor-plugin, type: directory} engines: {node: '>=20.9.0'} peerDependencies: - '@rushstack/heft': 1.3.4 + '@rushstack/heft': 1.3.5 '@rushstack/heft-config-file@file:../../../libraries/heft-config-file': resolution: {directory: ../../../libraries/heft-config-file, type: directory} @@ -929,7 +929,7 @@ packages: resolution: {directory: ../../../heft-plugins/heft-jest-plugin, type: directory} engines: {node: '>=20.9.0'} peerDependencies: - '@rushstack/heft': ^1.3.4 + '@rushstack/heft': ^1.3.5 '@types/jest': ^30.0.0 jest-environment-jsdom: ^30.3.0 jest-environment-node: ^30.3.0 @@ -945,18 +945,18 @@ packages: resolution: {directory: ../../../heft-plugins/heft-lint-plugin, type: directory} engines: {node: '>=20.9.0'} peerDependencies: - '@rushstack/heft': 1.3.4 + '@rushstack/heft': 1.3.5 '@rushstack/heft-node-rig@file:../../../rigs/heft-node-rig': resolution: {directory: ../../../rigs/heft-node-rig, type: directory} peerDependencies: - '@rushstack/heft': ^1.3.4 + '@rushstack/heft': ^1.3.5 '@rushstack/heft-typescript-plugin@file:../../../heft-plugins/heft-typescript-plugin': resolution: {directory: ../../../heft-plugins/heft-typescript-plugin, type: directory} engines: {node: '>=20.9.0'} peerDependencies: - '@rushstack/heft': 1.3.4 + '@rushstack/heft': 1.3.5 '@rushstack/heft@file:../../../apps/heft': resolution: {directory: ../../../apps/heft, type: directory} @@ -4827,6 +4827,7 @@ snapshots: '@rushstack/heft-jest-plugin@file:../../../heft-plugins/heft-jest-plugin(@rushstack/heft@file:../../../apps/heft(@types/node@20.17.19))(@types/jest@30.0.0)(@types/node@20.17.19)(jest-environment-node@30.3.0)': dependencies: + '@bcoe/v8-coverage': 0.2.3 '@jest/core': 30.3.0 '@jest/reporters': 30.3.0 '@jest/transform': 30.3.0 diff --git a/common/config/subspaces/build-tests-subspace/repo-state.json b/common/config/subspaces/build-tests-subspace/repo-state.json index 1449961bcde..3d0782ef3a1 100644 --- a/common/config/subspaces/build-tests-subspace/repo-state.json +++ b/common/config/subspaces/build-tests-subspace/repo-state.json @@ -1,6 +1,6 @@ // DO NOT MODIFY THIS FILE MANUALLY BUT DO COMMIT IT. It is generated and used by Rush. { - "pnpmShrinkwrapHash": "18a657d83020df41f6602b7c9087b7253cfee8e0", + "pnpmShrinkwrapHash": "98213830272f4d538689298fb79024c1e4829c2c", "preferredVersionsHash": "550b4cee0bef4e97db6c6aad726df5149d20e7d9", - "packageJsonInjectedDependenciesHash": "293debc6ed16567f5567a7748229a73be6647cc6" + "packageJsonInjectedDependenciesHash": "cb3540bac82315d9512a19a124c70a8a34419d01" } diff --git a/common/config/subspaces/default/pnpm-lock.yaml b/common/config/subspaces/default/pnpm-lock.yaml index 13b7ce39782..270d462e99d 100644 --- a/common/config/subspaces/default/pnpm-lock.yaml +++ b/common/config/subspaces/default/pnpm-lock.yaml @@ -3298,6 +3298,9 @@ importers: ../../../heft-plugins/heft-jest-plugin: dependencies: + '@bcoe/v8-coverage': + specifier: 0.2.3 + version: 0.2.3 '@jest/core': specifier: ~30.3.0 version: 30.3.0(babel-plugin-macros@3.1.0)(esbuild-register@3.6.0(esbuild@0.28.0)) @@ -4838,7 +4841,7 @@ importers: version: 1.3.4(@types/node@20.17.19) '@rushstack/heft-node-rig': specifier: 2.11.55 - version: 2.11.55(@rushstack/heft@1.3.4(@types/node@20.17.19))(@types/node@20.17.19)(babel-plugin-macros@3.1.0)(esbuild-register@3.6.0(esbuild@0.28.0))(jest-environment-jsdom@30.3.0) + version: 2.11.55(@rushstack/heft@1.3.4(@types/node@20.17.19))(@types/node@20.17.19)(esbuild-register@3.6.0(esbuild@0.28.0))(jest-environment-jsdom@30.3.0) '@types/jest': specifier: 30.0.0 version: 30.0.0 @@ -7065,7 +7068,7 @@ packages: resolution: {integrity: sha512-4iri8i1AqYHJE2DstZYkyEprg6Pq6sKx3xn5FpySk9sNhH7qN2LLlHJCfDTZRILNwQNPD7mATWM0TBui7uC1pA==} '@bcoe/v8-coverage@0.2.3': - resolution: {integrity: sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==} + resolution: {integrity: sha1-daLotRy3WKdVPWgEpZMteqznXDk=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz} '@bufbuild/protobuf@2.11.0': resolution: {integrity: sha512-sBXGT13cpmPR5BMgHE6UEEfEaShh5Ror6rfN3yEK5si7QVrtZg8LEPQb0VVhiLRUslD2yLnXtnRzG035J/mZXQ==} @@ -9019,7 +9022,7 @@ packages: engines: {node: '>=10.16'} '@pnpm/patching.types@1000.1.0': - resolution: {integrity: sha512-Zib2ysLctRnWM4KXXlljR44qSKwyEqYmLk+8VPBDBEK3l5Gp5mT3N4ix9E4qjYynvFqahumsxzOfxOYQhUGMGw==} + resolution: {integrity: sha1-1AOzl0N4A7hZx/sullgMiXtitx4=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@pnpm/patching.types/-/patching.types-1000.1.0.tgz} engines: {node: '>=18.12'} '@pnpm/patching.types@900.0.0': @@ -9082,7 +9085,7 @@ packages: engines: {node: '>=14.6'} '@pnpm/types@9.4.2': - resolution: {integrity: sha512-g1hcF8Nv4gd76POilz9gD4LITAPXOe5nX4ijgr8ixCbLQZfcpYiMfJ+C1RlMNRUDo8vhlNB4O3bUlxmT6EAQXA==} + resolution: {integrity: sha1-CjTDxB1UUkYdjYlYN0pyf5xGz7I=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@pnpm/types/-/types-9.4.2.tgz} engines: {node: '>=16.14'} '@pnpm/types@900.0.0': @@ -10263,7 +10266,7 @@ packages: os: [darwin] '@swc/core-darwin-x64@1.7.10': - resolution: {integrity: sha1-cdNUFYDjbr73bTfwCBxJp/Gv6tY=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@swc/core-darwin-x64/-/core-darwin-x64-1.7.10.tgz} + resolution: {integrity: sha512-P3LJjAWh5yLc6p5IUwV5LgRfA3R1oDCZDMabYyb2BVQuJTD4MfegW9DhBcUUF5dhBLwq3191KpLVzE+dLTbiXw==, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@swc/core-darwin-x64/-/core-darwin-x64-1.7.10.tgz} engines: {node: '>=10'} cpu: [x64] os: [darwin] @@ -10303,13 +10306,13 @@ packages: libc: [musl] '@swc/core-win32-arm64-msvc@1.7.10': - resolution: {integrity: sha1-XW7P2kzF6D7IZZEZ8WB7FmP3Cm0=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@swc/core-win32-arm64-msvc/-/core-win32-arm64-msvc-1.7.10.tgz} + resolution: {integrity: sha512-plRIsOcfy9t9Q/ivm5DA7I0HaIvfAWPbI+bvVRrr3C/1K2CSqnqZJjEWOAmx2LiyipijNnEaFYuLBp0IkGuJpg==, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@swc/core-win32-arm64-msvc/-/core-win32-arm64-msvc-1.7.10.tgz} engines: {node: '>=10'} cpu: [arm64] os: [win32] '@swc/core-win32-ia32-msvc@1.7.10': - resolution: {integrity: sha1-N/MXfaU7KLLcjIOu/vwgIFBk688=, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@swc/core-win32-ia32-msvc/-/core-win32-ia32-msvc-1.7.10.tgz} + resolution: {integrity: sha512-GntrVNT23viHtbfzmlK8lfBiKeajH24GzbDT7qXhnoO20suUPcyYZxyvCb4gWM2zu8ZBTPHNlqfrNsriQCZ+lQ==, tarball: https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry/@swc/core-win32-ia32-msvc/-/core-win32-ia32-msvc-1.7.10.tgz} engines: {node: '>=10'} cpu: [ia32] os: [win32] @@ -24963,7 +24966,7 @@ snapshots: transitivePeerDependencies: - '@types/node' - '@rushstack/heft-jest-plugin@2.0.21(@rushstack/heft@1.3.4(@types/node@20.17.19))(@types/jest@30.0.0)(@types/node@20.17.19)(babel-plugin-macros@3.1.0)(esbuild-register@3.6.0(esbuild@0.28.0))(jest-environment-jsdom@30.3.0)(jest-environment-node@30.3.0)': + '@rushstack/heft-jest-plugin@2.0.21(@rushstack/heft@1.3.4(@types/node@20.17.19))(@types/jest@30.0.0)(@types/node@20.17.19)(esbuild-register@3.6.0(esbuild@0.28.0))(jest-environment-jsdom@30.3.0)(jest-environment-node@30.3.0)': dependencies: '@jest/core': 30.3.0(babel-plugin-macros@3.1.0)(esbuild-register@3.6.0(esbuild@0.28.0)) '@jest/reporters': 30.3.0 @@ -24996,13 +24999,13 @@ snapshots: transitivePeerDependencies: - '@types/node' - '@rushstack/heft-node-rig@2.11.55(@rushstack/heft@1.3.4(@types/node@20.17.19))(@types/node@20.17.19)(babel-plugin-macros@3.1.0)(esbuild-register@3.6.0(esbuild@0.28.0))(jest-environment-jsdom@30.3.0)': + '@rushstack/heft-node-rig@2.11.55(@rushstack/heft@1.3.4(@types/node@20.17.19))(@types/node@20.17.19)(esbuild-register@3.6.0(esbuild@0.28.0))(jest-environment-jsdom@30.3.0)': dependencies: '@microsoft/api-extractor': 7.60.0(@types/node@20.17.19) '@rushstack/eslint-config': 4.9.0(eslint@9.37.0)(typescript@5.8.2) '@rushstack/heft': 1.3.4(@types/node@20.17.19) '@rushstack/heft-api-extractor-plugin': 1.3.31(@rushstack/heft@1.3.4(@types/node@20.17.19))(@types/node@20.17.19) - '@rushstack/heft-jest-plugin': 2.0.21(@rushstack/heft@1.3.4(@types/node@20.17.19))(@types/jest@30.0.0)(@types/node@20.17.19)(babel-plugin-macros@3.1.0)(esbuild-register@3.6.0(esbuild@0.28.0))(jest-environment-jsdom@30.3.0)(jest-environment-node@30.3.0) + '@rushstack/heft-jest-plugin': 2.0.21(@rushstack/heft@1.3.4(@types/node@20.17.19))(@types/jest@30.0.0)(@types/node@20.17.19)(esbuild-register@3.6.0(esbuild@0.28.0))(jest-environment-jsdom@30.3.0)(jest-environment-node@30.3.0) '@rushstack/heft-lint-plugin': 1.4.1(@rushstack/heft@1.3.4(@types/node@20.17.19))(@types/node@20.17.19) '@rushstack/heft-typescript-plugin': 1.3.26(@rushstack/heft@1.3.4(@types/node@20.17.19))(@types/node@20.17.19) '@types/jest': 30.0.0 @@ -31145,7 +31148,7 @@ snapshots: eslint@8.57.1: dependencies: - '@eslint-community/eslint-utils': 4.9.1(eslint@8.57.1) + '@eslint-community/eslint-utils': 4.9.1(eslint@9.37.0) '@eslint-community/regexpp': 4.12.2 '@eslint/eslintrc': 2.1.4 '@eslint/js': 8.57.1 diff --git a/common/config/subspaces/default/repo-state.json b/common/config/subspaces/default/repo-state.json index 3d09725be2d..8f7166142d6 100644 --- a/common/config/subspaces/default/repo-state.json +++ b/common/config/subspaces/default/repo-state.json @@ -1,5 +1,5 @@ // DO NOT MODIFY THIS FILE MANUALLY BUT DO COMMIT IT. It is generated and used by Rush. { - "pnpmShrinkwrapHash": "a21e9138c38033203ce379c3ec1a9aa12562d3c6", + "pnpmShrinkwrapHash": "c292b31aea80e910ef742495873b27b273fc04aa", "preferredVersionsHash": "029c99bd6e65c5e1f25e2848340509811ff9753c" } diff --git a/heft-plugins/heft-jest-plugin/README.md b/heft-plugins/heft-jest-plugin/README.md index 25f82e5ef62..61abaeb76e2 100644 --- a/heft-plugins/heft-jest-plugin/README.md +++ b/heft-plugins/heft-jest-plugin/README.md @@ -2,6 +2,12 @@ This is a Heft plugin for running Jest. +`@rushstack/heft-jest-plugin/lib/JestV8Coverage` provides raw V8 range validation and per-script compaction +for typed observations. Callers remain responsible for JSON validation, source identity and source-map +integrity. This utility does not enable sharding, collect coverage or convert coverage reports. +Coincident function spans require complete captures in V8 nesting order; sparse incremental captures are unsupported. +Distinct named roles sharing a non-root span, such as class initializers, are compacted separately. + ## Links - [CHANGELOG.md]( diff --git a/heft-plugins/heft-jest-plugin/package.json b/heft-plugins/heft-jest-plugin/package.json index 53c493bc2ac..a045ff6efc0 100644 --- a/heft-plugins/heft-jest-plugin/package.json +++ b/heft-plugins/heft-jest-plugin/package.json @@ -37,6 +37,7 @@ } }, "dependencies": { + "@bcoe/v8-coverage": "0.2.3", "@jest/core": "~30.3.0", "@jest/reporters": "~30.3.0", "@jest/transform": "~30.3.0", diff --git a/heft-plugins/heft-jest-plugin/src/JestV8Coverage.ts b/heft-plugins/heft-jest-plugin/src/JestV8Coverage.ts new file mode 100644 index 00000000000..f6234578da8 --- /dev/null +++ b/heft-plugins/heft-jest-plugin/src/JestV8Coverage.ts @@ -0,0 +1,199 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. +// See LICENSE in the project root for license information. + +import { isDeepStrictEqual } from 'node:util'; + +import { + mergeScriptCovs, + compareFunctionCovs, + type ScriptCov, + type FunctionCov, + type RangeCov +} from '@bcoe/v8-coverage'; + +export interface IJestCoverageSourceMap { + version: 3; + /** Build-root-relative original identities, materialized as absolute paths only for conversion. */ + sources: string[]; + sourcesContent: string[]; + names: string[]; + mappings: string; + /** The self-source's shebang was restored for hashing; conversion must use Jest's actual input text. */ + inputShebangRemoved?: true; +} + +export interface IJestV8Coverage { + /** Preserve V8's nesting order, including the script before a function with the same root span. */ + result: ScriptCov; + /** Generated text for mapped scripts; otherwise the full input before Jest removes its shebang. */ + source: string; + // eslint-disable-next-line @rushstack/no-new-null -- Explicit absence of captured source-map data. + sourceMap: IJestCoverageSourceMap | null; + baseline: boolean; +} + +/** Jest's ScriptTransformer removes the initial shebang, but preserves its newline. */ +export function normalizeJestCoverageInput(source: string): string { + return source.replace(/^#!.*/, ''); +} + +/** Validate function-scoped ranges on an already typed observation, not an unknown JSON payload. */ +export function validateV8Ranges(entry: IJestV8Coverage): void { + const sourceLength: number = (entry.sourceMap ? entry.source : normalizeJestCoverageInput(entry.source)) + .length; + for (const fn of entry.result.functions) { + const root: RangeCov | undefined = fn.ranges[0]; + if (!root) { + throw new Error('Missing raw V8 function-scoped coverage ranges.'); + } + let previousStart: number = -1; + const parents: RangeCov[] = []; + for (const range of fn.ranges) { + if ( + !Number.isSafeInteger(range.count) || + range.count < 0 || + !Number.isSafeInteger(range.startOffset) || + range.startOffset < 0 || + !Number.isSafeInteger(range.endOffset) || + range.startOffset < root.startOffset || + range.endOffset > root.endOffset || + range.endOffset < range.startOffset || + (fn.ranges.length > 1 && range.endOffset === range.startOffset) || + range.startOffset < previousStart || + (!entry.baseline && range.endOffset > sourceLength) + ) { + throw new Error('Invalid raw V8 function-scoped coverage range.'); + } + while (parents.length && range.startOffset >= parents[parents.length - 1].endOffset) { + parents.pop(); + } + const parent: RangeCov | undefined = parents[parents.length - 1]; + if ( + parent && + (range.endOffset > parent.endOffset || + (range.startOffset === parent.startOffset && range.endOffset === parent.endOffset)) + ) { + throw new Error('Crossing or duplicate raw V8 coverage ranges.'); + } + parents.push(range); + previousStart = range.startOffset; + } + } + const empty: FunctionCov | undefined = entry.result.functions[0]; + if ( + !empty || + (entry.baseline + ? entry.result.functions.length !== 1 || + empty.functionName !== '(empty-report)' || + !empty.isBlockCoverage || + empty.ranges.length !== 1 || + empty.ranges[0].count !== 0 || + empty.ranges[0].startOffset !== 0 || + empty.ranges[0].endOffset !== Buffer.byteLength(entry.source) + : entry.result.functions.some((fn) => fn.functionName === '(empty-report)')) + ) { + throw new Error('Invalid raw V8 untested-file baseline.'); + } +} + +function groupV8Functions(entry: IJestV8Coverage): Map { + const groups: Map = new Map(); + for (const fn of entry.result.functions) { + const root: RangeCov = fn.ranges[0]; + const key: string = `${root.startOffset};${root.endOffset}`; + const group: FunctionCov[] | undefined = groups.get(key); + if (group) { + group.push(fn); + } else { + groups.set(key, [fn]); + } + } + const sourceLength: number = (entry.sourceMap ? entry.source : normalizeJestCoverageInput(entry.source)) + .length; + for (const group of groups.values()) { + if (group.length === 1) continue; + const root: RangeCov = group[0].ranges[0]; + if (root.startOffset === 0 && root.endOffset === sourceLength) { + // V8 reports the top-level script before its coincident function, even for equal empty names. + if (group.length === 2 && group[0] === entry.result.functions[0] && group[0].functionName === '') { + continue; + } + } else { + // Native roles such as static and instance initializers can share a non-root extent. + const names: Set = new Set(group.map((fn) => fn.functionName)); + if (!names.has('') && names.size === group.length) { + continue; + } + } + throw new Error(`Ambiguous raw V8 function identity: "${entry.result.url}".`); + } + return groups; +} + +/** + * Retain one source/map and function-scoped range tree per script, not one copy per suite. + * Callers must populate the map only through this function and must not mutate its retained entries. + * Coincident spans require complete captures in V8 nesting order, not sparse incremental captures. + * A sparse anonymous range does not identify whether it belongs to the script or its function. + * JSON shape, source identities, source-map integrity and source hashes must be validated separately. + */ +export function addV8Coverage(scripts: Map, entry: IJestV8Coverage): void { + // Validate before normalization/supersession: merging must never erase malformed observations. + validateV8Ranges(entry); + const incomingGroups: Map = groupV8Functions(entry); + const previous: IJestV8Coverage | undefined = scripts.get(entry.result.url); + if (previous && previous.baseline !== entry.baseline) { + // Untested code has not been transformed; its baseline must not constrain executed code. + if (entry.baseline) { + return; + } + } else if (previous) { + if (previous.source !== entry.source || !isDeepStrictEqual(previous.sourceMap, entry.sourceMap)) { + throw new Error(`Incompatible V8 code or source maps: "${entry.result.url}".`); + } + if (entry.baseline) { + return; + } + const result: ScriptCov = structuredClone(previous.result); + const groups: Map = groupV8Functions({ ...previous, result }); + for (const [key, incoming] of incomingGroups) { + const existing: FunctionCov[] | undefined = groups.get(key); + let matched: FunctionCov[] = incoming; + if (existing && incoming.length > 1 && incoming[0].functionName !== '') { + const byName: Map = new Map(incoming.map((fn) => [fn.functionName, fn])); + matched = existing.map((fn) => { + const match: FunctionCov | undefined = byName.get(fn.functionName); + if (!match) { + throw new Error(`Ambiguous raw V8 function identity: "${entry.result.url}".`); + } + return match; + }); + } + if ( + existing && + (existing.length !== incoming.length || + existing.some((fn, index) => fn.functionName !== matched[index].functionName)) + ) { + throw new Error(`Ambiguous raw V8 function identity: "${entry.result.url}".`); + } + groups.set( + key, + matched.map((fn, index) => { + // mergeScriptCovs keys only by root offsets; give it one matched function per observation. + const observations: ScriptCov[] = [{ ...entry.result, functions: [structuredClone(fn)] }]; + if (existing) { + observations.unshift({ ...previous.result, functions: [existing[index]] }); + } + return mergeScriptCovs(observations)!.functions[0]; + }) + ); + } + result.functions = [...groups.values()].flat(); + result.functions.sort(compareFunctionCovs); + const merged: IJestV8Coverage = { ...previous, result }; + validateV8Ranges(merged); + scripts.set(entry.result.url, merged); + return; + } + scripts.set(entry.result.url, structuredClone(entry)); +} diff --git a/heft-plugins/heft-jest-plugin/src/test/JestV8Coverage.test.ts b/heft-plugins/heft-jest-plugin/src/test/JestV8Coverage.test.ts new file mode 100644 index 00000000000..8ac0914dc4c --- /dev/null +++ b/heft-plugins/heft-jest-plugin/src/test/JestV8Coverage.test.ts @@ -0,0 +1,617 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. +// See LICENSE in the project root for license information. + +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; + +import type { ScriptCov, FunctionCov, RangeCov } from '@bcoe/v8-coverage'; + +import { + addV8Coverage, + validateV8Ranges, + type IJestV8Coverage, + type IJestCoverageSourceMap +} from '../JestV8Coverage'; + +const execFileAsync = promisify(execFile); + +function createEntry(): IJestV8Coverage { + return { + result: { + scriptId: '1', + url: 'source.js', + functions: [ + { + functionName: 'outer', + isBlockCoverage: true, + ranges: [ + { startOffset: 0, endOffset: 100, count: 1 }, + { startOffset: 70, endOffset: 90, count: 0 } + ] + }, + { + functionName: 'inner', + isBlockCoverage: true, + ranges: [ + { startOffset: 10, endOffset: 60, count: 1 }, + { startOffset: 30, endOffset: 40, count: 0 } + ] + } + ] + }, + source: '.'.repeat(100), + sourceMap: null, + baseline: false + }; +} + +function createBaseline(source: string = '\u00e9'): IJestV8Coverage { + return { + result: { + scriptId: '0', + url: 'source.js', + functions: [ + { + functionName: '(empty-report)', + isBlockCoverage: true, + ranges: [{ startOffset: 0, endOffset: Buffer.byteLength(source), count: 0 }] + } + ] + }, + source, + sourceMap: null, + baseline: true + }; +} + +function createSourceMap(): IJestCoverageSourceMap { + return { version: 3, sources: ['source.ts'], sourcesContent: ['original'], names: [], mappings: 'AAAA' }; +} + +// Node 22.23.4, one final precise capture without Debugger: instantiate, run(false/true/false), +// instantiate in a second context, collect garbage, then run(true) on the first instance. +function createClassInitializerEntry(): IJestV8Coverage { + return { + result: { + scriptId: '366', + url: 'static-and-instance.js', + functions: [ + { + functionName: '', + ranges: [{ startOffset: 0, endOffset: 87, count: 2 }], + isBlockCoverage: true + }, + { + functionName: '', + ranges: [{ startOffset: 7, endOffset: 79, count: 2 }], + isBlockCoverage: true + }, + { + functionName: '', + ranges: [{ startOffset: 7, endOffset: 79, count: 2 }], + isBlockCoverage: true + }, + { + functionName: 'value', + ranges: [{ startOffset: 29, endOffset: 40, count: 2 }], + isBlockCoverage: true + }, + { + functionName: 'run', + ranges: [ + { startOffset: 41, endOffset: 78, count: 4 }, + { startOffset: 62, endOffset: 77, count: 2 } + ], + isBlockCoverage: true + } + ] + }, + source: 'class C{static value=1;value=()=>C.value;run(flag){return flag?this.value():2}};new C()', + sourceMap: null, + baseline: false + }; +} + +function getFunctionCounts(fn: FunctionCov): number[] { + const root: RangeCov = fn.ranges[0]; + return Array.from({ length: root.endOffset - root.startOffset }, (unused, index) => + fn.ranges.reduce( + (count, range) => + root.startOffset + index >= range.startOffset && root.startOffset + index < range.endOffset + ? range.count + : count, + 0 + ) + ); +} + +async function captureAsync( + calls: boolean[], + source: string = 'function outer(x){ function inner(y){if(y)return 1; return 2;} if(x)return inner(x); return 3; }\n', + functionName: string = 'outer', + resetBeforeCalls: boolean = false +): Promise { + const { stdout } = await execFileAsync( + process.execPath, + [ + '-e', + ` + const { Session } = require('node:inspector'); + const { promisify } = require('node:util'); + (async () => { + const session = new Session(); + session.connect(); + try { + const post = promisify(session.post.bind(session)); + await post('Profiler.enable'); + await post('Profiler.startPreciseCoverage', { callCount: true, detailed: true }); + const result = new (require('node:vm').Script)(process.argv[1], { filename: 'nested-coverage.js' }).runInThisContext(); + const callable = typeof result === 'function' ? result : globalThis[process.argv[3]]; + if (JSON.parse(process.argv[4])) await post('Profiler.takePreciseCoverage'); + for (const value of JSON.parse(process.argv[2])) callable(value); + const coverage = await post('Profiler.takePreciseCoverage'); + const captured = coverage.result.find(entry => entry.url === 'nested-coverage.js'); + if (!captured) throw new Error('Missing fixture coverage'); + process.stdout.write(JSON.stringify(captured)); + } finally { + session.disconnect(); + } + })().catch(error => { console.error(error); process.exitCode = 1; }); + `, + source, + JSON.stringify(calls), + functionName, + JSON.stringify(resetBeforeCalls) + ], + { timeout: 20000 } + ); + const result: ScriptCov = JSON.parse(stdout); + return { result, source, sourceMap: null, baseline: false }; +} + +describe('JestV8Coverage', () => { + it('retains the distinct coincident class initializers in a complete Node 22 capture', () => { + const entry: IJestV8Coverage = createClassInitializerEntry(); + const original: IJestV8Coverage = structuredClone(entry); + const scripts: Map = new Map(); + for (let i: number = 0; i < 3; i++) { + addV8Coverage(scripts, entry); + } + expect(scripts.size).toBe(1); + expect(scripts.get(entry.result.url)!.result.functions).toEqual( + entry.result.functions.map((fn) => ({ + ...fn, + ranges: fn.ranges.map((range) => ({ ...range, count: range.count * 3 })) + })) + ); + expect(entry).toEqual(original); + }); + + it('matches coincident named roles independently of their order and counts', () => { + const entry: IJestV8Coverage = createClassInitializerEntry(); + const next: IJestV8Coverage = structuredClone(entry); + next.result.functions[1].ranges[0].count = 7; + next.result.functions[2].ranges[0].count = 3; + next.result.functions.splice(1, 2, next.result.functions[2], next.result.functions[1]); + const originals: IJestV8Coverage[] = structuredClone([entry, next]); + for (const contributions of [ + [entry, next], + [next, entry] + ]) { + const scripts: Map = new Map(); + for (const contribution of contributions) { + addV8Coverage(scripts, contribution); + } + const functions: FunctionCov[] = scripts.get(entry.result.url)!.result.functions; + expect(functions).toHaveLength(5); + expect(new Map(functions.map((fn) => [fn.functionName, fn.ranges]))).toEqual( + new Map([ + ['', [{ startOffset: 0, endOffset: 87, count: 4 }]], + ['', [{ startOffset: 7, endOffset: 79, count: 9 }]], + ['', [{ startOffset: 7, endOffset: 79, count: 5 }]], + ['value', [{ startOffset: 29, endOffset: 40, count: 4 }]], + [ + 'run', + [ + { startOffset: 41, endOffset: 78, count: 8 }, + { startOffset: 62, endOffset: 77, count: 4 } + ] + ] + ]) + ); + } + expect([entry, next]).toEqual(originals); + }); + + it.each<[string, (entry: IJestV8Coverage) => void]>([ + [ + 'duplicate role', + (entry) => { + entry.result.functions[2].functionName = ''; + } + ], + [ + 'anonymous role', + (entry) => { + entry.result.functions[2].functionName = ''; + } + ], + [ + 'changed role', + (entry) => { + entry.result.functions[2].functionName = 'different'; + } + ], + [ + 'missing role', + (entry) => { + entry.result.functions.splice(2, 1); + } + ] + ])('rejects a %s in coincident named functions without changing state', (unused, mutate) => { + const entry: IJestV8Coverage = createClassInitializerEntry(); + const scripts: Map = new Map(); + addV8Coverage(scripts, entry); + const retained: IJestV8Coverage = scripts.get(entry.result.url)!; + const invalid: IJestV8Coverage = structuredClone(entry); + mutate(invalid); + const original: IJestV8Coverage = structuredClone(invalid); + expect(() => addV8Coverage(scripts, invalid)).toThrow('Ambiguous raw V8 function identity'); + expect(scripts.get(entry.result.url)).toBe(retained); + expect(retained).toEqual(entry); + expect(invalid).toEqual(original); + }); + + it.each([ + ['named', 'function unused() {}', 'unused'], + ['anonymous', '()=>{}', ''] + ])('retains uncalled %s functions sharing the script span', async (unused, source, functionName) => { + const entry: IJestV8Coverage = await captureAsync([], source, functionName); + const original: IJestV8Coverage = structuredClone(entry); + expect(entry.result.functions).toHaveLength(2); + expect(entry.result.functions.map((fn) => fn.ranges[0])).toEqual([ + { startOffset: 0, endOffset: source.length, count: 1 }, + { startOffset: 0, endOffset: source.length, count: 0 } + ]); + const scripts: Map = new Map(); + addV8Coverage(scripts, entry); + addV8Coverage(scripts, entry); + expect(scripts.get(entry.result.url)!.result.functions).toEqual([ + { ...entry.result.functions[0], ranges: [{ startOffset: 0, endOffset: source.length, count: 2 }] }, + entry.result.functions[1] + ]); + expect(entry).toEqual(original); + }); + + it.each([ + ['named', 'function outer(x){return x?1:2;}'], + ['anonymous', '(x)=>x?1:2'] + ])( + 'preserves %s coincident function counts and branches in either arrival order', + async (unused, source) => { + const [uncalled, first, second, canonical] = await Promise.all([ + captureAsync([], source), + captureAsync([true], source), + captureAsync([false], source), + captureAsync([true, false, true], source) + ]); + expect(canonical.result.functions).toHaveLength(2); + expect(canonical.result.functions.map((fn) => fn.ranges[0])).toEqual([ + { startOffset: 0, endOffset: source.length, count: 1 }, + { startOffset: 0, endOffset: source.length, count: 3 } + ]); + const entries: IJestV8Coverage[] = [uncalled, first, second, first]; + const originals: IJestV8Coverage[] = structuredClone(entries); + for (const contributions of [entries, [...entries].reverse()]) { + const scripts: Map = new Map(); + for (const entry of contributions) { + addV8Coverage(scripts, entry); + } + expect(scripts.size).toBe(1); + const actual: FunctionCov[] = scripts.get(first.result.url)!.result.functions; + const expected: FunctionCov[] = [ + { + ...canonical.result.functions[0], + ranges: [{ startOffset: 0, endOffset: source.length, count: 4 }] + }, + canonical.result.functions[1] + ]; + // Equivalent counts can use different nesting; compare every offset within each distinct function. + expect(actual.map((fn) => ({ ...fn, ranges: [fn.ranges[0]] }))).toEqual( + expected.map((fn) => ({ ...fn, ranges: [fn.ranges[0]] })) + ); + expect(actual.map(getFunctionCounts)).toEqual(expected.map(getFunctionCounts)); + } + expect(entries).toEqual(originals); + } + ); + + it.each([true, false])( + 'rejects ambiguous sparse anonymous captures (complete first: %s)', + async (first) => { + const complete: IJestV8Coverage = await captureAsync([], '()=>{}'); + const sparse: IJestV8Coverage = await captureAsync([true], '()=>{}', '', true); + expect(complete.result.functions).toHaveLength(2); + expect(sparse.result.functions).toHaveLength(1); + const [initial, incoming] = first ? [complete, sparse] : [sparse, complete]; + const scripts: Map = new Map(); + addV8Coverage(scripts, initial); + const original: IJestV8Coverage = structuredClone(initial); + expect(() => addV8Coverage(scripts, incoming)).toThrow('Ambiguous raw V8 function identity'); + expect([...scripts.values()]).toEqual([original]); + } + ); + + it('rejects reordered or indistinguishable extra coincident functions without changing state', async () => { + const entry: IJestV8Coverage = await captureAsync([], 'function unused() {}', 'unused'); + const scripts: Map = new Map(); + addV8Coverage(scripts, entry); + const reordered: IJestV8Coverage = structuredClone(entry); + reordered.result.functions.reverse(); + const extra: IJestV8Coverage = structuredClone(entry); + extra.result.functions.push(structuredClone(extra.result.functions[1])); + for (const invalid of [reordered, extra]) { + expect(() => addV8Coverage(scripts, invalid)).toThrow('Ambiguous raw V8 function identity'); + expect([...scripts.values()]).toEqual([entry]); + } + }); + + it('merges nested functions like a single V8 capture without inventing inner branch hits', async () => { + const [first, second, canonical] = await Promise.all([ + captureAsync([true]), + captureAsync([false]), + captureAsync([true, false]) + ]); + const scripts: Map = new Map(); + addV8Coverage(scripts, first); + addV8Coverage(scripts, second); + const merged: ScriptCov = scripts.get(first.result.url)!.result; + const namedFunctions = (result: ScriptCov): ScriptCov['functions'] => + result.functions.filter((fn) => fn.functionName); + expect(namedFunctions(merged).map((fn) => fn.functionName)).toEqual(['outer', 'inner']); + expect(namedFunctions(merged)).toEqual(namedFunctions(canonical.result)); + expect(merged.functions.find((fn) => fn.functionName === 'inner')!.ranges).toContainEqual( + expect.objectContaining({ count: 0 }) + ); + const reverse: Map = new Map(); + addV8Coverage(reverse, second); + addV8Coverage(reverse, first); + expect(reverse.get(first.result.url)!.result.functions).toEqual(merged.functions); + }); + + it('sums repeated counts while retaining one independent range tree per script', () => { + const entry: IJestV8Coverage = createEntry(); + const original: IJestV8Coverage = structuredClone(entry); + const scripts: Map = new Map(); + for (let i: number = 0; i < 20; i++) { + addV8Coverage(scripts, entry); + } + const retained: IJestV8Coverage = scripts.get(entry.result.url)!; + expect(scripts.size).toBe(1); + expect(retained.result.functions).toEqual( + entry.result.functions.map((fn) => ({ + ...fn, + ranges: fn.ranges.map((range) => ({ ...range, count: range.count * 20 })) + })) + ); + expect(JSON.stringify(retained).length).toBeLessThan(JSON.stringify(entry).length + 10); + expect(entry).toEqual(original); + addV8Coverage(scripts, { ...entry, result: { ...entry.result, url: 'other.js' } }); + expect(scripts.size).toBe(2); + expect(scripts.get('source.js')).toBe(retained); + }); + + it.each([true, false])('lets executed coverage supersede baselines (baseline first: %s)', (first) => { + const scripts: Map = new Map(); + const baseline: IJestV8Coverage = createBaseline(); + const executed: IJestV8Coverage = createEntry(); + executed.sourceMap = createSourceMap(); + for (const entry of first ? [baseline, executed] : [executed, baseline]) { + addV8Coverage(scripts, entry); + } + expect([...scripts.values()]).toEqual([executed]); + }); + + it.each(['', '\u00e9', '#!/usr/bin/env node\r\n\u00e9'])( + 'retains canonical byte-length baselines without accumulating counts: %j', + (source) => { + const scripts: Map = new Map(); + const baseline: IJestV8Coverage = createBaseline(source); + addV8Coverage(scripts, baseline); + addV8Coverage(scripts, structuredClone(baseline)); + expect([...scripts.values()]).toEqual([baseline]); + } + ); + + it.each<[string, (entry: IJestV8Coverage) => void]>([ + [ + 'positive count', + (entry) => { + entry.result.functions[0].ranges[0].count = 1; + } + ], + [ + 'wrong name', + (entry) => { + entry.result.functions[0].functionName = 'executed'; + } + ], + [ + 'function coverage', + (entry) => { + entry.result.functions[0].isBlockCoverage = false; + } + ], + [ + 'character length', + (entry) => { + entry.result.functions[0].ranges[0].endOffset = 1; + } + ], + [ + 'extra function', + (entry) => { + entry.result.functions.push(entry.result.functions[0]); + } + ], + [ + 'executed marker', + (entry) => { + entry.baseline = false; + } + ] + ])('rejects malformed baselines before supersession: %s', (unused, mutate) => { + const scripts: Map = new Map(); + const executed: IJestV8Coverage = createEntry(); + addV8Coverage(scripts, executed); + const invalid: IJestV8Coverage = createBaseline(); + mutate(invalid); + expect(() => addV8Coverage(scripts, invalid)).toThrow('Invalid raw V8'); + expect([...scripts.values()]).toEqual([executed]); + }); + + it.each([ + ['negative count', { count: -1 }], + ['fractional count', { count: 0.5 }], + ['unsafe count', { count: Number.MAX_SAFE_INTEGER + 1 }], + ['nonfinite count', { count: Infinity }], + ['negative start', { startOffset: -1 }], + ['fractional start', { startOffset: 0.5 }], + ['unsafe start', { startOffset: Number.MAX_SAFE_INTEGER + 1 }], + ['nonfinite end', { endOffset: NaN }], + ['fractional end', { endOffset: 99.5 }], + ['unsafe end', { endOffset: Number.MAX_SAFE_INTEGER + 1 }], + ['reversed range', { endOffset: -1 }], + ['past source', { endOffset: 101 }] + ] as const)('rejects invalid numeric ranges before replacing a baseline: %s', (unused, change) => { + const scripts: Map = new Map(); + const baseline: IJestV8Coverage = createBaseline(); + addV8Coverage(scripts, baseline); + const invalid: IJestV8Coverage = createEntry(); + Object.assign(invalid.result.functions[0].ranges[0], change); + expect(() => addV8Coverage(scripts, invalid)).toThrow('Invalid raw V8'); + expect([...scripts.values()]).toEqual([baseline]); + }); + + it.each<{ name: string; ranges: RangeCov[] }>([ + { name: 'missing', ranges: [] }, + { + name: 'empty child', + ranges: [ + { startOffset: 0, endOffset: 100, count: 1 }, + { startOffset: 100, endOffset: 100, count: 0 } + ] + }, + { + name: 'duplicate', + ranges: [ + { startOffset: 0, endOffset: 100, count: 1 }, + { startOffset: 0, endOffset: 100, count: 2 } + ] + }, + { + name: 'out-of-root', + ranges: [ + { startOffset: 0, endOffset: 100, count: 1 }, + { startOffset: 10, endOffset: 101, count: 0 } + ] + }, + { + name: 'unordered', + ranges: [ + { startOffset: 0, endOffset: 100, count: 1 }, + { startOffset: 20, endOffset: 40, count: 0 }, + { startOffset: 10, endOffset: 15, count: 1 } + ] + }, + { + name: 'crossing', + ranges: [ + { startOffset: 0, endOffset: 100, count: 1 }, + { startOffset: 10, endOffset: 40, count: 0 }, + { startOffset: 30, endOffset: 50, count: 1 } + ] + } + ])('rejects $name ranges before merging', ({ ranges }) => { + const scripts: Map = new Map(); + const entry: IJestV8Coverage = createEntry(); + addV8Coverage(scripts, entry); + const invalid: IJestV8Coverage = createEntry(); + invalid.result.functions[0].ranges = ranges; + expect(() => addV8Coverage(scripts, invalid)).toThrow(); + expect([...scripts.values()]).toEqual([entry]); + }); + + it('accepts nested ranges with shared starts and adjacent siblings, but rejects missing functions', () => { + const entry: IJestV8Coverage = createEntry(); + entry.result.functions[0].ranges = [ + { startOffset: 0, endOffset: 100, count: 1 }, + { startOffset: 0, endOffset: 50, count: 0 }, + { startOffset: 10, endOffset: 20, count: 1 }, + { startOffset: 50, endOffset: 100, count: 0 } + ]; + expect(() => validateV8Ranges(entry)).not.toThrow(); + entry.result.functions = []; + expect(() => validateV8Ranges(entry)).toThrow('Invalid raw V8'); + }); + + it('bounds unmapped execution by UTF-16 text after shebang removal, not UTF-8 bytes', () => { + const entry: IJestV8Coverage = createEntry(); + entry.source = '#!/usr/bin/env node\r\n\u00e9'; + entry.result.functions = [ + { functionName: '', isBlockCoverage: true, ranges: [{ startOffset: 0, endOffset: 3, count: 1 }] } + ]; + expect(() => validateV8Ranges(entry)).not.toThrow(); + entry.result.functions[0].ranges[0].endOffset = 4; + expect(() => validateV8Ranges(entry)).toThrow('Invalid raw V8'); + entry.sourceMap = createSourceMap(); + entry.result.functions[0].ranges[0].endOffset = entry.source.length; + expect(() => validateV8Ranges(entry)).not.toThrow(); + }); + + it.each(['source', 'sourceMap'] as const)( + 'rejects incompatible executed %s without changing state', + (field) => { + const scripts: Map = new Map(); + const entry: IJestV8Coverage = createEntry(); + entry.sourceMap = createSourceMap(); + addV8Coverage(scripts, entry); + const changed: IJestV8Coverage = structuredClone(entry); + if (field === 'source') { + changed.source += '.'; + } else { + changed.sourceMap!.sourcesContent[0] = 'changed'; + } + expect(() => addV8Coverage(scripts, changed)).toThrow('Incompatible V8'); + expect([...scripts.values()]).toEqual([entry]); + } + ); + + it('owns captured range trees and maps without mutating incoming observations', () => { + const scripts: Map = new Map(); + const entry: IJestV8Coverage = createEntry(); + entry.sourceMap = createSourceMap(); + const original: IJestV8Coverage = structuredClone(entry); + addV8Coverage(scripts, entry); + entry.sourceMap.sourcesContent[0] = 'changed'; + entry.result.functions[0].ranges[0].count = 99; + expect([...scripts.values()]).toEqual([original]); + const contribution: IJestV8Coverage = structuredClone(original); + addV8Coverage(scripts, contribution); + expect(contribution).toEqual(original); + contribution.sourceMap!.names.push('changed'); + expect(scripts.get(entry.result.url)!.sourceMap).toEqual(original.sourceMap); + }); + + it('rejects count overflow after merging without corrupting accumulated or incoming ranges', () => { + const scripts: Map = new Map(); + const entry: IJestV8Coverage = createEntry(); + entry.result.functions[0].ranges[0].count = Number.MAX_SAFE_INTEGER; + addV8Coverage(scripts, entry); + const next: IJestV8Coverage = createEntry(); + const original: IJestV8Coverage = structuredClone(next); + expect(() => addV8Coverage(scripts, next)).toThrow('Invalid raw V8'); + expect([...scripts.values()]).toEqual([entry]); + expect(next).toEqual(original); + }); +});