1 | import type {TransformOptions} from "@jest/transform";
|
2 | import {extname} from "path";
|
3 | import {Transform, transform} from "sucrase";
|
4 |
|
5 | import type {Options} from "../../../src/Options";
|
6 |
|
7 | function 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 |
|
21 |
|
22 | type RawSourceMap = ReturnType<typeof transform>["sourceMap"];
|
23 |
|
24 | export 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 |
|
41 |
|
42 |
|
43 | let suffix = "//# sourceMapping";
|
44 | suffix += `URL=data:application/json;charset=utf-8;base64,${mapBase64}`;
|
45 |
|
46 |
|
47 | return {code: `${code}\n${suffix}`, map: sourceMap};
|
48 | } else {
|
49 | return {code: src};
|
50 | }
|
51 | }
|
52 |
|
53 | export default {process};
|