-
Notifications
You must be signed in to change notification settings - Fork 454
/
config-set.ts
650 lines (586 loc) · 21.4 KB
/
config-set.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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
/**
* This is the core of settings and so ts-jest.
* Since configuration are used to create a good cache key, everything
* depending on it is here. Fast jest relies on correct cache keys
* depending on all settings that could affect the generated output.
*
* The big issue is that jest calls first `getCacheKey()` with stringified
* version of the `jest.ProjectConfig`, and then later it calls `process()`
* with the complete, object version of it.
*/
import type { TransformedSource } from '@jest/transform'
import type { Config } from '@jest/types'
import { LogContexts, Logger } from 'bs-logger'
import { existsSync, readFileSync } from 'fs'
import { globsToMatcher } from 'jest-util'
import json5 = require('json5')
import { dirname, extname, isAbsolute, join, normalize, resolve } from 'path'
import {
CompilerOptions,
CustomTransformers,
Diagnostic,
FormatDiagnosticsHost,
ParsedCommandLine,
ScriptTarget,
} from 'typescript'
import { createCompilerInstance } from '../compiler/instance'
import { DEFAULT_JEST_TEST_MATCH } from '../constants'
import { factory as hoisting } from '../transformers/hoist-jest'
import type {
AstTransformer,
BabelConfig,
BabelJestTransformer,
TsCompiler,
TsJestDiagnosticsCfg,
TsJestGlobalOptions,
TTypeScript,
} from '../types'
import { backportJestConfig } from '../utils/backports'
import { importer } from '../utils/importer'
import { stringify } from '../utils/json'
import { rootLogger } from '../utils/logger'
import { Memoize } from '../utils/memoize'
import { Deprecations, Errors, ImportReasons, interpolate } from '../utils/messages'
import { normalizeSlashes } from '../utils/normalize-slashes'
import { sha1 } from '../utils/sha1'
import { TSError } from '../utils/ts-error'
/**
* @internal
*/
export const MY_DIGEST: string = readFileSync(resolve(__dirname, '..', '..', '.ts-jest-digest'), 'utf8')
interface TsJestHooksMap {
afterProcess?(args: any[], result: string | TransformedSource): string | TransformedSource | void
}
/**
* @internal
*/
export const IGNORE_DIAGNOSTIC_CODES = [
6059, // "'rootDir' is expected to contain all source files."
18002, // "The 'files' list in config file is empty."
18003, // "No inputs were found in config file."
]
/**
* @internal
*/
export const TS_JEST_OUT_DIR = '$$ts-jest$$'
const TARGET_TO_VERSION_MAPPING: Record<number, string> = {
[ScriptTarget.ES2018]: 'es2018',
[ScriptTarget.ES2019]: 'es2019',
[ScriptTarget.ES2020]: 'es2020',
[ScriptTarget.ESNext]: 'ESNext',
}
/**
* @internal
*/
// WARNING: DO NOT CHANGE THE ORDER OF CODE NAMES!
// ONLY APPEND IF YOU NEED TO ADD SOME
const enum DiagnosticCodes {
TsJest = 151000,
ConfigModuleOption,
}
const normalizeRegex = (pattern: string | RegExp | undefined): string | undefined =>
pattern ? (typeof pattern === 'string' ? pattern : pattern.source) : undefined
const toDiagnosticCode = (code: any): number | undefined =>
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
code ? parseInt(`${code}`.trim().replace(/^TS/, ''), 10) ?? undefined : undefined
const toDiagnosticCodeList = (items: (string | number)[], into: number[] = []): number[] => {
for (let item of items) {
if (typeof item === 'string') {
const children = item.trim().split(/\s*,\s*/g)
if (children.length > 1) {
toDiagnosticCodeList(children, into)
continue
}
item = children[0]
}
if (!item) continue
const code = toDiagnosticCode(item)
if (code && !into.includes(code)) into.push(code)
}
return into
}
export class ConfigSet {
readonly logger: Logger
readonly compilerModule: TTypeScript
readonly isolatedModules: boolean
readonly cwd: string
tsCacheDir: string | undefined
parsedTsConfig!: ParsedCommandLine | Record<string, any>
customTransformers: CustomTransformers = Object.create(null)
readonly rootDir: string
/**
* @internal
*/
private _jestCfg!: Config.ProjectConfig
/**
* @internal
*/
private _babelConfig: BabelConfig | undefined
/**
* @internal
*/
private _babelJestTransformers: BabelJestTransformer | undefined
/**
* @internal
*/
private _diagnostics!: TsJestDiagnosticsCfg
/**
* @internal
*/
private _stringifyContentRegExp: RegExp | undefined
protected _overriddenCompilerOptions: Partial<CompilerOptions> = {
// we handle sourcemaps this way and not another
sourceMap: true,
inlineSourceMap: false,
inlineSources: true,
// we don't want to create declaration files
declaration: false,
noEmit: false, // set to true will make compiler API not emit any compiled results.
// else istanbul related will be dropped
removeComments: false,
// to clear out else it's buggy
out: undefined,
outFile: undefined,
composite: undefined, // see https://github.com/TypeStrong/ts-node/pull/657/files
declarationDir: undefined,
declarationMap: undefined,
emitDeclarationOnly: undefined,
sourceRoot: undefined,
tsBuildInfoFile: undefined,
}
constructor(
/**
* @internal
*/
private readonly jestConfig: Config.ProjectConfig,
/**
* Mainly for testing logging
*
* @internal
*/
private readonly parentLogger?: Logger,
) {
this.logger = this.parentLogger
? this.parentLogger.child({ [LogContexts.namespace]: 'config' })
: rootLogger.child({ namespace: 'config' })
this.cwd = normalize(this.jestConfig.cwd ?? process.cwd())
this.rootDir = normalize(this.jestConfig.rootDir ?? this.cwd)
const tsJestCfg = this.jestConfig.globals && this.jestConfig.globals['ts-jest']
const options: TsJestGlobalOptions = tsJestCfg ?? Object.create(null)
// compiler module
this.compilerModule = importer.typescript(ImportReasons.TsJest, options.compiler ?? 'typescript')
// isolatedModules
this.isolatedModules = options.isolatedModules ?? false
this.logger.debug({ compilerModule: this.compilerModule }, 'normalized compiler module config via ts-jest option')
this._backportJestCfg()
this._setupTsJestCfg(options)
this._resolveTsCacheDir()
}
/**
* @internal
*/
private _backportJestCfg(): void {
const config = backportJestConfig(this.logger, this.jestConfig)
this.logger.debug({ jestConfig: config }, 'normalized jest config')
this._jestCfg = config
}
/**
* @internal
*/
private _setupTsJestCfg(options: TsJestGlobalOptions): void {
if (options.packageJson) {
this.logger.warn(Deprecations.PackageJson)
}
// babel config (for babel-jest) default is undefined so we don't need to have fallback like tsConfig
if (!options.babelConfig) {
this.logger.debug('babel is disabled')
} else {
const baseBabelCfg = { cwd: this.cwd }
if (typeof options.babelConfig === 'string') {
const babelCfgPath = this.resolvePath(options.babelConfig)
if (extname(options.babelConfig) === '.js') {
this._babelConfig = {
...baseBabelCfg,
...require(babelCfgPath),
}
} else {
this._babelConfig = {
...baseBabelCfg,
...json5.parse(readFileSync(babelCfgPath, 'utf-8')),
}
}
} else if (typeof options.babelConfig === 'object') {
this._babelConfig = {
...baseBabelCfg,
...options.babelConfig,
}
} else {
this._babelConfig = baseBabelCfg
}
this.logger.debug({ babelConfig: this._babelConfig }, 'normalized babel config via ts-jest option')
}
if (!this._babelConfig) {
this._overriddenCompilerOptions.module = this.compilerModule.ModuleKind.CommonJS
} else {
this._babelJestTransformers = importer
.babelJest(ImportReasons.BabelJest)
.createTransformer(this._babelConfig) as BabelJestTransformer
this.logger.debug('created babel-jest transformer')
}
// diagnostics
const diagnosticsOpt = options.diagnostics ?? true
const ignoreList: (string | number)[] = [...IGNORE_DIAGNOSTIC_CODES]
if (typeof diagnosticsOpt === 'object') {
const { ignoreCodes } = diagnosticsOpt
if (ignoreCodes) {
Array.isArray(ignoreCodes) ? ignoreList.push(...ignoreCodes) : ignoreList.push(ignoreCodes)
}
this._diagnostics = {
pretty: diagnosticsOpt.pretty ?? true,
ignoreCodes: toDiagnosticCodeList(ignoreList),
pathRegex: normalizeRegex(diagnosticsOpt.pathRegex),
throws: !diagnosticsOpt.warnOnly,
}
} else {
this._diagnostics = {
ignoreCodes: diagnosticsOpt ? toDiagnosticCodeList(ignoreList) : [],
pretty: true,
throws: diagnosticsOpt,
}
}
this.logger.debug({ diagnostics: this._diagnostics }, 'normalized diagnostics config via ts-jest option')
// tsconfig
if (options.tsConfig) {
this.logger.warn(Deprecations.TsConfig)
}
const tsconfigOpt = options.tsConfig ?? options.tsconfig
const configFilePath = typeof tsconfigOpt === 'string' ? this.resolvePath(tsconfigOpt) : undefined
this.parsedTsConfig = this._resolveTsConfig(
typeof tsconfigOpt === 'object' ? tsconfigOpt : undefined,
configFilePath,
)
// throw errors if any matching wanted diagnostics
this.raiseDiagnostics(this.parsedTsConfig.errors, configFilePath)
this.logger.debug({ tsconfig: this.parsedTsConfig }, 'normalized typescript config via ts-jest option')
// transformers
const { astTransformers } = options
this.customTransformers = {
before: [hoisting(this)],
}
if (astTransformers) {
if (Array.isArray(astTransformers)) {
this.logger.warn(Deprecations.AstTransformerArrayConfig)
this.customTransformers = {
before: [
...this.customTransformers.before,
...astTransformers.map((transformer) => {
const transformerPath = this.resolvePath(transformer, { nodeResolve: true })
return require(transformerPath).factory(this)
}),
],
}
} else {
const resolveTransformers = (transformers: (string | AstTransformer)[]) =>
transformers.map((transformer) => {
let transformerPath: string
if (typeof transformer === 'string') {
transformerPath = this.resolvePath(transformer, { nodeResolve: true })
return require(transformerPath).factory(this)
} else {
transformerPath = this.resolvePath(transformer.path, { nodeResolve: true })
return require(transformerPath).factory(this, transformer.options)
}
})
if (astTransformers.before) {
this.customTransformers = {
before: [...this.customTransformers.before, ...resolveTransformers(astTransformers.before)],
}
}
if (astTransformers.after) {
this.customTransformers = {
...this.customTransformers,
after: resolveTransformers(astTransformers.after),
}
}
if (astTransformers.afterDeclarations) {
this.customTransformers = {
...this.customTransformers,
afterDeclarations: resolveTransformers(astTransformers.afterDeclarations),
}
}
}
}
this.logger.debug(
{ customTransformers: this.customTransformers },
'normalized custom AST transformers via ts-jest option',
)
// stringifyContentPathRegex
if (options.stringifyContentPathRegex) {
this._stringifyContentRegExp =
typeof options.stringifyContentPathRegex === 'string'
? new RegExp(normalizeRegex(options.stringifyContentPathRegex)!) // eslint-disable-line @typescript-eslint/no-non-null-assertion
: options.stringifyContentPathRegex
this.logger.debug(
{ stringifyContentPathRegex: this._stringifyContentRegExp },
'normalized stringifyContentPathRegex config via ts-jest option',
)
}
}
/**
* @internal
*/
private _resolveTsCacheDir(): void {
if (!this._jestCfg.cache) {
this.logger.debug('file caching disabled')
return undefined
}
const cacheSuffix = sha1(
stringify({
version: this.compilerModule.version,
digest: this.tsJestDigest,
compilerModule: this.compilerModule,
compilerOptions: this.parsedTsConfig.options,
isolatedModules: this.isolatedModules,
diagnostics: this._diagnostics,
}),
)
const res = join(this._jestCfg.cacheDirectory, 'ts-jest', cacheSuffix.substr(0, 2), cacheSuffix.substr(2))
this.logger.debug({ cacheDirectory: res }, 'will use file caching')
this.tsCacheDir = res
}
/**
* Load TypeScript configuration. Returns the parsed TypeScript config and
* any `tsConfig` options specified in ts-jest tsConfig
*/
protected _resolveTsConfig(compilerOptions?: CompilerOptions, resolvedConfigFile?: string): Record<string, any>
// eslint-disable-next-line no-dupe-class-members
protected _resolveTsConfig(compilerOptions?: CompilerOptions, resolvedConfigFile?: string): ParsedCommandLine {
let config = { compilerOptions: Object.create(null) }
let basePath = normalizeSlashes(this.rootDir)
const ts = this.compilerModule
// Read project configuration when available.
const configFileName: string | undefined = resolvedConfigFile
? normalizeSlashes(resolvedConfigFile)
: ts.findConfigFile(normalizeSlashes(this.rootDir), ts.sys.fileExists)
if (configFileName) {
this.logger.debug({ tsConfigFileName: configFileName }, 'readTsConfig(): reading', configFileName)
const result = ts.readConfigFile(configFileName, ts.sys.readFile)
// Return diagnostics.
if (result.error) {
return { errors: [result.error], fileNames: [], options: {} }
}
config = result.config
basePath = normalizeSlashes(dirname(configFileName))
}
// Override default configuration options `ts-jest` requires.
config.compilerOptions = {
...config.compilerOptions,
...compilerOptions,
}
// parse json, merge config extending others, ...
const result = ts.parseJsonConfigFileContent(config, ts.sys, basePath, undefined, configFileName)
const { _overriddenCompilerOptions: forcedOptions } = this
const finalOptions = result.options
// Target ES5 output by default (instead of ES3).
if (finalOptions.target === undefined) {
finalOptions.target = ts.ScriptTarget.ES5
}
// check the module interoperability
const target = finalOptions.target
// compute the default if not set
const defaultModule = [ts.ScriptTarget.ES3, ts.ScriptTarget.ES5].includes(target)
? ts.ModuleKind.CommonJS
: ts.ModuleKind.ESNext
const moduleValue = finalOptions.module == null ? defaultModule : finalOptions.module
if (
'module' in forcedOptions &&
moduleValue !== forcedOptions.module &&
!(finalOptions.esModuleInterop || finalOptions.allowSyntheticDefaultImports)
) {
result.errors.push({
code: DiagnosticCodes.ConfigModuleOption,
messageText: Errors.ConfigNoModuleInterop,
category: ts.DiagnosticCategory.Message,
file: undefined,
start: undefined,
length: undefined,
})
// at least enable synthetic default imports (except if it's set in the input config)
if (!('allowSyntheticDefaultImports' in config.compilerOptions)) {
finalOptions.allowSyntheticDefaultImports = true
}
}
// Make sure when allowJs is enabled, outDir is required to have when using allowJs: true
if (finalOptions.allowJs && !finalOptions.outDir) {
finalOptions.outDir = TS_JEST_OUT_DIR
}
// ensure undefined are removed and other values are overridden
for (const key of Object.keys(forcedOptions)) {
const val = forcedOptions[key]
if (val === undefined) {
delete finalOptions[key]
} else {
finalOptions[key] = val
}
}
/**
* See https://github.com/microsoft/TypeScript/wiki/Node-Target-Mapping
* Every time this page is updated, we also need to update here. Here we only show warning message for Node LTS versions
*/
const nodeJsVer = process.version
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const compilationTarget = result.options.target!
/* istanbul ignore next (cover by e2e) */
if (
!this._babelConfig &&
((nodeJsVer.startsWith('v10') && compilationTarget > ScriptTarget.ES2018) ||
(nodeJsVer.startsWith('v12') && compilationTarget > ScriptTarget.ES2019))
) {
const message = interpolate(Errors.MismatchNodeTargetMapping, {
nodeJsVer: process.version,
compilationTarget: config.compilerOptions.target ?? TARGET_TO_VERSION_MAPPING[compilationTarget],
})
this.logger.warn(message)
}
return result
}
/**
* @internal
*/
@Memoize()
get tsCompiler(): TsCompiler {
return createCompilerInstance(this)
}
/**
* @internal
*/
get babelConfig(): BabelConfig | undefined {
return this._babelConfig
}
/**
* @internal
*/
get babelJestTransformer(): BabelJestTransformer | undefined {
return this._babelJestTransformers
}
/**
* Use by e2e, don't mark as internal
*/
@Memoize()
// eslint-disable-next-line class-methods-use-this
get tsJestDigest(): string {
return MY_DIGEST
}
/**
* @internal
*/
@Memoize()
get hooks(): TsJestHooksMap {
let hooksFile = process.env.TS_JEST_HOOKS
if (hooksFile) {
hooksFile = resolve(this.cwd, hooksFile)
return importer.tryTheseOr(hooksFile, {})
}
return {}
}
@Memoize()
get isTestFile(): (fileName: string) => boolean {
const matchablePatterns = [...this._jestCfg.testMatch, ...this._jestCfg.testRegex].filter(
(pattern) =>
/**
* jest config testRegex doesn't always deliver the correct RegExp object
* See https://github.com/facebook/jest/issues/9778
*/
pattern instanceof RegExp || typeof pattern === 'string',
)
if (!matchablePatterns.length) {
matchablePatterns.push(...DEFAULT_JEST_TEST_MATCH)
}
const stringPatterns = matchablePatterns.filter((pattern: any) => typeof pattern === 'string') as string[]
const isMatch = globsToMatcher(stringPatterns)
return (fileName: string) =>
matchablePatterns.some((pattern) => (typeof pattern === 'string' ? isMatch(fileName) : pattern.test(fileName)))
}
shouldStringifyContent(filePath: string): boolean {
return this._stringifyContentRegExp ? this._stringifyContentRegExp.test(filePath) : false
}
raiseDiagnostics(diagnostics: Diagnostic[], filePath?: string, logger?: Logger): void {
const { ignoreCodes } = this._diagnostics
const { DiagnosticCategory } = this.compilerModule
const filteredDiagnostics =
filePath && !this.shouldReportDiagnostics(filePath)
? []
: diagnostics.filter((diagnostic) => {
if (diagnostic.file?.fileName && !this.shouldReportDiagnostics(diagnostic.file.fileName)) {
return false
}
return !ignoreCodes.includes(diagnostic.code)
})
if (!filteredDiagnostics.length) return
const error = this._createTsError(filteredDiagnostics)
// only throw if `warnOnly` and it is a warning or error
const importantCategories = [DiagnosticCategory.Warning, DiagnosticCategory.Error]
if (this._diagnostics.throws && filteredDiagnostics.some((d) => importantCategories.includes(d.category))) {
throw error
}
/* istanbul ignore next (already covered) */
logger ? logger.warn({ error }, error.message) : this.logger.warn({ error }, error.message)
}
shouldReportDiagnostics(filePath: string): boolean {
const { pathRegex } = this._diagnostics
if (pathRegex) {
const regex = new RegExp(pathRegex)
return regex.test(filePath)
} else {
return true
}
}
/**
* @internal
*/
private _createTsError(diagnostics: readonly Diagnostic[]): TSError {
const formatDiagnostics = this._diagnostics.pretty
? this.compilerModule.formatDiagnosticsWithColorAndContext
: this.compilerModule.formatDiagnostics
/* istanbul ignore next (not possible to cover) */
const diagnosticHost: FormatDiagnosticsHost = {
getNewLine: () => '\n',
getCurrentDirectory: () => this.cwd,
getCanonicalFileName: (path: string) => path,
}
const diagnosticText = formatDiagnostics(diagnostics, diagnosticHost)
const diagnosticCodes = diagnostics.map((x) => x.code)
return new TSError(diagnosticText, diagnosticCodes)
}
resolvePath(
inputPath: string,
{ throwIfMissing = true, nodeResolve = false }: { throwIfMissing?: boolean; nodeResolve?: boolean } = {},
): string {
let path: string = inputPath
let nodeResolved = false
if (path.startsWith('<rootDir>')) {
path = resolve(join(this.rootDir, path.substr(9)))
} else if (!isAbsolute(path)) {
if (!path.startsWith('.') && nodeResolve) {
try {
path = require.resolve(path)
nodeResolved = true
} catch (_) {}
}
if (!nodeResolved) {
path = resolve(this.cwd, path)
}
}
if (!nodeResolved && nodeResolve) {
try {
path = require.resolve(path)
nodeResolved = true
} catch (_) {}
}
if (throwIfMissing && !existsSync(path)) {
throw new Error(interpolate(Errors.FileNotFound, { inputPath, resolvedPath: path }))
}
this.logger.debug({ fromPath: inputPath, toPath: path }, 'resolved path from', inputPath, 'to', path)
return path
}
}