UNPKG

2.16 kBPlain TextView Raw
1import type {TransformOptions} from "@jest/transform";
2import {extname} from "path";
3import {Transform, transform} from "sucrase";
4
5import type {Options} from "../../../src/Options";
6
7function getTransforms(filename: string, supportsStaticESM: boolean): Array<Transform> | null {
8 const extension = extname(filename);
9 const maybeImports: Array<Transform> = supportsStaticESM ? [] : ["imports"];
10 if ([".js", ".jsx", ".mjs", ".cjs"].includes(extension)) {
11 return [...maybeImports, "flow", "jsx", "jest"];
12 } else if (extension === ".ts") {
13 return [...maybeImports, "typescript", "jest"];
14 } else if ([".tsx", ".mts", ".cts"].includes(extension)) {
15 return [...maybeImports, "typescript", "jsx", "jest"];
16 }
17 return null;
18}
19
20// this is compatible to the one that is required by Jest, using the type from here:
21// https://github.com/mozilla/source-map/blob/0.6.1/source-map.d.ts#L6-L12
22type RawSourceMap = ReturnType<typeof transform>["sourceMap"];
23
24export function process(
25 src: string,
26 filename: string,
27 options: TransformOptions<Partial<Options>>,
28): {code: string; map?: RawSourceMap | string | null} {
29 const transforms = getTransforms(filename, options.supportsStaticESM);
30 if (transforms !== null) {
31 const {code, sourceMap} = transform(src, {
32 transforms,
33 disableESTransforms: true,
34 preserveDynamicImport: options.supportsDynamicImport,
35 ...options.transformerConfig,
36 sourceMapOptions: {compiledFilename: filename},
37 filePath: filename,
38 });
39 const mapBase64 = Buffer.from(JSON.stringify(sourceMap)).toString("base64");
40 // Split the source map comment across two strings so that tools like
41 // source-map-support don't accidentally interpret it as a source map
42 // comment for this file.
43 let suffix = "//# sourceMapping";
44 suffix += `URL=data:application/json;charset=utf-8;base64,${mapBase64}`;
45 // sourceMappingURL is necessary for breakpoints to work in WebStorm, so
46 // include it in addition to specifying the source map normally.
47 return {code: `${code}\n${suffix}`, map: sourceMap};
48 } else {
49 return {code: src};
50 }
51}
52
53export default {process};