ts-jest 29.0.1 → 29.0.3

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 (38) hide show
  1. package/.ts-jest-digest +1 -1
  2. package/CHANGELOG.md +34 -0
  3. package/dist/cli/config/init.d.ts +5 -0
  4. package/dist/cli/config/init.js +61 -20
  5. package/dist/cli/config/migrate.js +88 -15
  6. package/dist/cli/help.js +7 -1
  7. package/dist/cli/helpers/presets.js +12 -5
  8. package/dist/cli/index.js +9 -5
  9. package/dist/config/paths-to-module-name-mapper.d.ts +3 -2
  10. package/dist/config/paths-to-module-name-mapper.js +21 -11
  11. package/dist/constants.js +5 -0
  12. package/dist/legacy/compiler/compiler-utils.d.ts +6 -0
  13. package/dist/legacy/compiler/compiler-utils.js +10 -0
  14. package/dist/legacy/compiler/ts-compiler.d.ts +6 -0
  15. package/dist/legacy/compiler/ts-compiler.js +76 -7
  16. package/dist/legacy/compiler/ts-jest-compiler.js +2 -1
  17. package/dist/legacy/config/config-set.d.ts +7 -0
  18. package/dist/legacy/config/config-set.js +91 -12
  19. package/dist/legacy/ts-jest-transformer.d.ts +13 -0
  20. package/dist/legacy/ts-jest-transformer.js +61 -12
  21. package/dist/presets/create-jest-preset.js +3 -2
  22. package/dist/raw-compiler-options.d.ts +297 -0
  23. package/dist/transformers/hoist-jest.d.ts +4 -0
  24. package/dist/transformers/hoist-jest.js +24 -0
  25. package/dist/types.d.ts +103 -8
  26. package/dist/utils/backports.js +13 -4
  27. package/dist/utils/get-package-version.js +3 -0
  28. package/dist/utils/importer.js +31 -4
  29. package/dist/utils/json.js +9 -0
  30. package/dist/utils/jsonable-value.js +2 -1
  31. package/dist/utils/logger.js +1 -0
  32. package/dist/utils/memoize.js +20 -1
  33. package/dist/utils/messages.js +5 -0
  34. package/dist/utils/normalize-slashes.js +3 -0
  35. package/dist/utils/sha1.js +10 -0
  36. package/dist/utils/ts-error.js +12 -2
  37. package/dist/utils/version-checkers.js +9 -5
  38. package/package.json +5 -5
