UNPKG

1.45 kBPlain TextView Raw
1import {Transform, transform} from "sucrase";
2
3function getTransforms(filename: string): Array<Transform> | null {
4 if (filename.endsWith(".js") || filename.endsWith(".jsx")) {
5 return ["flow", "jsx", "imports", "jest"];
6 } else if (filename.endsWith(".ts")) {
7 return ["typescript", "imports", "jest"];
8 } else if (filename.endsWith(".tsx")) {
9 return ["typescript", "jsx", "imports", "jest"];
10 }
11 return null;
12}
13
14// this is compatible to the one that is required by Jest, using the type from here:
15// https://github.com/mozilla/source-map/blob/0.6.1/source-map.d.ts#L6-L12
16type RawSourceMap = ReturnType<typeof transform>["sourceMap"];
17
18export function process(
19 src: string,
20 filename: string,
21): {code: string; map?: RawSourceMap | string | null} {
22 const transforms = getTransforms(filename);
23 if (transforms !== null) {
24 const {code, sourceMap} = transform(src, {
25 transforms,
26 sourceMapOptions: {compiledFilename: filename},
27 filePath: filename,
28 });
29 const mapBase64 = Buffer.from(JSON.stringify(sourceMap)).toString("base64");
30 const suffix = `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${mapBase64}`;
31 // sourceMappingURL is necessary for breakpoints to work in WebStorm, so
32 // include it in addition to specifying the source map normally.
33 return {code: `${code}\n${suffix}`, map: sourceMap};
34 } else {
35 return {code: src};
36 }
37}
38
39export default {process};