/
ts-compiler.ts
250 lines (222 loc) · 10.4 KB
/
ts-compiler.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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import { LogContexts, Logger, LogLevels } from 'bs-logger'
import memoize from 'lodash.memoize'
import { basename, normalize, relative } from 'path'
import {
EmitOutput,
LanguageService,
LanguageServiceHost,
ParsedCommandLine,
ResolvedModuleFull,
TranspileOutput,
ModuleKind,
} from 'typescript'
import { updateOutput } from './compiler-utils'
import type { ConfigSet } from '../config/config-set'
import { LINE_FEED } from '../constants'
import type { CompilerInstance, ResolvedModulesMap, StringMap, TTypeScript } from '../types'
import { rootLogger } from '../utils/logger'
import { Errors, interpolate } from '../utils/messages'
const AVAILABLE_ESM_MODULE_KINDS = [ModuleKind.ES2015, ModuleKind.ES2020, ModuleKind.ESNext]
/**
* @internal
*/
export class TsCompiler implements CompilerInstance {
private readonly _logger: Logger
private readonly _ts: TTypeScript
private readonly _parsedTsConfig: ParsedCommandLine
private readonly _compilerCacheFS: Map<string, number> = new Map<string, number>()
private readonly _jestCacheFS: StringMap
private _cachedReadFile: ((fileName: string) => string | undefined) | undefined
private _projectVersion = 1
private _languageService: LanguageService | undefined
constructor(readonly configSet: ConfigSet, readonly jestCacheFS: StringMap) {
this._ts = configSet.compilerModule
this._logger = rootLogger.child({ namespace: 'ts-compiler' })
this._parsedTsConfig = this.configSet.parsedTsConfig as ParsedCommandLine
this._jestCacheFS = jestCacheFS
if (!this.configSet.isolatedModules) {
this._createLanguageService()
}
}
private _createLanguageService(): void {
const compilerOptions = {
...this._parsedTsConfig.options,
module: ModuleKind.CommonJS,
}
const serviceHostTraceCtx = {
namespace: 'ts:serviceHost',
call: null,
[LogContexts.logLevel]: LogLevels.trace,
}
// Initialize memory cache for typescript compiler
this._parsedTsConfig.fileNames
.filter((fileName) => !this.configSet.isTestFile(fileName))
.forEach((fileName) => this._compilerCacheFS.set(fileName, 0))
this._cachedReadFile = this._logger.wrap(serviceHostTraceCtx, 'readFile', memoize(this._ts.sys.readFile))
/* istanbul ignore next */
const moduleResolutionHost = {
fileExists: memoize(this._ts.sys.fileExists),
readFile: this._cachedReadFile,
directoryExists: memoize(this._ts.sys.directoryExists),
getCurrentDirectory: () => this.configSet.cwd,
realpath: this._ts.sys.realpath && memoize(this._ts.sys.realpath),
getDirectories: memoize(this._ts.sys.getDirectories),
}
const moduleResolutionCache = this._ts.createModuleResolutionCache(this.configSet.cwd, (x) => x, compilerOptions)
/* istanbul ignore next */
const serviceHost: LanguageServiceHost = {
getProjectVersion: () => String(this._projectVersion),
getScriptFileNames: () => [...this._compilerCacheFS.keys()],
getScriptVersion: (fileName: string) => {
const normalizedFileName = normalize(fileName)
const version = this._compilerCacheFS.get(normalizedFileName)
// We need to return `undefined` and not a string here because TypeScript will use
// `getScriptVersion` and compare against their own version - which can be `undefined`.
// If we don't return `undefined` it results in `undefined === "undefined"` and run
// `createProgram` again (which is very slow). Using a `string` assertion here to avoid
// TypeScript errors from the function signature (expects `(x: string) => string`).
return version === undefined ? ((undefined as any) as string) : String(version)
},
getScriptSnapshot: (fileName: string) => {
const normalizedFileName = normalize(fileName)
const hit = this._isFileInCache(normalizedFileName)
this._logger.trace({ normalizedFileName, cacheHit: hit }, 'getScriptSnapshot():', 'cache', hit ? 'hit' : 'miss')
// Read contents from TypeScript memory cache.
if (!hit) {
const fileContent =
this._jestCacheFS.get(normalizedFileName) ?? this._cachedReadFile?.(normalizedFileName) ?? undefined
if (fileContent) {
this._jestCacheFS.set(normalizedFileName, fileContent)
this._compilerCacheFS.set(normalizedFileName, 1)
}
}
const contents = this._jestCacheFS.get(normalizedFileName)
if (contents === undefined) return
return this._ts.ScriptSnapshot.fromString(contents)
},
fileExists: memoize(this._ts.sys.fileExists),
readFile: this._cachedReadFile,
readDirectory: memoize(this._ts.sys.readDirectory),
getDirectories: memoize(this._ts.sys.getDirectories),
directoryExists: memoize(this._ts.sys.directoryExists),
realpath: this._ts.sys.realpath && memoize(this._ts.sys.realpath),
getNewLine: () => LINE_FEED,
getCurrentDirectory: () => this.configSet.cwd,
getCompilationSettings: () => compilerOptions,
getDefaultLibFileName: () => this._ts.getDefaultLibFilePath(compilerOptions),
getCustomTransformers: () => this.configSet.customTransformers,
resolveModuleNames: (moduleNames: string[], containingFile: string): (ResolvedModuleFull | undefined)[] =>
moduleNames.map((moduleName) => {
const { resolvedModule } = this._ts.resolveModuleName(
moduleName,
containingFile,
compilerOptions,
moduleResolutionHost,
moduleResolutionCache,
)
return resolvedModule
}),
}
this._logger.debug('created language service')
this._languageService = this._ts.createLanguageService(serviceHost, this._ts.createDocumentRegistry())
}
getResolvedModulesMap(fileContent: string, fileName: string): ResolvedModulesMap {
this._updateMemoryCache(fileContent, fileName)
// See https://github.com/microsoft/TypeScript/blob/master/src/compiler/utilities.ts#L164
return (this._languageService?.getProgram()?.getSourceFile(fileName) as any)?.resolvedModules
}
getCompiledOutput(fileContent: string, fileName: string, supportsStaticESM: boolean): string {
if (this._languageService) {
this._logger.debug({ fileName }, 'getCompiledOutput(): compiling using language service')
// Must set memory cache before attempting to compile
this._updateMemoryCache(fileContent, fileName)
const output: EmitOutput = this._languageService.getEmitOutput(fileName)
this._logger.debug({ fileName }, 'getCompiledOutput(): computing diagnostics using language service')
this._doTypeChecking(fileName)
/* istanbul ignore next (this should never happen but is kept for security) */
if (output.emitSkipped) {
throw new TypeError(`${relative(this.configSet.cwd, fileName)}: Emit skipped for language service`)
}
// Throw an error when requiring `.d.ts` files.
if (!output.outputFiles.length) {
throw new TypeError(
interpolate(Errors.UnableToRequireDefinitionFile, {
file: basename(fileName),
}),
)
}
return updateOutput(output.outputFiles[1].text, fileName, output.outputFiles[0].text)
} else {
let moduleKind = this._parsedTsConfig.options.module
if (supportsStaticESM && this.configSet.useESM) {
moduleKind =
!moduleKind || (moduleKind && !AVAILABLE_ESM_MODULE_KINDS.includes(moduleKind))
? ModuleKind.ESNext
: moduleKind
} else {
moduleKind = ModuleKind.CommonJS
}
this._logger.debug({ fileName }, 'getCompiledOutput(): compiling as isolated module')
const result: TranspileOutput = this._ts.transpileModule(fileContent, {
fileName,
transformers: this.configSet.customTransformers,
compilerOptions: {
...this._parsedTsConfig.options,
module: moduleKind,
},
reportDiagnostics: this.configSet.shouldReportDiagnostics(fileName),
})
if (result.diagnostics && this.configSet.shouldReportDiagnostics(fileName)) {
this.configSet.raiseDiagnostics(result.diagnostics, fileName, this._logger)
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return updateOutput(result.outputText, fileName, result.sourceMapText!)
}
}
private _isFileInCache(fileName: string): boolean {
return (
this._jestCacheFS.has(fileName) &&
this._compilerCacheFS.has(fileName) &&
this._compilerCacheFS.get(fileName) !== 0
)
}
/* istanbul ignore next */
private _updateMemoryCache(contents: string, fileName: string): void {
this._logger.debug({ fileName }, 'updateMemoryCache: update memory cache for language service')
let shouldIncrementProjectVersion = false
const hit = this._isFileInCache(fileName)
if (!hit) {
this._compilerCacheFS.set(fileName, 1)
shouldIncrementProjectVersion = true
} else {
const prevVersion = this._compilerCacheFS.get(fileName) ?? 0
const previousContents = this._jestCacheFS.get(fileName)
// Avoid incrementing cache when nothing has changed.
if (previousContents !== contents) {
this._compilerCacheFS.set(fileName, prevVersion + 1)
// Only bump project version when file is modified in cache, not when discovered for the first time
if (hit) shouldIncrementProjectVersion = true
}
/**
* When a file is from node_modules or referenced to a referenced project and jest wants to transform it, we need
* to make sure that the Program is updated with this information
*/
if (!this._parsedTsConfig.fileNames.includes(fileName)) {
shouldIncrementProjectVersion = true
}
}
if (shouldIncrementProjectVersion) this._projectVersion++
}
private _doTypeChecking(fileName: string): void {
if (this.configSet.shouldReportDiagnostics(fileName)) {
// Get the relevant diagnostics - this is 3x faster than `getPreEmitDiagnostics`.
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const diagnostics = this._languageService!.getSemanticDiagnostics(fileName).concat(
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this._languageService!.getSyntacticDiagnostics(fileName),
)
// will raise or just warn diagnostics depending on config
this.configSet.raiseDiagnostics(diagnostics, fileName, this._logger)
}
}
}