ts-jest 26.3.0 → 26.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/.ts-jest-digest +1 -1
  2. package/CHANGELOG.md +52 -0
  3. package/README.md +0 -1
  4. package/dist/cli/config/init.d.ts +0 -5
  5. package/dist/cli/config/init.js +3 -18
  6. package/dist/cli/config/migrate.js +11 -41
  7. package/dist/cli/help.js +1 -7
  8. package/dist/cli/helpers/presets.js +5 -11
  9. package/dist/cli/index.js +11 -12
  10. package/dist/compiler/instance.d.ts +2 -1
  11. package/dist/compiler/instance.js +8 -27
  12. package/dist/compiler/language-service.js +11 -62
  13. package/dist/compiler/transpiler.js +5 -10
  14. package/dist/config/config-set.d.ts +19 -26
  15. package/dist/config/config-set.js +305 -727
  16. package/dist/config/paths-to-module-name-mapper.d.ts +1 -1
  17. package/dist/config/paths-to-module-name-mapper.js +13 -12
  18. package/dist/constants.d.ts +2 -1
  19. package/dist/constants.js +1 -22
  20. package/dist/index.d.ts +4 -120
  21. package/dist/index.js +9 -87
  22. package/dist/{config → presets}/create-jest-preset.d.ts +2 -1
  23. package/dist/{config → presets}/create-jest-preset.js +1 -1
  24. package/dist/transformers/hoist-jest.js +48 -73
  25. package/dist/transformers/index.js +20 -4
  26. package/dist/transformers/path-mapping.d.ts +3 -0
  27. package/dist/transformers/path-mapping.js +121 -0
  28. package/dist/ts-jest-transformer.d.ts +5 -22
  29. package/dist/ts-jest-transformer.js +54 -103
  30. package/dist/types.d.ts +14 -90
  31. package/dist/{util → utils}/backports.d.ts +0 -0
  32. package/dist/{util → utils}/backports.js +4 -11
  33. package/dist/{util → utils}/get-package-version.d.ts +0 -0
  34. package/dist/{util → utils}/get-package-version.js +0 -3
  35. package/dist/{util → utils}/importer.d.ts +0 -0
  36. package/dist/{util → utils}/importer.js +4 -29
  37. package/dist/utils/json.d.ts +2 -0
  38. package/dist/{util → utils}/json.js +0 -14
  39. package/dist/utils/jsonable-value.d.ts +10 -0
  40. package/dist/{util → utils}/jsonable-value.js +1 -4
  41. package/dist/{util → utils}/logger.d.ts +0 -0
  42. package/dist/{util → utils}/logger.js +0 -4
  43. package/dist/{util → utils}/memoize.d.ts +0 -0
  44. package/dist/{util → utils}/memoize.js +0 -8
  45. package/dist/{util → utils}/messages.d.ts +0 -0
  46. package/dist/{util → utils}/messages.js +0 -4
  47. package/dist/{util → utils}/normalize-slashes.d.ts +0 -0
  48. package/dist/{util → utils}/normalize-slashes.js +0 -3
  49. package/dist/{util → utils}/sha1.d.ts +0 -0
  50. package/dist/{util → utils}/sha1.js +0 -10
  51. package/dist/{util → utils}/testing.d.ts +1 -1
  52. package/dist/{util → utils}/testing.js +0 -0
  53. package/dist/{util → utils}/ts-error.d.ts +0 -0
  54. package/dist/{util → utils}/ts-error.js +2 -12
  55. package/dist/{util → utils}/version-checkers.d.ts +0 -0
  56. package/dist/{util → utils}/version-checkers.js +5 -8
  57. package/jest-preset.js +1 -1
  58. package/package.json +8 -7
  59. package/presets/index.js +4 -4
  60. package/utils/index.d.ts +3 -1
  61. package/utils/index.js +15 -1
  62. package/dist/util/index.d.ts +0 -3
  63. package/dist/util/index.js +0 -9
  64. package/dist/util/json.d.ts +0 -1
  65. package/dist/util/jsonable-value.d.ts +0 -1
  66. package/presets/create.js +0 -1
  67. package/presets/index.d.ts +0 -5
