/
ts-jest-transformer.ts
170 lines (152 loc) · 6.3 KB
/
ts-jest-transformer.ts
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import createCacheKey from '@jest/create-cache-key-function'
import type { CacheKeyOptions, TransformedSource, Transformer, TransformOptions } from '@jest/transform'
import type { Config } from '@jest/types'
import type { Logger } from 'bs-logger'
import { ConfigSet } from './config/config-set'
import { JS_JSX_REGEX, TS_TSX_REGEX } from './constants'
import { stringify } from './utils/json'
import { JsonableValue } from './utils/jsonable-value'
import { rootLogger } from './utils/logger'
import { Errors, interpolate } from './utils/messages'
interface CachedConfigSet {
configSet: ConfigSet
jestConfig: JsonableValue<Config.ProjectConfig>
transformerCfgStr: string
}
export class TsJestTransformer implements Transformer {
/**
* cache ConfigSet between test runs
*
* @internal
*/
private static readonly _cachedConfigSets: CachedConfigSet[] = []
protected readonly logger: Logger
/**
* @internal
*/
private _transformCfgStr!: string
/**
* @internal
*/
private _tsJestCfgSet!: ConfigSet
constructor() {
this.logger = rootLogger.child({ namespace: 'ts-jest-transformer' })
this.logger.debug('created new transformer')
}
process(
input: string,
filePath: Config.Path,
jestConfig: Config.ProjectConfig,
transformOptions?: TransformOptions,
): TransformedSource | string {
this.logger.debug({ fileName: filePath, transformOptions }, 'processing', filePath)
let result: string | TransformedSource
const source: string = input
const { hooks } = this._tsJestCfgSet
const shouldStringifyContent = this._tsJestCfgSet.shouldStringifyContent(filePath)
const babelJest = shouldStringifyContent ? undefined : this._tsJestCfgSet.babelJestTransformer
const isDefinitionFile = filePath.endsWith('.d.ts')
const isJsFile = JS_JSX_REGEX.test(filePath)
const isTsFile = !isDefinitionFile && TS_TSX_REGEX.test(filePath)
if (shouldStringifyContent) {
// handles here what we should simply stringify
result = `module.exports=${stringify(source)}`
} else if (isDefinitionFile) {
// do not try to compile declaration files
result = ''
} else if (!this._tsJestCfgSet.parsedTsConfig.options.allowJs && isJsFile) {
// we've got a '.js' but the compiler option `allowJs` is not set or set to false
this.logger.warn({ fileName: filePath }, interpolate(Errors.GotJsFileButAllowJsFalse, { path: filePath }))
result = source
} else if (isJsFile || isTsFile) {
// transpile TS code (source maps are included)
/* istanbul ignore if */
result = this._tsJestCfgSet.tsCompiler.compile(source, filePath)
} else {
// we should not get called for files with other extension than js[x], ts[x] and d.ts,
// TypeScript will bail if we try to compile, and if it was to call babel, users can
// define the transform value with `babel-jest` for this extension instead
const message = babelJest ? Errors.GotUnknownFileTypeWithBabel : Errors.GotUnknownFileTypeWithoutBabel
this.logger.warn({ fileName: filePath }, interpolate(message, { path: filePath }))
result = source
}
// calling babel-jest transformer
if (babelJest) {
this.logger.debug({ fileName: filePath }, 'calling babel-jest processor')
// do not instrument here, jest will do it anyway afterwards
result = babelJest.process(result, filePath, jestConfig, { ...transformOptions, instrument: false })
}
// allows hooks (useful for internal testing)
/* istanbul ignore next (cover by e2e) */
if (hooks.afterProcess) {
this.logger.debug({ fileName: filePath, hookName: 'afterProcess' }, 'calling afterProcess hook')
const newResult = hooks.afterProcess([input, filePath, jestConfig, transformOptions], result)
if (newResult !== undefined) {
return newResult
}
}
return result
}
/**
* Jest uses this to cache the compiled version of a file
*
* @see https://github.com/facebook/jest/blob/v23.5.0/packages/jest-runtime/src/script_transformer.js#L61-L90
*/
getCacheKey(
fileContent: string,
filePath: string,
_jestConfigStr: string,
transformOptions: CacheKeyOptions,
): string {
this.createOrResolveTransformerCfg(transformOptions.config)
this.logger.debug({ fileName: filePath, transformOptions }, 'computing cache key for', filePath)
return createCacheKey()(fileContent, filePath, this._transformCfgStr, {
config: transformOptions.config,
instrument: false,
})
}
/**
* Users can override this method and provide their own config class
*/
protected createOrResolveTransformerCfg(jestConfig: Config.ProjectConfig): void {
const ccs: CachedConfigSet | undefined = TsJestTransformer._cachedConfigSets.find(
(cs) => cs.jestConfig.value === jestConfig,
)
if (ccs) {
this._transformCfgStr = ccs.transformerCfgStr
this._tsJestCfgSet = ccs.configSet
} else {
// try to look-it up by stringified version
const serializedJestCfg = stringify(jestConfig)
const serializedCcs = TsJestTransformer._cachedConfigSets.find(
(cs) => cs.jestConfig.serialized === serializedJestCfg,
)
if (serializedCcs) {
// update the object so that we can find it later
// this happens because jest first calls getCacheKey with stringified version of
// the config, and then it calls the transformer with the proper object
serializedCcs.jestConfig.value = jestConfig
this._transformCfgStr = serializedCcs.transformerCfgStr
this._tsJestCfgSet = serializedCcs.configSet
} else {
// create the new record in the index
this.logger.info('no matching config-set found, creating a new one')
this._tsJestCfgSet = new ConfigSet(jestConfig)
this._transformCfgStr = new JsonableValue({
digest: this._tsJestCfgSet.tsJestDigest,
babel: this._tsJestCfgSet.babelConfig,
...jestConfig,
tsconfig: {
options: this._tsJestCfgSet.parsedTsConfig.options,
raw: this._tsJestCfgSet.parsedTsConfig.raw,
},
}).serialized
TsJestTransformer._cachedConfigSets.push({
jestConfig: new JsonableValue(jestConfig),
configSet: this._tsJestCfgSet,
transformerCfgStr: this._transformCfgStr,
})
}
}
}
}