1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | const { createHash } = require('crypto');
|
18 | const { transform } = require('sucrase');
|
19 | const sucrasePkg = require('sucrase/package.json');
|
20 | const sucrasePluginPkg = require('@sucrase/jest-plugin/package.json');
|
21 |
|
22 | const ESM_REGEX = /\b(?:import|export)\b/;
|
23 |
|
24 | function createTransformer(config) {
|
25 | const process = (source, filePath) => {
|
26 | let transforms;
|
27 |
|
28 | if (filePath.endsWith('.esm.js')) {
|
29 | transforms = ['imports'];
|
30 | } else if (filePath.endsWith('.js')) {
|
31 |
|
32 |
|
33 | if (ESM_REGEX.test(source)) {
|
34 | transforms = ['imports', 'jsx'];
|
35 | }
|
36 | } else if (filePath.endsWith('.jsx')) {
|
37 | transforms = ['jsx', 'imports'];
|
38 | } else if (filePath.endsWith('.ts')) {
|
39 | transforms = ['typescript', 'imports'];
|
40 | } else if (filePath.endsWith('.tsx')) {
|
41 | transforms = ['typescript', 'jsx', 'imports'];
|
42 | }
|
43 |
|
44 |
|
45 | if (transforms && filePath.includes('.test.')) {
|
46 | transforms.push('jest');
|
47 | }
|
48 |
|
49 | if (transforms) {
|
50 | const { code, sourceMap: map } = transform(source, {
|
51 | transforms,
|
52 | filePath,
|
53 | disableESTransforms: true,
|
54 | sourceMapOptions: {
|
55 | compiledFilename: filePath,
|
56 | },
|
57 | });
|
58 | if (config.enableSourceMaps) {
|
59 | const b64 = Buffer.from(JSON.stringify(map), 'utf8').toString('base64');
|
60 | const suffix = `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${b64}`;
|
61 |
|
62 |
|
63 | return { code: `${code}\n${suffix}`, map };
|
64 | }
|
65 |
|
66 |
|
67 | return code;
|
68 | }
|
69 |
|
70 | return source;
|
71 | };
|
72 |
|
73 |
|
74 | const getCacheKey = sourceText => {
|
75 | return createHash('md5')
|
76 | .update(sourceText)
|
77 | .update(Buffer.alloc(1))
|
78 | .update(sucrasePkg.version)
|
79 | .update(Buffer.alloc(1))
|
80 | .update(sucrasePluginPkg.version)
|
81 | .update(Buffer.alloc(1))
|
82 | .update(JSON.stringify(config))
|
83 | .update(Buffer.alloc(1))
|
84 | .update('1')
|
85 | .digest('hex');
|
86 | };
|
87 |
|
88 | return { process, getCacheKey };
|
89 | }
|
90 |
|
91 | module.exports = { createTransformer };
|