@@ -1,15 +1,4 @@
1
1
  "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
2
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
3
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
4
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -85,21 +74,16 @@ var path_1 = require("path");
85
74
  var memoize = require("lodash.memoize");
86
75
  var mkdirp = require("mkdirp");
87
76
  var constants_1 = require("../constants");
88
- var messages_1 = require("../util/messages");
89
- var json_1 = require("../util/json");
90
- var sha1_1 = require("../util/sha1");
77
+ var messages_1 = require("../utils/messages");
78
+ var json_1 = require("../utils/json");
79
+ var sha1_1 = require("../utils/sha1");
91
80
  function doTypeChecking(configs, diagnosedFiles, fileName, service, logger) {
92
- if (configs.shouldReportDiagnostic(fileName)) {
93
- // Get the relevant diagnostics - this is 3x faster than `getPreEmitDiagnostics`.
81
+ if (configs.shouldReportDiagnostics(fileName)) {
94
82
  var diagnostics = service.getSemanticDiagnostics(fileName).concat(service.getSyntacticDiagnostics(fileName));
95
83
  diagnosedFiles.push(fileName);
96
- // will raise or just warn diagnostics depending on config
97
84
  configs.raiseDiagnostics(diagnostics, fileName, logger);
98
85
  }
99
86
  }
100
- /**
101
- * @internal
102
- */
103
87
  exports.initializeLanguageServiceInstance = function (configs, logger) {
104
88
  var _a;
105
89
  logger.debug('initializeLanguageServiceInstance(): create typescript compiler');
@@ -120,28 +104,25 @@ exports.initializeLanguageServiceInstance = function (configs, logger) {
120
104
  };
121
105
  var tsResolvedModulesCachePath;
122
106
  if (cacheDir) {
123
- // Make sure the cache directory exists before continuing.
124
107
  mkdirp.sync(cacheDir);
125
108
  tsResolvedModulesCachePath = path_1.join(cacheDir, sha1_1.sha1('ts-jest-resolved-modules', '\x00'));
126
109
  try {
127
- /* istanbul ignore next (already covered with unit test) */
128
110
  var cachedTSResolvedModules = fs_1.readFileSync(tsResolvedModulesCachePath, 'utf-8');
129
111
  memoryCache.resolvedModules = new Map(json_1.parse(cachedTSResolvedModules));
130
112
  }
131
113
  catch (e) { }
132
114
  }
133
- // Initialize memory cache for typescript compiler
134
- configs.parsedTsConfig.fileNames.forEach(function (fileName) {
115
+ configs.parsedTsConfig.fileNames
116
+ .filter(function (fileName) { return fileName.endsWith('.d.ts'); })
117
+ .forEach(function (fileName) {
135
118
  memoryCache.files.set(fileName, {
136
119
  version: 0,
137
120
  });
138
121
  });
139
122
  function isFileInCache(fileName) {
140
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
141
123
  return memoryCache.files.has(fileName) && memoryCache.files.get(fileName).version !== 0;
142
124
  }
143
125
  var cacheReadFile = logger.wrap(serviceHostTraceCtx, 'readFile', memoize(ts.sys.readFile));
144
- /* istanbul ignore next */
145
126
  var moduleResolutionHost = {
146
127
  fileExists: memoize(ts.sys.fileExists),
147
128
  readFile: cacheReadFile,
@@ -169,8 +150,6 @@ exports.initializeLanguageServiceInstance = function (configs, logger) {
169
150
  });
170
151
  }
171
152
  var projectVersion = 1;
172
- // Set the file contents into cache.
173
- /* istanbul ignore next (cover by e2e) */
174
153
  var updateMemoryCache = function (contents, fileName) {
175
154
  logger.debug({ fileName: fileName }, 'updateMemoryCache(): update memory cache for language service');
176
155
  var shouldIncrementProjectVersion = false;
@@ -183,22 +162,15 @@ exports.initializeLanguageServiceInstance = function (configs, logger) {
183
162
  shouldIncrementProjectVersion = true;
184
163
  }
185
164
  else {
186
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
187
165
  var previousContents = memoryCache.files.get(fileName).text;
188
- // Avoid incrementing cache when nothing has changed.
189
166
  if (previousContents !== contents) {
190
167
  memoryCache.files.set(fileName, {
191
168
  text: contents,
192
169
  version: memoryCache.files.get(fileName).version + 1,
193
170
  });
194
- // Only bump project version when file is modified in cache, not when discovered for the first time
195
171
  if (hit)
196
172
  shouldIncrementProjectVersion = true;
197
173
  }
198
- /**
199
- * When a file is from node_modules or referenced to a referenced project and jest wants to transform it, we need
200
- * to make sure that the Program is updated with this information
201
- */
202
174
  if (!fileNames.includes(fileName)) {
203
175
  shouldIncrementProjectVersion = true;
204
176
  }
@@ -213,11 +185,6 @@ exports.initializeLanguageServiceInstance = function (configs, logger) {
213
185
  var _a;
214
186
  var normalizedFileName = path_1.normalize(fileName);
215
187
  var version = (_a = memoryCache.files.get(normalizedFileName)) === null || _a === void 0 ? void 0 : _a.version;
216
- // We need to return `undefined` and not a string here because TypeScript will use
217
- // `getScriptVersion` and compare against their own version - which can be `undefined`.
218
- // If we don't return `undefined` it results in `undefined === "undefined"` and run
219
- // `createProgram` again (which is very slow). Using a `string` assertion here to avoid
220
- // TypeScript errors from the function signature (expects `(x: string) => string`).
221
188
  return version === undefined ? undefined : String(version);
222
189
  },
223
190
  getScriptSnapshot: function (fileName) {
@@ -225,7 +192,6 @@ exports.initializeLanguageServiceInstance = function (configs, logger) {
225
192
  var normalizedFileName = path_1.normalize(fileName);
226
193
  var hit = isFileInCache(normalizedFileName);
227
194
  logger.trace({ normalizedFileName: normalizedFileName, cacheHit: hit }, 'getScriptSnapshot():', 'cache', hit ? 'hit' : 'miss');
228
- // Read contents from TypeScript memory cache.
229
195
  if (!hit) {
230
196
  memoryCache.files.set(normalizedFileName, {
231
197
  text: cacheReadFile(normalizedFileName),
@@ -247,7 +213,7 @@ exports.initializeLanguageServiceInstance = function (configs, logger) {
247
213
  getCurrentDirectory: function () { return cwd; },
248
214
  getCompilationSettings: function () { return options; },
249
215
  getDefaultLibFileName: function () { return ts.getDefaultLibFilePath(options); },
250
- getCustomTransformers: function () { return configs.tsCustomTransformers; },
216
+ getCustomTransformers: function () { return configs.customTransformers; },
251
217
  resolveModuleNames: resolveModuleNames,
252
218
  };
253
219
  logger.debug('initializeLanguageServiceInstance(): creating language service');
@@ -257,47 +223,33 @@ exports.initializeLanguageServiceInstance = function (configs, logger) {
257
223
  var e_1, _a;
258
224
  var _b;
259
225
  logger.debug({ fileName: fileName }, 'compileFn(): compiling using language service');
260
- // Must set memory cache before attempting to compile
261
226
  updateMemoryCache(code, fileName);
262
227
  var output = service.getEmitOutput(fileName);
263
- /* istanbul ignore next */
264
228
  if (tsResolvedModulesCachePath) {
265
- // Cache resolved modules to disk so next run can reuse it
266
229
  void (function () { return __awaiter(void 0, void 0, void 0, function () {
267
230
  return __generator(this, function (_a) {
268
231
  switch (_a.label) {
269
- case 0:
270
- // eslint-disable-next-line @typescript-eslint/await-thenable
271
- return [4 /*yield*/, fs_1.writeFile(tsResolvedModulesCachePath, json_1.stringify(__spread(memoryCache.resolvedModules)), function () { })];
232
+ case 0: return [4, fs_1.writeFile(tsResolvedModulesCachePath, json_1.stringify(__spread(memoryCache.resolvedModules)), function () { })];
272
233
  case 1:
273
- // eslint-disable-next-line @typescript-eslint/await-thenable
274
234
  _a.sent();
275
- return [2 /*return*/];
235
+ return [2];
276
236
  }
277
237
  });
278
238
  }); })();
279
239
  }
280
- /**
281
- * There might be a chance that test files are type checked even before jest executes them, we don't need to do
282
- * type check again
283
- */
284
240
  if (!diagnosedFiles.includes(fileName)) {
285
241
  logger.debug({ fileName: fileName }, 'compileFn(): computing diagnostics using language service');
286
242
  doTypeChecking(configs, diagnosedFiles, fileName, service, logger);
287
243
  }
288
- /* istanbul ignore next (already covered with unit tests) */
289
244
  if (!configs.isTestFile(fileName)) {
290
245
  try {
291
246
  for (var _c = __values(memoryCache.resolvedModules.entries()), _d = _c.next(); !_d.done; _d = _c.next()) {
292
247
  var _e = __read(_d.value, 2), testFileName = _e[0], resolvedModules = _e[1];
293
- // Only do type checking for test files which haven't been type checked before as well as the file must exist
294
248
  if (resolvedModules.includes(fileName) &&
295
249
  !diagnosedFiles.includes(testFileName) &&
296
250
  fs_1.existsSync(testFileName)) {
297
251
  var testFileContent = (_b = memoryCache.files.get(testFileName)) === null || _b === void 0 ? void 0 : _b.text;
298
252
  if (!testFileContent) {
299
- // Must set memory cache before attempting to get diagnostics
300
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
301
253
  updateMemoryCache(cacheReadFile(testFileName), testFileName);
302
254
  }
303
255
  logger.debug({ testFileName: testFileName }, 'compileFn(): computing diagnostics using language service for test file which uses the module');
@@ -313,17 +265,14 @@ exports.initializeLanguageServiceInstance = function (configs, logger) {
313
265
  finally { if (e_1) throw e_1.error; }
314
266
  }
315
267
  }
316
- /* istanbul ignore next (this should never happen but is kept for security) */
317
268
  if (output.emitSkipped) {
318
269
  throw new TypeError(path_1.relative(cwd, fileName) + ": Emit skipped for language service");
319
270
  }
320
- // Throw an error when requiring `.d.ts` files.
321
271
  if (!output.outputFiles.length) {
322
- throw new TypeError(messages_1.interpolate("Unable to require `.d.ts` file for file: {{file}}.\nThis is usually the result of a faulty configuration or import. Make sure there is a `.js`, `.json` or another executable extension available alongside `{{file}}`." /* UnableToRequireDefinitionFile */, {
272
+ throw new TypeError(messages_1.interpolate("Unable to require `.d.ts` file for file: {{file}}.\nThis is usually the result of a faulty configuration or import. Make sure there is a `.js`, `.json` or another executable extension available alongside `{{file}}`.", {
323
273
  file: path_1.basename(fileName),
324
274
  }));
325
275
  }
326
- memoryCache.files.set(fileName, __assign(__assign({}, memoryCache.files.get(fileName)), { output: output.outputFiles[1].text }));
327
276
  return [output.outputFiles[1].text, output.outputFiles[0].text];
328
277
  },
329
278
  program: service.getProgram(),
@@ -1,29 +1,24 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.initializeTranspilerInstance = void 0;
4
- /**
5
- * @internal
6
- */
7
4
  exports.initializeTranspilerInstance = function (configs, logger) {
8
5
  logger.debug('initializeTranspilerInstance(): create typescript compiler');
9
- var _a = configs.parsedTsConfig, options = _a.options, fileNames = _a.fileNames;
6
+ var options = configs.parsedTsConfig.options;
10
7
  var ts = configs.compilerModule;
11
- var program = ts.createProgram(fileNames, options);
12
8
  return {
13
9
  compileFn: function (code, fileName) {
14
10
  logger.debug({ fileName: fileName }, 'compileFn(): compiling as isolated module');
15
11
  var result = ts.transpileModule(code, {
16
12
  fileName: fileName,
17
- transformers: configs.tsCustomTransformers,
13
+ transformers: configs.customTransformers,
18
14
  compilerOptions: options,
19
- reportDiagnostics: configs.shouldReportDiagnostic(fileName),
15
+ reportDiagnostics: configs.shouldReportDiagnostics(fileName),
20
16
  });
21
- if (result.diagnostics && configs.shouldReportDiagnostic(fileName)) {
17
+ if (result.diagnostics && configs.shouldReportDiagnostics(fileName)) {
22
18
  configs.raiseDiagnostics(result.diagnostics, fileName, logger);
23
19
  }
24
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
25
20
  return [result.outputText, result.sourceMapText];
26
21
  },
27
- program: program,
22
+ program: undefined,
28
23
  };
29
24
  };
@@ -1,31 +1,24 @@
1
- /**
2
- * This is the core of settings and so ts-jest.
3
- * Since configuration are used to create a good cache key, everything
4
- * depending on it is here. Fast jest relies on correct cache keys
5
- * depending on all settings that could affect the generated output.
6
- *
7
- * The big issue is that jest calls first `getCacheKey()` with stringified
8
- * version of the `jest.ProjectConfig`, and then later it calls `process()`
9
- * with the complete, object version of it.
10
- */
11
1
  import type { Config } from '@jest/types';
12
2
  import { Logger } from 'bs-logger';
13
- import type { TsCompiler, TsJestGlobalOptions, TTypeScript } from '../types';
3
+ import { CustomTransformers, Diagnostic, ParsedCommandLine } from 'typescript';
4
+ import type { TTypeScript } from '../types';
14
5
  export declare class ConfigSet {
15
- readonly parentOptions?: TsJestGlobalOptions | undefined;
16
- /**
17
- * Use by e2e, don't mark as internal
18
- */
19
- get versions(): Record<string, string>;
20
- /**
21
- * This API can be used by custom transformers
22
- */
23
- get compilerModule(): TTypeScript;
24
- get tsCompiler(): TsCompiler;
25
- /**
26
- * Use by e2e, don't mark as internal
27
- */
28
- get tsJestDigest(): string;
29
6
  readonly logger: Logger;
30
- constructor(jestConfig: Config.ProjectConfig, parentOptions?: TsJestGlobalOptions | undefined, parentLogger?: Logger);
7
+ readonly compilerModule: TTypeScript;
8
+ readonly isolatedModules: boolean;
9
+ readonly cwd: string;
10
+ tsCacheDir: string | undefined;
11
+ parsedTsConfig: ParsedCommandLine;
12
+ customTransformers: CustomTransformers;
13
+ readonly rootDir: string;
14
+ constructor(jestConfig: Config.ProjectConfig, parentLogger?: Logger | undefined);
15
+ get tsJestDigest(): string;
16
+ get isTestFile(): (fileName: string) => boolean;
17
+ shouldStringifyContent(filePath: string): boolean;
18
+ raiseDiagnostics(diagnostics: Diagnostic[], filePath?: string, logger?: Logger): void;
19
+ shouldReportDiagnostics(filePath: string): boolean;
20
+ resolvePath(inputPath: string, { throwIfMissing, nodeResolve }?: {
21
+ throwIfMissing?: boolean;
22
+ nodeResolve?: boolean;
23
+ }): string;
31
24
  }