package/.ts-jest-digest CHANGED
@@ -1 +1 @@
1
- 039bf2bc4c11e2e3341df450e4af7ab945a9404d
1
+ 7378fcb54a209ca78cc5680b6d7f7243b480d5bb
package/CHANGELOG.md CHANGED
@@ -1,3 +1,37 @@
1
+ ## [29.0.3](https://github.com/kulshekhar/ts-jest/compare/v29.0.2...v29.0.3) (2022-09-28)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * merge config from `globals` with transformer config correctly ([#3842](https://github.com/kulshekhar/ts-jest/issues/3842)) ([9c9fd60](https://github.com/kulshekhar/ts-jest/commit/9c9fd6097aea36a6e8b06b0e8841df22896f9121)), closes [#3841](https://github.com/kulshekhar/ts-jest/issues/3841)
7
+ * **presets:** allow merging transform config when using presets ([#3833](https://github.com/kulshekhar/ts-jest/issues/3833)) ([afc6a94](https://github.com/kulshekhar/ts-jest/commit/afc6a948b17c2dc22be51b1a9475a0f6ecbbc372))
8
+
9
+
10
+ ### Features
11
+
12
+ * add `useESM` option to `pathsToModuleNameMapper` options ([#3792](https://github.com/kulshekhar/ts-jest/issues/3792)) ([eabe906](https://github.com/kulshekhar/ts-jest/commit/eabe906e1dd6b132a7b0d05ffc13172cd8a6b73b))
13
+
14
+
15
+
16
+ ## [29.0.2](https://github.com/kulshekhar/ts-jest/compare/v29.0.1...v29.0.2) (2022-09-23)
17
+
18
+
19
+ ### Bug Fixes
20
+
21
+ * mark `ts-jest` as optional in `ConfigGlobals` ([#3816](https://github.com/kulshekhar/ts-jest/issues/3816)) ([cbb88bb](https://github.com/kulshekhar/ts-jest/commit/cbb88bba34dbb852d8f4013be6e020769feb306d)), closes [#3815](https://github.com/kulshekhar/ts-jest/issues/3815)
22
+ * use correct typings for `config:init` command ([#3825](https://github.com/kulshekhar/ts-jest/issues/3825)) ([21b94db](https://github.com/kulshekhar/ts-jest/commit/21b94dbca25b762f79e63b92dea12d830f444570))
23
+
24
+
25
+
26
+ ## [29.0.2](https://github.com/kulshekhar/ts-jest/compare/v29.0.1...v29.0.2) (2022-09-22)
27
+
28
+
29
+ ### Bug Fixes
30
+
31
+ * mark `ts-jest` as optional in `ConfigGlobals` ([#3816](https://github.com/kulshekhar/ts-jest/issues/3816)) ([cbb88bb](https://github.com/kulshekhar/ts-jest/commit/cbb88bba34dbb852d8f4013be6e020769feb306d)), closes [#3815](https://github.com/kulshekhar/ts-jest/issues/3815)
32
+
33
+
34
+
1
35
  ## [29.0.1](https://github.com/kulshekhar/ts-jest/compare/v29.0.0...v29.0.1) (2022-09-13)
2
36
 
3
37
 
@@ -1 +1,6 @@
1
+ /**
2
+ * This has been written quickly. While trying to improve I realised it'd be better to have it in Jest...
3
+ * ...and I saw a merged PR with `jest --init` tool!
4
+ * TODO: see what's the best path for this
5
+ */
1
6
  export {};
@@ -1,4 +1,9 @@
1
1
  "use strict";
2
+ /**
3
+ * This has been written quickly. While trying to improve I realised it'd be better to have it in Jest...
4
+ * ...and I saw a merged PR with `jest --init` tool!
5
+ * TODO: see what's the best path for this
6
+ */
2
7
  var __assign = (this && this.__assign) || function () {
3
8
  __assign = Object.assign || function(t) {
4
9
  for (var s, i = 1, n = arguments.length; i < n; i++) {
@@ -46,16 +51,35 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
46
51
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
52
  }
48
53
  };
54
+ var __read = (this && this.__read) || function (o, n) {
55
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
56
+ if (!m) return o;
57
+ var i = m.call(o), r, ar = [], e;
58
+ try {
59
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
60
+ }
61
+ catch (error) { e = { error: error }; }
62
+ finally {
63
+ try {
64
+ if (r && !r.done && (m = i["return"])) m.call(i);
65
+ }
66
+ finally { if (e) throw e.error; }
67
+ }
68
+ return ar;
69
+ };
49
70
  Object.defineProperty(exports, "__esModule", { value: true });
50
71
  exports.help = exports.run = void 0;
51
72
  var fs_1 = require("fs");
52
73
  var path_1 = require("path");
53
74
  var json5_1 = require("json5");
54
75
  var presets_1 = require("../helpers/presets");
55
- var run = function (args) { return __awaiter(void 0, void 0, void 0, function () {
56
- var file, filePath, name, isPackage, exists, pkgFile, hasPackage, _a, jestPreset, askedTsconfig, force, jsdom, tsconfig, pkgJson, jsFilesProcessor, shouldPostProcessWithBabel, preset, body, base, tsJestConf, content;
57
- var _b, _c;
58
- return __generator(this, function (_d) {
76
+ /**
77
+ * @internal
78
+ */
79
+ var run = function (args /* , logger: Logger */) { return __awaiter(void 0, void 0, void 0, function () {
80
+ var file, filePath, name, isPackage, exists, pkgFile, hasPackage, _a, jestPreset, askedTsconfig, force, jsdom, tsconfig, pkgJson, jsFilesProcessor, shouldPostProcessWithBabel, preset, body, jestConfig, transformerConfig, content;
81
+ var _b, _c, _d;
82
+ return __generator(this, function (_e) {
59
83
  file = (_c = (_b = args._[0]) === null || _b === void 0 ? void 0 : _b.toString()) !== null && _c !== void 0 ? _c : 'jest.config.js';
60
84
  filePath = (0, path_1.join)(process.cwd(), file);
61
85
  name = (0, path_1.basename)(file);
@@ -67,10 +91,13 @@ var run = function (args) { return __awaiter(void 0, void 0, void 0, function ()
67
91
  tsconfig = askedTsconfig === 'tsconfig.json' ? undefined : askedTsconfig;
68
92
  pkgJson = hasPackage ? JSON.parse((0, fs_1.readFileSync)(pkgFile, 'utf8')) : {};
69
93
  jsFilesProcessor = args.js, shouldPostProcessWithBabel = args.babel;
94
+ // set defaults for missing options
70
95
  if (jsFilesProcessor == null) {
96
+ // set default js files processor depending on whether the user wants to post-process with babel
71
97
  jsFilesProcessor = shouldPostProcessWithBabel ? 'babel' : undefined;
72
98
  }
73
99
  else if (shouldPostProcessWithBabel == null) {
100
+ // auto enables babel post-processing if the user wants babel to process js files
74
101
  shouldPostProcessWithBabel = jsFilesProcessor === 'babel';
75
102
  }
76
103
  if (jsFilesProcessor === 'babel') {
@@ -101,25 +128,35 @@ var run = function (args) { return __awaiter(void 0, void 0, void 0, function ()
101
128
  }
102
129
  }
103
130
  if (isPackage) {
104
- base = jestPreset ? { preset: preset.name } : __assign({}, preset.value);
131
+ jestConfig = jestPreset ? { preset: preset.name } : __assign({}, preset.value);
105
132
  if (!jsdom)
106
- base.testEnvironment = 'node';
107
- if (tsconfig || shouldPostProcessWithBabel) {
108
- tsJestConf = {};
109
- base.globals = { 'ts-jest': tsJestConf };
110
- if (tsconfig)
111
- tsJestConf.tsconfig = tsconfig;
112
- if (shouldPostProcessWithBabel)
113
- tsJestConf.babelConfig = true;
133
+ jestConfig.testEnvironment = 'node';
134
+ transformerConfig = Object.entries((_d = jestConfig.transform) !== null && _d !== void 0 ? _d : {}).reduce(function (acc, _a) {
135
+ var _b, _c;
136
+ var _d = __read(_a, 2), fileRegex = _d[0], transformerConfig = _d[1];
137
+ if (tsconfig || shouldPostProcessWithBabel) {
138
+ var tsJestConf = {};
139
+ if (tsconfig)
140
+ tsJestConf.tsconfig = tsconfig;
141
+ if (shouldPostProcessWithBabel)
142
+ tsJestConf.babelConfig = true;
143
+ return __assign(__assign({}, acc), (_b = {}, _b[fileRegex] = typeof transformerConfig === 'string'
144
+ ? [transformerConfig, tsJestConf]
145
+ : [transformerConfig[0], __assign(__assign({}, transformerConfig[1]), tsJestConf)], _b));
146
+ }
147
+ return __assign(__assign({}, acc), (_c = {}, _c[fileRegex] = transformerConfig, _c));
148
+ }, {});
149
+ if (Object.keys(transformerConfig).length) {
150
+ jestConfig.transform = __assign(__assign({}, jestConfig.transform), transformerConfig);
114
151
  }
115
- body = JSON.stringify(__assign(__assign({}, pkgJson), { jest: base }), undefined, ' ');
152
+ body = JSON.stringify(__assign(__assign({}, pkgJson), { jest: jestConfig }), undefined, ' ');
116
153
  }
117
154
  else {
118
155
  content = [];
119
156
  if (!jestPreset) {
120
157
  content.push("".concat(preset.jsImport('tsjPreset'), ";"), '');
121
158
  }
122
- content.push("/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */");
159
+ content.push("/** @type {import('ts-jest').JestConfigWithTsJest} */");
123
160
  content.push('module.exports = {');
124
161
  if (jestPreset) {
125
162
  content.push(" preset: '".concat(preset.name, "',"));
@@ -130,28 +167,32 @@ var run = function (args) { return __awaiter(void 0, void 0, void 0, function ()
130
167
  if (!jsdom)
131
168
  content.push(" testEnvironment: 'node',");
132
169
  if (tsconfig || shouldPostProcessWithBabel) {
133
- content.push(' globals: {');
134
- content.push(" 'ts-jest': {");
170
+ content.push(' transform: {');
171
+ content.push(" '^.+\\\\.[tj]sx?$': ['ts-jest', {");
135
172
  if (tsconfig)
136
173
  content.push(" tsconfig: ".concat((0, json5_1.stringify)(tsconfig), ","));
137
174
  if (shouldPostProcessWithBabel)
138
175
  content.push(' babelConfig: true,');
139
- content.push(' },');
176
+ content.push(' }],');
140
177
  content.push(' },');
141
178
  }
142
179
  content.push('};');
180
+ // join all together
143
181
  body = content.join('\n');
144
182
  }
145
183
  (0, fs_1.writeFileSync)(filePath, body);
146
184
  process.stderr.write("\nJest configuration written to \"".concat(filePath, "\".\n"));
147
- return [2];
185
+ return [2 /*return*/];
148
186
  });
149
187
  }); };
150
188
  exports.run = run;
189
+ /**
190
+ * @internal
191
+ */
151
192
  var help = function () { return __awaiter(void 0, void 0, void 0, function () {
152
193
  return __generator(this, function (_a) {
153
194
  process.stdout.write("\nUsage:\n ts-jest config:init [options] [<config-file>]\n\nArguments:\n <config-file> Can be a js or json Jest config file. If it is a\n package.json file, the configuration will be read from\n the \"jest\" property.\n Default: jest.config.js\n\nOptions:\n --force Discard any existing Jest config\n --js ts|babel Process .js files with ts-jest if 'ts' or with\n babel-jest if 'babel'\n --no-jest-preset Disable the use of Jest presets\n --tsconfig <file> Path to the tsconfig.json file\n --babel Pipe babel-jest after ts-jest\n --jsdom Use jsdom as test environment instead of node\n");
154
- return [2];
195
+ return [2 /*return*/];
155
196
  });
156
197
  }); };
157
198
  exports.help = help;
@@ -1,4 +1,15 @@
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
+ };
2
13
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
14
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
15
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -72,8 +83,11 @@ var fast_json_stable_stringify_1 = __importDefault(require("fast-json-stable-str
72
83
  var json5_1 = require("json5");
73
84
  var backports_1 = require("../../utils/backports");
74
85
  var presets_1 = require("../helpers/presets");
75
- var run = function (args) { return __awaiter(void 0, void 0, void 0, function () {
76
- var nullLogger, file, filePath, footNotes, name, isPackage, actualConfig, migratedConfig, presetName, preset, jsTransformers, jsWithTs, jsWithBabel, presetValue, migratedValue, presetValue, migratedValue, globalsTsJestConfig, before, after, stringify, prefix;
86
+ /**
87
+ * @internal
88
+ */
89
+ var run = function (args /* , logger: Logger*/) { return __awaiter(void 0, void 0, void 0, function () {
90
+ var nullLogger, file, filePath, footNotes, name, isPackage, actualConfig, migratedConfig, presetName, preset, jsTransformers, jsWithTs, jsWithBabel, presetValue, migratedValue, presetValue, migratedValue, globalsTsJestConfig, migratedConfigTransform, presetValueTransform_1, before, after, stringify, prefix;
77
91
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
78
92
  return __generator(this, function (_l) {
79
93
  nullLogger = (0, bs_logger_1.createLogger)({ targets: [] });
@@ -90,18 +104,22 @@ var run = function (args) { return __awaiter(void 0, void 0, void 0, function ()
90
104
  }
91
105
  actualConfig = require(filePath);
92
106
  if (isPackage) {
107
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
93
108
  actualConfig = actualConfig.jest;
94
109
  }
95
110
  if (!actualConfig)
96
111
  actualConfig = {};
97
112
  migratedConfig = (0, backports_1.backportJestConfig)(nullLogger, actualConfig);
113
+ // then we check if we can use `preset`
98
114
  if (!migratedConfig.preset && args.jestPreset) {
115
+ // find the best preset
99
116
  if (args.js) {
100
- presetName = args.js === 'babel' ? "ts-jest/presets/js-with-babel" : "ts-jest/presets/js-with-ts";
117
+ presetName = args.js === 'babel' ? "ts-jest/presets/js-with-babel" /* JestPresetNames.jsWIthBabel */ : "ts-jest/presets/js-with-ts" /* JestPresetNames.jsWithTs */;
101
118
  }
102
119
  else {
103
120
  jsTransformers = Object.keys(migratedConfig.transform || {}).reduce(function (list, pattern) {
104
121
  if (RegExp(pattern.replace(/^<rootDir>\/?/, '/dummy-project/')).test('/dummy-project/src/foo.js')) {
122
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
105
123
  var transformer = migratedConfig.transform[pattern];
106
124
  if (/\bbabel-jest\b/.test(transformer))
107
125
  transformer = 'babel-jest';
@@ -114,16 +132,18 @@ var run = function (args) { return __awaiter(void 0, void 0, void 0, function ()
114
132
  jsWithTs = jsTransformers.includes('ts-jest');
115
133
  jsWithBabel = jsTransformers.includes('babel-jest');
116
134
  if (jsWithBabel && !jsWithTs) {
117
- presetName = "ts-jest/presets/js-with-babel";
135
+ presetName = "ts-jest/presets/js-with-babel" /* JestPresetNames.jsWIthBabel */;
118
136
  }
119
137
  else if (jsWithTs && !jsWithBabel) {
120
- presetName = "ts-jest/presets/js-with-ts";
138
+ presetName = "ts-jest/presets/js-with-ts" /* JestPresetNames.jsWithTs */;
121
139
  }
122
140
  else {
123
- presetName = "ts-jest/presets/default";
141
+ // sounds like js files are NOT handled, or handled with a unknown transformer, so we do not need to handle it
142
+ presetName = "ts-jest/presets/default" /* JestPresetNames.default */;
124
143
  }
125
144
  }
126
- presetName = presetName !== null && presetName !== void 0 ? presetName : "ts-jest/presets/default";
145
+ // ensure we are using a preset
146
+ presetName = presetName !== null && presetName !== void 0 ? presetName : "ts-jest/presets/default" /* JestPresetNames.default */;
127
147
  preset = presets_1.allPresets[presetName];
128
148
  footNotes.push("Detected preset '".concat(preset.label, "' as the best matching preset for your configuration.\nVisit https://kulshekhar.github.io/ts-jest/user/config/#jest-preset for more information about presets.\n"));
129
149
  }
@@ -132,11 +152,14 @@ var run = function (args) { return __awaiter(void 0, void 0, void 0, function ()
132
152
  delete migratedConfig.preset;
133
153
  }
134
154
  else {
155
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
135
156
  preset = (_c = presets_1.allPresets[migratedConfig.preset]) !== null && _c !== void 0 ? _c : presets_1.defaults;
136
157
  }
137
158
  }
159
+ // enforce the correct name
138
160
  if (preset)
139
161
  migratedConfig.preset = preset.name;
162
+ // check the extensions
140
163
  if (((_d = migratedConfig.moduleFileExtensions) === null || _d === void 0 ? void 0 : _d.length) && preset) {
141
164
  presetValue = dedupSort((_e = preset.value.moduleFileExtensions) !== null && _e !== void 0 ? _e : []).join('::');
142
165
  migratedValue = dedupSort(migratedConfig.moduleFileExtensions).join('::');
@@ -144,9 +167,11 @@ var run = function (args) { return __awaiter(void 0, void 0, void 0, function ()
144
167
  delete migratedConfig.moduleFileExtensions;
145
168
  }
146
169
  }
170
+ // there is a testRegex, remove our testMatch
147
171
  if ((typeof migratedConfig.testRegex === 'string' || ((_f = migratedConfig.testRegex) === null || _f === void 0 ? void 0 : _f.length)) && preset) {
148
172
  delete migratedConfig.testMatch;
149
173
  }
174
+ // check the testMatch
150
175
  else if (((_g = migratedConfig.testMatch) === null || _g === void 0 ? void 0 : _g.length) && preset) {
151
176
  presetValue = dedupSort((_h = preset.value.testMatch) !== null && _h !== void 0 ? _h : []).join('::');
152
177
  migratedValue = dedupSort(migratedConfig.testMatch).join('::');
@@ -154,10 +179,13 @@ var run = function (args) { return __awaiter(void 0, void 0, void 0, function ()
154
179
  delete migratedConfig.testMatch;
155
180
  }
156
181
  }
182
+ // migrate the transform
157
183
  if (migratedConfig.transform) {
158
184
  Object.keys(migratedConfig.transform).forEach(function (key) {
185
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
159
186
  var val = migratedConfig.transform[key];
160
187
  if (typeof val === 'string' && /\/?ts-jest?(?:\/preprocessor\.js)?$/.test(val)) {
188
+ // eslint-disable-next-line
161
189
  ;
162
190
  migratedConfig.transform[key] = 'ts-jest';
163
191
  }
@@ -166,44 +194,85 @@ var run = function (args) { return __awaiter(void 0, void 0, void 0, function ()
166
194
  globalsTsJestConfig = (_j = migratedConfig.globals) === null || _j === void 0 ? void 0 : _j['ts-jest'];
167
195
  if (globalsTsJestConfig && migratedConfig.transform) {
168
196
  Object.keys(migratedConfig.transform).forEach(function (key) {
197
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
169
198
  var val = migratedConfig.transform[key];
170
199
  if (typeof val === 'string' && val.includes('ts-jest')) {
200
+ // eslint-disable-next-line
171
201
  ;
172
202
  migratedConfig.transform[key] = Object.keys(globalsTsJestConfig).length ? [val, globalsTsJestConfig] : val;
173
203
  }
174
204
  });
175
205
  delete ((_k = migratedConfig.globals) !== null && _k !== void 0 ? _k : Object.create(null))['ts-jest'];
176
206
  }
177
- if (preset &&
178
- migratedConfig.transform &&
179
- (0, fast_json_stable_stringify_1.default)(migratedConfig.transform) === (0, fast_json_stable_stringify_1.default)(preset.value.transform)) {
180
- delete migratedConfig.transform;
207
+ // check if it's the same as the preset's one
208
+ if (preset && migratedConfig.transform) {
209
+ if ((0, fast_json_stable_stringify_1.default)(migratedConfig.transform) === (0, fast_json_stable_stringify_1.default)(preset.value.transform)) {
210
+ delete migratedConfig.transform;
211
+ }
212
+ else {
213
+ migratedConfigTransform = migratedConfig.transform;
214
+ presetValueTransform_1 = preset.value.transform;
215
+ if (migratedConfigTransform && presetValueTransform_1) {
216
+ migratedConfig.transform = Object.entries(migratedConfigTransform).reduce(
217
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
218
+ function (acc, _a) {
219
+ var _b, _c;
220
+ var _d = __read(_a, 2), fileRegex = _d[0], transformerConfig = _d[1];
221
+ var presetValueTransformerConfig = presetValueTransform_1[fileRegex];
222
+ var shouldRemoveDuplicatedConfig = (presetValueTransformerConfig &&
223
+ Array.isArray(presetValueTransformerConfig) &&
224
+ transformerConfig === presetValueTransformerConfig[0] &&
225
+ !Object.keys(presetValueTransformerConfig[1]).length) ||
226
+ transformerConfig === presetValueTransformerConfig;
227
+ return shouldRemoveDuplicatedConfig
228
+ ? acc
229
+ : acc
230
+ ? __assign(__assign({}, acc), (_b = {}, _b[fileRegex] = transformerConfig, _b)) : (_c = {}, _c[fileRegex] = transformerConfig, _c);
231
+ }, undefined);
232
+ }
233
+ }
181
234
  }
235
+ // cleanup
182
236
  cleanupConfig(actualConfig);
183
237
  cleanupConfig(migratedConfig);
184
238
  before = (0, fast_json_stable_stringify_1.default)(actualConfig);
185
239
  after = (0, fast_json_stable_stringify_1.default)(migratedConfig);
186
240
  if (after === before) {
187
241
  process.stderr.write("\nNo migration needed for given Jest configuration\n ");
188
- return [2];
242
+ return [2 /*return*/];
189
243
  }
190
244
  stringify = file.endsWith('.json') ? JSON.stringify : json5_1.stringify;
191
245
  prefix = file.endsWith('.json') ? '"jest": ' : 'module.exports = ';
246
+ // if we are using preset, inform the user that he might be able to remove some section(s)
247
+ // we couldn't check for equality
248
+ // if (usesPreset && migratedConfig.testMatch) {
249
+ // footNotes.push(`
250
+ // I couldn't check if your "testMatch" value is the same as mine which is: ${stringify(
251
+ // presets.testMatch,
252
+ // undefined,
253
+ // ' ',
254
+ // )}
255
+ // If it is the case, you can safely remove the "testMatch" from what I've migrated.
256
+ // `)
257
+ // }
192
258
  if (preset && migratedConfig.transform) {
193
259
  footNotes.push("\nI couldn't check if your \"transform\" value is the same as mine which is: ".concat(stringify(preset.value.transform, undefined, ' '), "\nIf it is the case, you can safely remove the \"transform\" from what I've migrated.\n"));
194
260
  }
261
+ // output new config
195
262
  process.stderr.write("\nMigrated Jest configuration:\n");
196
263
  process.stdout.write("".concat(prefix).concat(stringify(migratedConfig, undefined, ' '), "\n"));
197
264
  if (footNotes.length) {
198
265
  process.stderr.write("\n".concat(footNotes.join('\n'), "\n"));
199
266
  }
200
- return [2];
267
+ return [2 /*return*/];
201
268
  });
202
269
  }); };
203
270
  exports.run = run;
204
271
  function cleanupConfig(config) {
205
272
  if (config.globals) {
273
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
206
274
  if (config.globals['ts-jest'] && Object.keys(config.globals['ts-jest']).length === 0) {
275
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
207
276
  delete config.globals['ts-jest'];
208
277
  }
209
278
  if (!Object.keys(config.globals).length) {
@@ -223,18 +292,22 @@ function cleanupConfig(config) {
223
292
  if (!config.testMatch.length)
224
293
  delete config.testMatch;
225
294
  }
226
- if (config.preset === "ts-jest/presets/default")
295
+ if (config.preset === "ts-jest/presets/default" /* JestPresetNames.default */)
227
296
  config.preset = presets_1.defaults.name;
228
297
  }
298
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
229
299
  function dedupSort(arr) {
230
300
  return arr
231
301
  .filter(function (s, i, a) { return a.findIndex(function (e) { return s.toString() === e.toString(); }) === i; })
232
302
  .sort(function (a, b) { return (a.toString() > b.toString() ? 1 : a.toString() < b.toString() ? -1 : 0); });
233
303
  }
304
+ /**
305
+ * @internal
306
+ */
234
307
  var help = function () { return __awaiter(void 0, void 0, void 0, function () {
235
308
  return __generator(this, function (_a) {
236
309
  process.stdout.write("\nUsage:\n ts-jest config:migrate [options] <config-file>\n\nArguments:\n <config-file> Can be a js or json Jest config file. If it is a\n package.json file, the configuration will be read from\n the \"jest\" property.\n\nOptions:\n --js ts|babel Process .js files with ts-jest if 'ts' or with\n babel-jest if 'babel'\n --no-jest-preset Disable the use of Jest presets\n");
237
- return [2];
310
+ return [2 /*return*/];
238
311
  });
239
312
  }); };
240
313
  exports.help = help;
package/dist/cli/help.js CHANGED
@@ -37,11 +37,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.help = exports.run = void 0;
40
+ /**
41
+ * @internal
42
+ */
40
43
  var run = function (_) { return __awaiter(void 0, void 0, void 0, function () {
41
44
  return __generator(this, function (_a) {
42
45
  process.stdout.write("\nUsage:\n ts-jest command [options] [...args]\n\nCommands:\n config:init Creates initial Jest configuration\n config:migrate Migrates a given Jest configuration\n help [command] Show this help, or help about a command\n\nExample:\n ts-jest help config:migrate\n");
43
- return [2];
46
+ return [2 /*return*/];
44
47
  });
45
48
  }); };
46
49
  exports.run = run;
50
+ /**
51
+ * @internal
52
+ */
47
53
  exports.help = exports.run;
@@ -7,15 +7,17 @@ var definePreset = function (fullName) { return ({
7
7
  return this.isDefault ? 'ts-jest' : fullName;
8
8
  },
9
9
  get label() {
10
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
10
11
  return fullName.split('/').pop();
11
12
  },
12
13
  get jsVarName() {
13
14
  return this.isDefault
14
15
  ? 'defaults'
15
- :
16
+ : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
16
17
  fullName
17
18
  .split('/')
18
19
  .pop()
20
+ // eslint-disable-next-line no-useless-escape
19
21
  .replace(/\-([a-z])/g, function (_, l) { return l.toUpperCase(); });
20
22
  },
21
23
  get value() {
@@ -26,10 +28,15 @@ var definePreset = function (fullName) { return ({
26
28
  return "const { ".concat(this.jsVarName, ": ").concat(varName, " } = require('ts-jest/presets')");
27
29
  },
28
30
  get isDefault() {
29
- return fullName === "ts-jest/presets/default";
31
+ return fullName === "ts-jest/presets/default" /* JestPresetNames.default */;
30
32
  },
31
33
  }); };
34
+ /** @internal */
35
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
32
36
  exports.allPresets = {};
33
- exports.defaults = (exports.allPresets["ts-jest/presets/default"] = definePreset("ts-jest/presets/default"));
34
- exports.jsWithTs = (exports.allPresets["ts-jest/presets/js-with-ts"] = definePreset("ts-jest/presets/js-with-ts"));
35
- exports.jsWIthBabel = (exports.allPresets["ts-jest/presets/js-with-babel"] = definePreset("ts-jest/presets/js-with-babel"));
37
+ /** @internal */
38
+ exports.defaults = (exports.allPresets["ts-jest/presets/default" /* JestPresetNames.default */] = definePreset("ts-jest/presets/default" /* JestPresetNames.default */));
39
+ /** @internal */
40
+ exports.jsWithTs = (exports.allPresets["ts-jest/presets/js-with-ts" /* JestPresetNames.jsWithTs */] = definePreset("ts-jest/presets/js-with-ts" /* JestPresetNames.jsWithTs */));
41
+ /** @internal */
42
+ exports.jsWIthBabel = (exports.allPresets["ts-jest/presets/js-with-babel" /* JestPresetNames.jsWIthBabel */] = definePreset("ts-jest/presets/js-with-babel" /* JestPresetNames.jsWIthBabel */));
package/dist/cli/index.js CHANGED
@@ -65,6 +65,7 @@ function cli(args) {
65
65
  },
66
66
  },
67
67
  });
68
+ // deprecated
68
69
  if (parsedArgv.allowJs != null) {
69
70
  if (parsedArgv.js)
70
71
  throw new Error("The 'allowJs' and 'js' options cannot be set together.");
@@ -78,7 +79,7 @@ function cli(args) {
78
79
  command = 'help';
79
80
  _a = require("./".concat(command.replace(/:/g, '/'))), run = _a.run, help = _a.help;
80
81
  cmd = isHelp && command !== 'help' ? help : run;
81
- return [2, cmd(parsedArgv, logger)];
82
+ return [2 /*return*/, cmd(parsedArgv, logger)];
82
83
  });
83
84
  });
84
85
  }
@@ -87,6 +88,9 @@ var errorHasMessage = function (err) {
87
88
  return false;
88
89
  return 'message' in err;
89
90
  };
91
+ /**
92
+ * @internal
93
+ */
90
94
  function processArgv() {
91
95
  return __awaiter(this, void 0, void 0, function () {
92
96
  var err_1;
@@ -94,19 +98,19 @@ function processArgv() {
94
98
  switch (_a.label) {
95
99
  case 0:
96
100
  _a.trys.push([0, 2, , 3]);
97
- return [4, cli(process.argv.slice(2))];
101
+ return [4 /*yield*/, cli(process.argv.slice(2))];
98
102
  case 1:
99
103
  _a.sent();
100
104
  process.exit(0);
101
- return [3, 3];
105
+ return [3 /*break*/, 3];
102
106
  case 2:
103
107
  err_1 = _a.sent();
104
108
  if (errorHasMessage(err_1)) {
105
109
  logger.fatal(err_1.message);
106
110
  process.exit(1);
107
111
  }
108
- return [3, 3];
109
- case 3: return [2];
112
+ return [3 /*break*/, 3];
113
+ case 3: return [2 /*return*/];
110
114
  }
111
115
  });
112
116
  });
@@ -1,6 +1,7 @@
1
1
  import type { Config } from '@jest/types';
2
2
  declare type JestPathMapping = Config.InitialOptions['moduleNameMapper'];
3
- export declare const pathsToModuleNameMapper: (mapping: import("typescript").MapLike<string[]>, { prefix }?: {
4
- prefix: string;
3
+ export declare const pathsToModuleNameMapper: (mapping: import("typescript").MapLike<string[]>, { prefix, useESM }?: {
4
+ prefix?: string | undefined;
5
+ useESM?: boolean | undefined;
5
6
  }) => JestPathMapping;
6
7
  export {};
@@ -16,29 +16,32 @@ exports.pathsToModuleNameMapper = void 0;
16
16
  var bs_logger_1 = require("bs-logger");
17
17
  var utils_1 = require("../utils");
18
18
  var messages_1 = require("../utils/messages");
19
+ // we don't need to escape all chars, so commented out is the real one
20
+ // const escapeRegex = (str: string) => str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
19
21
  var escapeRegex = function (str) { return str.replace(/[-\\^$*+?.()|[\]{}]/g, '\\$&'); };
20
22
  var logger = utils_1.rootLogger.child((_a = {}, _a[bs_logger_1.LogContexts.namespace] = 'path-mapper', _a));
21
23
  var pathsToModuleNameMapper = function (mapping, _a) {
22
24
  var e_1, _b;
23
- var _c = _a === void 0 ? Object.create(null) : _a, _d = _c.prefix, prefix = _d === void 0 ? '' : _d;
25
+ var _c = _a === void 0 ? {} : _a, _d = _c.prefix, prefix = _d === void 0 ? '' : _d, _e = _c.useESM, useESM = _e === void 0 ? false : _e;
24
26
  var jestMap = {};
25
27
  try {
26
- for (var _e = __values(Object.keys(mapping)), _f = _e.next(); !_f.done; _f = _e.next()) {
27
- var fromPath = _f.value;
28
- var pattern = void 0;
28
+ for (var _f = __values(Object.keys(mapping)), _g = _f.next(); !_g.done; _g = _f.next()) {
29
+ var fromPath = _g.value;
29
30
  var toPaths = mapping[fromPath];
31
+ // check that we have only one target path
30
32
  if (toPaths.length === 0) {
31
- logger.warn((0, messages_1.interpolate)("Not mapping \"{{path}}\" because it has no target.", { path: fromPath }));
33
+ logger.warn((0, messages_1.interpolate)("Not mapping \"{{path}}\" because it has no target." /* Errors.NotMappingPathWithEmptyMap */, { path: fromPath }));
32
34
  continue;
33
35
  }
36
+ // split with '*'
34
37
  var segments = fromPath.split(/\*/g);
35
38
  if (segments.length === 1) {
36
39
  var paths = toPaths.map(function (target) {
37
40
  var enrichedPrefix = prefix !== '' && !prefix.endsWith('/') ? "".concat(prefix, "/") : prefix;
38
41
  return "".concat(enrichedPrefix).concat(target);
39
42
  });
40
- pattern = "^".concat(escapeRegex(fromPath), "$");
41
- jestMap[pattern] = paths.length === 1 ? paths[0] : paths;
43
+ var cjsPattern = "^".concat(escapeRegex(fromPath), "$");
44
+ jestMap[cjsPattern] = paths.length === 1 ? paths[0] : paths;
42
45
  }
43
46
  else if (segments.length === 2) {
44
47
  var paths = toPaths.map(function (target) {
@@ -46,21 +49,28 @@ var pathsToModuleNameMapper = function (mapping, _a) {
46
49
  var enrichedPrefix = prefix !== '' && !prefix.endsWith('/') ? "".concat(prefix, "/") : prefix;
47
50
  return "".concat(enrichedPrefix).concat(enrichedTarget.replace(/\*/g, '$1'));
48
51
  });
49
- pattern = "^".concat(escapeRegex(segments[0]), "(.*)").concat(escapeRegex(segments[1]), "$");
50
- jestMap[pattern] = paths.length === 1 ? paths[0] : paths;
52
+ if (useESM) {
53
+ var esmPattern = "^".concat(escapeRegex(segments[0]), "(.*)").concat(escapeRegex(segments[1]), "\\.js$");
54
+ jestMap[esmPattern] = paths.length === 1 ? paths[0] : paths;
55
+ }
56
+ var cjsPattern = "^".concat(escapeRegex(segments[0]), "(.*)").concat(escapeRegex(segments[1]), "$");
57
+ jestMap[cjsPattern] = paths.length === 1 ? paths[0] : paths;
51
58
  }
52
59
  else {
53
- logger.warn((0, messages_1.interpolate)("Not mapping \"{{path}}\" because it has more than one star (`*`).", { path: fromPath }));
60
+ logger.warn((0, messages_1.interpolate)("Not mapping \"{{path}}\" because it has more than one star (`*`)." /* Errors.NotMappingMultiStarPath */, { path: fromPath }));
54
61
  }
55
62
  }
56
63
  }
57
64
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
58
65
  finally {
59
66
  try {
60
- if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
67
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
61
68
  }
62
69
  finally { if (e_1) throw e_1.error; }
63
70
  }
71
+ if (useESM) {
72
+ jestMap['^(\\.{1,2}/.*)\\.js$'] = '$1';
73
+ }
64
74
  return jestMap;
65
75
  };
66
76
  exports.pathsToModuleNameMapper = pathsToModuleNameMapper;
package/dist/constants.js CHANGED
@@ -6,6 +6,11 @@ exports.DECLARATION_TYPE_EXT = '.d.ts';
6
6
  exports.JS_JSX_EXTENSIONS = ['.js', '.jsx'];
7
7
  exports.TS_TSX_REGEX = /\.m?tsx?$/;
8
8
  exports.JS_JSX_REGEX = /\.m?jsx?$/;
9
+ // `extensionsToTreatAsEsm` will throw error with `.mjs`
9
10
  exports.TS_EXT_TO_TREAT_AS_ESM = ['.ts', '.tsx', '.mts'];
10
11
  exports.JS_EXT_TO_TREAT_AS_ESM = ['.jsx'];
12
+ /**
13
+ * @internal
14
+ * See https://jestjs.io/docs/en/configuration#testmatch-arraystring
15
+ */
11
16
  exports.DEFAULT_JEST_TEST_MATCH = ['**/__tests__/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[jt]s?(x)'];