-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnycInstrumentationPlugin.ts
More file actions
72 lines (61 loc) · 1.97 KB
/
Copy pathnycInstrumentationPlugin.ts
File metadata and controls
72 lines (61 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import type { Plugin } from "vite";
const SHOULD_INSTRUMENT_WITH_NYC = process.env.NYC_INSTRUMENT === "true";
export function createNycInstrumentationPlugin(): Plugin {
let instrumenterPromise: Promise<{
instrumentSync: (code: string, filename: string, sourceMap?: object) => string;
lastSourceMap: () => object | undefined;
}> | null = null;
const loadInstrumenter = () => {
instrumenterPromise ??= import(String("istanbul-lib-instrument")).then((module: unknown) => {
const { createInstrumenter } = module as {
createInstrumenter: (options: {
esModules: boolean;
produceSourceMap: boolean;
compact: boolean;
parserPlugins: string[];
}) => {
instrumentSync: (code: string, filename: string, sourceMap?: object) => string;
lastSourceMap: () => object | undefined;
};
};
return createInstrumenter({
esModules: true,
produceSourceMap: true,
compact: false,
parserPlugins: ["typescript", "jsx"],
});
});
return instrumenterPromise;
};
return {
name: "nyc-instrumentation",
enforce: "post",
async transform(code, id, _options) {
void _options;
if (!SHOULD_INSTRUMENT_WITH_NYC) {
return null;
}
const [filename] = id.split("?");
if (
filename == null ||
!filename.includes("/src/") ||
!/\.(ts|tsx)$/.test(filename) ||
/\.test\./.test(filename)
) {
return null;
}
const instrumenter = await loadInstrumenter();
const sourceMap = this.getCombinedSourcemap();
const instrumentedCode = instrumenter.instrumentSync(
code,
filename,
sourceMap && Object.keys(sourceMap).length > 0 ? sourceMap : undefined,
);
const instrumentedResult = {
code: instrumentedCode,
map: instrumenter.lastSourceMap(),
} as unknown as never;
return instrumentedResult;
},
};
}