Skip to content

Commit fdd345b

Browse files
authored
feat(lib-instrument)!: replace babel with rolldown + magic-string (#28)
1 parent ddb0a7e commit fdd345b

18 files changed

Lines changed: 1154 additions & 1099 deletions

‎.github/renovate.json‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,11 @@
3333
"description": "Node version is managed manually",
3434
"matchDepNames": ["node"],
3535
"enabled": false
36+
},
37+
{
38+
"description": "Keep the wide rolldown range, so that it's shared with Vite's own rolldown",
39+
"matchPackageNames": ["rolldown"],
40+
"enabled": false
3641
}
3742
]
3843
}

‎packages/istanbul-lib-instrument/README.md‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,15 @@
22

33
[![Build Status](https://img.shields.io/github/actions/workflow/status/vitest-dev/istanbuljs/ci.yml?label=CI&logo=GitHub)](https://github.com/vitest-dev/istanbuljs/actions/workflows/ci.yml)
44

5-
Istanbul instrumenter library, implemented using `Babel`. The implementation is inspired
6-
by prior art by @dtinth as demonstrated in the `__coverage__` babel plugin.
5+
Istanbul instrumenter library. The code is parsed with [OXC](https://oxc.rs) (via `rolldown`) and
6+
coverage counters are inserted into the original code with `magic-string`, so the output keeps the
7+
original formatting, comments and line numbers.
78

8-
It provides 2 "modes" of instrumentation.
9+
```ts
10+
import { createInstrumenter } from "@vitest/istanbul-lib-instrument";
911

10-
- An `Instrumenter` API that performs the instrumentation using babel as a library.
11-
12-
- A `programVisitor` function for the Babel AST that can be used by a Babel plugin
13-
to emit instrumentation for ES6 code directly without any source map
14-
processing. This is the preferred path for babel users. The Babel plugin is
15-
called `babel-plugin-istanbul`.
12+
const instrumenter = createInstrumenter({ esModules: true, produceSourceMap: true });
13+
const code = instrumenter.instrumentSync(source, filename, inputSourceMap);
14+
const coverage = instrumenter.lastFileCoverage();
15+
const map = instrumenter.lastSourceMap();
16+
```

‎packages/istanbul-lib-instrument/package.json‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,12 @@
3535
"test": "pnpm --filter @vitest/istanbuljs-monorepo run test --project @vitest/istanbul-lib-instrument"
3636
},
3737
"dependencies": {
38-
"@babel/core": "catalog:",
39-
"@babel/parser": "catalog:",
4038
"@istanbuljs/schema": "catalog:",
39+
"@jridgewell/remapping": "catalog:",
4140
"@jridgewell/trace-mapping": "catalog:",
42-
"@vitest/istanbul-lib-coverage": "workspace:*"
41+
"@vitest/istanbul-lib-coverage": "workspace:*",
42+
"magic-string": "catalog:",
43+
"rolldown": "catalog:"
4344
},
4445
"devDependencies": {
4546
"tsdown": "catalog:",

‎packages/istanbul-lib-instrument/src/index.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ import { defaults } from "@istanbuljs/schema";
33
import Instrumenter from "./instrumenter";
44
import type { InstrumenterOptions } from "./instrumenter";
55
import readInitialCoverage from "./read-coverage";
6-
import programVisitor from "./visitor";
76

87
/**
98
* createInstrumenter creates a new instrumenter with the
@@ -17,10 +16,9 @@ function createInstrumenter(opts?: Partial<InstrumenterOptions>): Instrumenter {
1716

1817
const defaultOpts = defaults.instrumenter;
1918

20-
export { createInstrumenter, programVisitor, readInitialCoverage, defaultOpts };
19+
export { createInstrumenter, readInitialCoverage, defaultOpts };
2120

2221
export type { Instrumenter };
23-
export type { InstrumenterCallback, InstrumenterOptions } from "./instrumenter";
22+
export type { InstrumenterCallback, InstrumenterOptions, SourceMap } from "./instrumenter";
2423
export type { InitialCoverage } from "./read-coverage";
2524
export type { InputSourceMap, SourceCoverageData } from "./source-coverage";
26-
export type { VisitorExitResult, VisitorOptions } from "./visitor";

‎packages/istanbul-lib-instrument/src/instrumenter.ts‎

Lines changed: 66 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,33 @@
11
/*
2-
Copyright 2012-2015, Yahoo Inc.
3-
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
4-
*/
5-
import { transformSync } from "@babel/core";
6-
import type { FileResult, InputOptions, NodePath, PluginObject, types as t } from "@babel/core";
7-
import type { ParserPlugin } from "@babel/parser";
2+
Copyright 2012-2015, Yahoo Inc.
3+
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
4+
*/
85
import { defaults } from "@istanbuljs/schema";
6+
import remapping from "@jridgewell/remapping";
7+
import type { EncodedSourceMap } from "@jridgewell/trace-mapping";
8+
import MagicString from "magic-string";
99

10+
import { parse } from "./parse";
1011
import readInitialCoverage from "./read-coverage";
1112
import type { InputSourceMap, SourceCoverageData } from "./source-coverage";
12-
import programVisitor from "./visitor";
13-
import type { VisitorExitResult } from "./visitor";
13+
import instrumentProgram from "./visitor";
1414

15-
/** source map produced by babel's transform */
16-
type SourceMap = NonNullable<FileResult["map"]>;
15+
/** source map produced for the instrumented code */
16+
export type SourceMap = EncodedSourceMap;
1717

1818
/** options accepted by {@link Instrumenter} and {@link createInstrumenter} */
1919
export interface InstrumenterOptions {
2020
/** name of global coverage variable (default `__coverage__`) */
2121
coverageVariable: string;
2222
/** report boolean value of logical expressions (default `false`) */
2323
reportLogic: boolean;
24-
/** preserve comments in output (default `false`) */
24+
/**
25+
* @deprecated has no effect, comments of the original code are always preserved
26+
*/
2527
preserveComments: boolean;
26-
/** generate compact code (default `true`) */
28+
/**
29+
* @deprecated has no effect, the original code is preserved as-is
30+
*/
2731
compact: boolean;
2832
/** set to true to instrument ES6 modules */
2933
esModules: boolean;
@@ -41,26 +45,23 @@ export interface InstrumenterOptions {
4145
* and the source map URL.
4246
*/
4347
sourceMapUrlCallback: ((filename: string, url: string) => void) | null;
44-
/** turn debugging on (default `false`) */
48+
/**
49+
* @deprecated has no effect
50+
*/
4551
debug: boolean;
46-
/** set babel parser plugins, see @istanbuljs/schema for defaults */
47-
parserPlugins: ParserPlugin[];
4852
/** the global coverage variable scope (default `this`) */
4953
coverageGlobalScope: string;
5054
/** use an evaluated function to find coverageGlobalScope (default `true`) */
5155
coverageGlobalScopeFunc: boolean;
52-
/** set babel generator options */
53-
generatorOpts?: Record<string, unknown>;
5456
}
5557

5658
/** callback for the callback-style {@link Instrumenter#instrument} method */
5759
export type InstrumenterCallback = (error: Error | null, code?: string) => void;
5860

5961
/**
6062
* Instrumenter is the public API for the instrument library.
61-
* It is typically used for ES5 code. For ES6 code that you
62-
* are already running under `babel` use the coverage plugin
63-
* instead.
63+
* The code is parsed with OXC and coverage counters are inserted
64+
* into the original code with `magic-string`.
6465
* @param opts optional. See {@link InstrumenterOptions}.
6566
*/
6667
class Instrumenter {
@@ -95,67 +96,35 @@ class Instrumenter {
9596
}
9697
filename = filename || String(new Date().getTime()) + ".js";
9798
const { opts } = this;
98-
let output: VisitorExitResult | undefined;
99-
const babelOpts: InputOptions = {
100-
configFile: false,
101-
babelrc: false,
102-
ast: true,
103-
filename: filename || String(new Date().getTime()) + ".js",
104-
// trace-mapping allows `sources: (string | null)[]`, babel's types don't — same runtime shape
105-
inputSourceMap: inputSourceMap as InputOptions["inputSourceMap"],
106-
sourceMaps: opts.produceSourceMap,
107-
compact: opts.compact,
108-
comments: opts.preserveComments,
109-
parserOpts: {
110-
allowReturnOutsideFunction: opts.autoWrap,
111-
sourceType: opts.esModules ? "module" : "script",
112-
plugins: opts.parserPlugins,
113-
},
114-
generatorOpts: opts.generatorOpts,
115-
plugins: [
116-
({ types }: { types: typeof t }): PluginObject => {
117-
const ee = programVisitor(types, filename as string, {
118-
coverageVariable: opts.coverageVariable,
119-
reportLogic: opts.reportLogic,
120-
coverageGlobalScope: opts.coverageGlobalScope,
121-
coverageGlobalScopeFunc: opts.coverageGlobalScopeFunc,
122-
ignoreClassMethods: opts.ignoreClassMethods,
123-
ignoreLines: opts.ignoreLines,
124-
inputSourceMap,
125-
});
99+
const { program, comments } = parse(code, filename, opts);
100+
const s = new MagicString(code);
126101

127-
return {
128-
visitor: {
129-
Program: {
130-
enter: ee.enter,
131-
exit(path: NodePath<t.Program>) {
132-
output = ee.exit(path);
133-
},
134-
},
135-
},
136-
};
137-
},
138-
],
139-
};
140-
141-
const codeMap = transformSync(code, babelOpts)!;
102+
const output = instrumentProgram(s, program, comments, filename, {
103+
coverageVariable: opts.coverageVariable,
104+
reportLogic: opts.reportLogic,
105+
coverageGlobalScope: opts.coverageGlobalScope,
106+
coverageGlobalScopeFunc: opts.coverageGlobalScopeFunc,
107+
ignoreClassMethods: opts.ignoreClassMethods,
108+
ignoreLines: opts.ignoreLines,
109+
inputSourceMap,
110+
});
142111

143-
if (!output || !output.fileCoverage) {
112+
if (!output) {
144113
const initialCoverage =
145-
readInitialCoverage(codeMap.ast!) || /* istanbul ignore next: paranoid check */ {};
114+
readInitialCoverage(program) || /* istanbul ignore next: paranoid check */ {};
146115
this.fileCoverage = (initialCoverage as { coverageData?: SourceCoverageData }).coverageData;
147116
this.sourceMap = inputSourceMap;
148117
return code;
149118
}
150119

151120
this.fileCoverage = output.fileCoverage;
152-
this.sourceMap = codeMap.map;
121+
this.sourceMap = opts.produceSourceMap ? createSourceMap(s, filename, inputSourceMap) : null;
153122
const cb = this.opts.sourceMapUrlCallback;
154123
if (cb && output.sourceMappingURL) {
155124
cb(filename, output.sourceMappingURL);
156125
}
157126

158-
return codeMap.code as string;
127+
return s.toString();
159128
}
160129
/**
161130
* callback-style instrument method that calls back with an error
@@ -202,4 +171,34 @@ class Instrumenter {
202171
}
203172
}
204173

174+
// maps the instrumented code to the input code, and further to the original
175+
// sources when the input code has a source map
176+
function createSourceMap(
177+
s: MagicString,
178+
filename: string,
179+
inputSourceMap?: InputSourceMap,
180+
): SourceMap {
181+
const map = s.generateMap({ hires: "boundary", source: filename, includeContent: true });
182+
if (!inputSourceMap) {
183+
return {
184+
version: 3,
185+
names: map.names,
186+
sources: map.sources,
187+
sourcesContent: map.sourcesContent,
188+
mappings: map.mappings,
189+
};
190+
}
191+
const remapped = remapping([map as EncodedSourceMap, inputSourceMap], () => null);
192+
return {
193+
version: 3,
194+
names: remapped.names,
195+
sources: remapped.sources,
196+
sourcesContent: remapped.sourcesContent,
197+
mappings: remapped.mappings as string,
198+
...(remapped.ignoreList && remapped.ignoreList.length > 0
199+
? { ignoreList: remapped.ignoreList }
200+
: {}),
201+
};
202+
}
203+
205204
export default Instrumenter;

‎packages/istanbul-lib-instrument/src/istanbuljs-schema.d.ts‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33
* this package is declared here, shaped after the actual runtime values.
44
*/
55
declare module "@istanbuljs/schema" {
6-
import type { ParserPlugin } from "@babel/parser";
7-
86
export const defaults: {
97
instrumenter: {
108
coverageVariable: string;
@@ -13,7 +11,7 @@ declare module "@istanbuljs/schema" {
1311
ignoreClassMethods: string[];
1412
autoWrap: boolean;
1513
esModules: boolean;
16-
parserPlugins: ParserPlugin[];
14+
parserPlugins: string[];
1715
compact: boolean;
1816
preserveComments: boolean;
1917
produceSourceMap: boolean;
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
* For Vitest users rolldown will be a transitive dependency of Vite 8.
3+
* If we wanted to drop rolldown dep, we could do something similar to what ast-v8-to-istanbul does
4+
* with its `options.ast` option. That would require js-tokens for comment parsing.
5+
*/
6+
import { parseSync } from "rolldown/utils";
7+
import type { ESTree } from "rolldown/utils";
8+
9+
import type { Comment } from "./visitor";
10+
11+
const RETURN_OUTSIDE_FUNCTION_RE = /'return' statement can only be used within a function body/;
12+
13+
/** options accepted by {@link parse} */
14+
export interface ParseOptions {
15+
/** parse the code as ES module */
16+
esModules: boolean;
17+
/** allow `return` statements outside of functions */
18+
autoWrap: boolean;
19+
/** do not throw on syntax errors */
20+
lenient?: boolean;
21+
}
22+
23+
/** the parsed program and its comments */
24+
export interface ParsedProgram {
25+
program: ESTree.Program;
26+
comments: Comment[];
27+
}
28+
29+
/**
30+
* Parses JavaScript (and JSX) code with OXC.
31+
* Throws a `SyntaxError` for invalid code, unless `lenient` is set.
32+
*/
33+
export function parse(code: string, filename: string, opts: ParseOptions): ParsedProgram {
34+
const result = parseSync(filename, code, {
35+
lang: "jsx",
36+
sourceType: opts.esModules ? "module" : "script",
37+
});
38+
39+
if (!opts.lenient) {
40+
const errors = result.errors.filter(
41+
(e) =>
42+
e.severity === "Error" && !(opts.autoWrap && RETURN_OUTSIDE_FUNCTION_RE.test(e.message)),
43+
);
44+
if (errors.length > 0) {
45+
const [error] = errors;
46+
throw new SyntaxError(
47+
error.message + (error.codeframe ? "\n" + error.codeframe : "") + `\nFile: ${filename}`,
48+
);
49+
}
50+
}
51+
52+
return { program: result.program, comments: result.comments };
53+
}

0 commit comments

Comments
 (0)