@pkg-nec/create-jest 30.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.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) Meta Platforms, Inc. and affiliates.
4
+ Copyright Contributors to the Jest project.
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,11 @@
1
+ # create-jest
2
+
3
+ > Getting started with Jest with a single command
4
+
5
+ ```bash
6
+ npm init jest@latest
7
+ # Or for Yarn
8
+ yarn create jest
9
+ # Or for pnpm
10
+ pnpm create jest
11
+ ```
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ require('..').runCLI();
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ export declare function runCLI(): Promise<void>;
9
+
10
+ export declare function runCreate(rootDir?: string): Promise<void>;
package/build/index.js ADDED
@@ -0,0 +1,465 @@
1
+ /*!
2
+ * /**
3
+ * * Copyright (c) Meta Platforms, Inc. and affiliates.
4
+ * *
5
+ * * This source code is licensed under the MIT license found in the
6
+ * * LICENSE file in the root directory of this source tree.
7
+ * * /
8
+ */
9
+ /******/ (() => { // webpackBootstrap
10
+ /******/ "use strict";
11
+ /******/ var __webpack_modules__ = ({
12
+
13
+ /***/ "./src/errors.ts"
14
+ (__unused_webpack_module, exports) {
15
+
16
+
17
+
18
+ Object.defineProperty(exports, "__esModule", ({
19
+ value: true
20
+ }));
21
+ exports.NotFoundPackageJsonError = exports.MalformedPackageJsonError = void 0;
22
+ /**
23
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
24
+ *
25
+ * This source code is licensed under the MIT license found in the
26
+ * LICENSE file in the root directory of this source tree.
27
+ */
28
+
29
+ class NotFoundPackageJsonError extends Error {
30
+ constructor(rootDir) {
31
+ super(`Could not find a "package.json" file in ${rootDir}`);
32
+ this.name = '';
33
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
34
+ Error.captureStackTrace(this, () => {});
35
+ }
36
+ }
37
+ exports.NotFoundPackageJsonError = NotFoundPackageJsonError;
38
+ class MalformedPackageJsonError extends Error {
39
+ constructor(packageJsonPath) {
40
+ super(`There is malformed json in ${packageJsonPath}`);
41
+ this.name = '';
42
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
43
+ Error.captureStackTrace(this, () => {});
44
+ }
45
+ }
46
+ exports.MalformedPackageJsonError = MalformedPackageJsonError;
47
+
48
+ /***/ },
49
+
50
+ /***/ "./src/generateConfigFile.ts"
51
+ (__unused_webpack_module, exports) {
52
+
53
+
54
+
55
+ Object.defineProperty(exports, "__esModule", ({
56
+ value: true
57
+ }));
58
+ exports["default"] = void 0;
59
+ function _jestConfig() {
60
+ const data = require("@pkg-nec/jest-config");
61
+ _jestConfig = function () {
62
+ return data;
63
+ };
64
+ return data;
65
+ }
66
+ /**
67
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
68
+ *
69
+ * This source code is licensed under the MIT license found in the
70
+ * LICENSE file in the root directory of this source tree.
71
+ */
72
+
73
+ const stringifyOption = (option, map, linePrefix = '') => {
74
+ const description = _jestConfig().descriptions[option];
75
+ const optionDescription = description != null && description.length > 0 ? ` // ${description}` : '';
76
+ const stringifiedObject = `${option}: ${JSON.stringify(map[option], null, 2)}`;
77
+ return `${optionDescription}\n${stringifiedObject.split('\n').map(line => ` ${linePrefix}${line}`).join('\n')},`;
78
+ };
79
+ const generateConfigFile = (results, generateEsm = false) => {
80
+ const {
81
+ useTypescript,
82
+ coverage,
83
+ coverageProvider,
84
+ clearMocks,
85
+ environment
86
+ } = results;
87
+ const overrides = {};
88
+ if (coverage) {
89
+ Object.assign(overrides, {
90
+ collectCoverage: true,
91
+ coverageDirectory: 'coverage'
92
+ });
93
+ }
94
+ if (coverageProvider === 'v8') {
95
+ Object.assign(overrides, {
96
+ coverageProvider: 'v8'
97
+ });
98
+ }
99
+ if (environment === 'jsdom') {
100
+ Object.assign(overrides, {
101
+ testEnvironment: 'jsdom'
102
+ });
103
+ }
104
+ if (clearMocks) {
105
+ Object.assign(overrides, {
106
+ clearMocks: true
107
+ });
108
+ }
109
+ const overrideKeys = Object.keys(overrides);
110
+ const properties = [];
111
+ for (const option in _jestConfig().descriptions) {
112
+ const opt = option;
113
+ if (overrideKeys.includes(opt)) {
114
+ properties.push(stringifyOption(opt, overrides));
115
+ } else {
116
+ properties.push(stringifyOption(opt, _jestConfig().defaults, '// '));
117
+ }
118
+ }
119
+ const configHeaderMessage = `/**
120
+ * For a detailed explanation regarding each configuration property, visit:
121
+ * https://jestjs.io/docs/configuration
122
+ */
123
+ `;
124
+ const jsDeclaration = `/** @type {import('@pkg-nec/jest').Config} */
125
+ const config = {`;
126
+ const tsDeclaration = `import type {Config} from '@pkg-nec/jest';
127
+
128
+ const config: Config = {`;
129
+ const cjsExport = 'module.exports = config;';
130
+ const esmExport = 'export default config;';
131
+ return [configHeaderMessage, useTypescript ? tsDeclaration : jsDeclaration, properties.join('\n\n'), '};\n', useTypescript || generateEsm ? esmExport : cjsExport, ''].join('\n');
132
+ };
133
+ var _default = exports["default"] = generateConfigFile;
134
+
135
+ /***/ },
136
+
137
+ /***/ "./src/modifyPackageJson.ts"
138
+ (__unused_webpack_module, exports) {
139
+
140
+
141
+
142
+ Object.defineProperty(exports, "__esModule", ({
143
+ value: true
144
+ }));
145
+ exports["default"] = void 0;
146
+ /**
147
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
148
+ *
149
+ * This source code is licensed under the MIT license found in the
150
+ * LICENSE file in the root directory of this source tree.
151
+ */
152
+
153
+ const modifyPackageJson = ({
154
+ projectPackageJson,
155
+ shouldModifyScripts
156
+ }) => {
157
+ if (shouldModifyScripts) {
158
+ if (projectPackageJson.scripts) {
159
+ projectPackageJson.scripts.test = 'jest';
160
+ } else {
161
+ projectPackageJson.scripts = {
162
+ test: 'jest'
163
+ };
164
+ }
165
+ }
166
+ delete projectPackageJson.jest;
167
+ return `${JSON.stringify(projectPackageJson, null, 2)}\n`;
168
+ };
169
+ var _default = exports["default"] = modifyPackageJson;
170
+
171
+ /***/ },
172
+
173
+ /***/ "./src/questions.ts"
174
+ (__unused_webpack_module, exports) {
175
+
176
+
177
+
178
+ Object.defineProperty(exports, "__esModule", ({
179
+ value: true
180
+ }));
181
+ exports.testScriptQuestion = exports["default"] = void 0;
182
+ /**
183
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
184
+ *
185
+ * This source code is licensed under the MIT license found in the
186
+ * LICENSE file in the root directory of this source tree.
187
+ */
188
+
189
+ const defaultQuestions = [{
190
+ initial: false,
191
+ message: 'Would you like to use Typescript for the configuration file?',
192
+ name: 'useTypescript',
193
+ type: 'confirm'
194
+ }, {
195
+ choices: [{
196
+ title: 'node',
197
+ value: 'node'
198
+ }, {
199
+ title: 'jsdom (browser-like)',
200
+ value: 'jsdom'
201
+ }],
202
+ initial: 0,
203
+ message: 'Choose the test environment that will be used for testing',
204
+ name: 'environment',
205
+ type: 'select'
206
+ }, {
207
+ initial: false,
208
+ message: 'Do you want Jest to add coverage reports?',
209
+ name: 'coverage',
210
+ type: 'confirm'
211
+ }, {
212
+ choices: [{
213
+ title: 'v8',
214
+ value: 'v8'
215
+ }, {
216
+ title: 'babel',
217
+ value: 'babel'
218
+ }],
219
+ initial: 0,
220
+ message: 'Which provider should be used to instrument code for coverage?',
221
+ name: 'coverageProvider',
222
+ type: 'select'
223
+ }, {
224
+ initial: false,
225
+ message: 'Automatically clear mock calls, instances, contexts and results before every test?',
226
+ name: 'clearMocks',
227
+ type: 'confirm'
228
+ }];
229
+ var _default = exports["default"] = defaultQuestions;
230
+ const testScriptQuestion = exports.testScriptQuestion = {
231
+ initial: true,
232
+ message: 'Would you like to use Jest when running "test" script in "package.json"?',
233
+ name: 'scripts',
234
+ type: 'confirm'
235
+ };
236
+
237
+ /***/ },
238
+
239
+ /***/ "./src/runCreate.ts"
240
+ (__unused_webpack_module, exports, __webpack_require__) {
241
+
242
+
243
+
244
+ Object.defineProperty(exports, "__esModule", ({
245
+ value: true
246
+ }));
247
+ exports.runCLI = runCLI;
248
+ exports.runCreate = runCreate;
249
+ function path() {
250
+ const data = _interopRequireWildcard(require("node:path"));
251
+ path = function () {
252
+ return data;
253
+ };
254
+ return data;
255
+ }
256
+ function _chalk() {
257
+ const data = _interopRequireDefault(require("chalk"));
258
+ _chalk = function () {
259
+ return data;
260
+ };
261
+ return data;
262
+ }
263
+ function _exitX() {
264
+ const data = _interopRequireDefault(require("exit-x"));
265
+ _exitX = function () {
266
+ return data;
267
+ };
268
+ return data;
269
+ }
270
+ function fs() {
271
+ const data = _interopRequireWildcard(require("graceful-fs"));
272
+ fs = function () {
273
+ return data;
274
+ };
275
+ return data;
276
+ }
277
+ function _prompts() {
278
+ const data = _interopRequireDefault(require("prompts"));
279
+ _prompts = function () {
280
+ return data;
281
+ };
282
+ return data;
283
+ }
284
+ function _jestConfig() {
285
+ const data = require("@pkg-nec/jest-config");
286
+ _jestConfig = function () {
287
+ return data;
288
+ };
289
+ return data;
290
+ }
291
+ function _jestUtil() {
292
+ const data = require("@pkg-nec/jest-util");
293
+ _jestUtil = function () {
294
+ return data;
295
+ };
296
+ return data;
297
+ }
298
+ var _errors = __webpack_require__("./src/errors.ts");
299
+ var _generateConfigFile = _interopRequireDefault(__webpack_require__("./src/generateConfigFile.ts"));
300
+ var _modifyPackageJson = _interopRequireDefault(__webpack_require__("./src/modifyPackageJson.ts"));
301
+ var _questions = _interopRequireWildcard(__webpack_require__("./src/questions.ts"));
302
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
303
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
304
+ /**
305
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
306
+ *
307
+ * This source code is licensed under the MIT license found in the
308
+ * LICENSE file in the root directory of this source tree.
309
+ */
310
+
311
+ const {
312
+ JEST_CONFIG_BASE_NAME,
313
+ JEST_CONFIG_EXT_MJS,
314
+ JEST_CONFIG_EXT_JS,
315
+ JEST_CONFIG_EXT_TS,
316
+ JEST_CONFIG_EXT_ORDER,
317
+ PACKAGE_JSON
318
+ } = _jestConfig().constants;
319
+ const getConfigFilename = ext => JEST_CONFIG_BASE_NAME + ext;
320
+ async function runCLI() {
321
+ try {
322
+ const rootDir = process.argv[2];
323
+ await runCreate(rootDir);
324
+ } catch (error) {
325
+ (0, _jestUtil().clearLine)(process.stderr);
326
+ (0, _jestUtil().clearLine)(process.stdout);
327
+ if (error instanceof Error && Boolean(error?.stack)) {
328
+ console.error(_chalk().default.red(error.stack));
329
+ } else {
330
+ console.error(_chalk().default.red(error));
331
+ }
332
+ (0, _exitX().default)(1);
333
+ throw error;
334
+ }
335
+ }
336
+ async function runCreate(rootDir = process.cwd()) {
337
+ rootDir = (0, _jestUtil().tryRealpath)(rootDir);
338
+ // prerequisite checks
339
+ const projectPackageJsonPath = path().join(rootDir, PACKAGE_JSON);
340
+ if (!fs().existsSync(projectPackageJsonPath)) {
341
+ throw new _errors.NotFoundPackageJsonError(rootDir);
342
+ }
343
+ const questions = [..._questions.default];
344
+ let hasJestProperty = false;
345
+ let projectPackageJson;
346
+ try {
347
+ projectPackageJson = JSON.parse(fs().readFileSync(projectPackageJsonPath, 'utf8'));
348
+ } catch {
349
+ throw new _errors.MalformedPackageJsonError(projectPackageJsonPath);
350
+ }
351
+ if (projectPackageJson.jest) {
352
+ hasJestProperty = true;
353
+ }
354
+ const existingJestConfigExt = JEST_CONFIG_EXT_ORDER.find(ext => fs().existsSync(path().join(rootDir, getConfigFilename(ext))));
355
+ if (hasJestProperty || existingJestConfigExt != null) {
356
+ const result = await (0, _prompts().default)({
357
+ initial: true,
358
+ message: 'It seems that you already have a jest configuration, do you want to override it?',
359
+ name: 'continue',
360
+ type: 'confirm'
361
+ });
362
+ if (!result.continue) {
363
+ console.log();
364
+ console.log('Aborting...');
365
+ return;
366
+ }
367
+ }
368
+
369
+ // Add test script installation only if needed
370
+ if (projectPackageJson.scripts?.test !== 'jest') {
371
+ questions.unshift(_questions.testScriptQuestion);
372
+ }
373
+
374
+ // Start the init process
375
+ console.log();
376
+ console.log(_chalk().default.underline('The following questions will help Jest to create a suitable configuration for your project\n'));
377
+ let promptAborted = false;
378
+ const results = await (0, _prompts().default)(questions, {
379
+ onCancel: () => {
380
+ promptAborted = true;
381
+ }
382
+ });
383
+ if (promptAborted) {
384
+ console.log();
385
+ console.log('Aborting...');
386
+ return;
387
+ }
388
+
389
+ // Determine if Jest should use JS or TS for the config file
390
+ const jestConfigFileExt = results.useTypescript ? JEST_CONFIG_EXT_TS : projectPackageJson.type === 'module' ? JEST_CONFIG_EXT_MJS : JEST_CONFIG_EXT_JS;
391
+
392
+ // Determine Jest config path
393
+ const jestConfigPath = existingJestConfigExt == null ? path().join(rootDir, getConfigFilename(jestConfigFileExt)) : getConfigFilename(existingJestConfigExt);
394
+ const shouldModifyScripts = results.scripts;
395
+ if (shouldModifyScripts || hasJestProperty) {
396
+ const modifiedPackageJson = (0, _modifyPackageJson.default)({
397
+ projectPackageJson,
398
+ shouldModifyScripts
399
+ });
400
+ fs().writeFileSync(projectPackageJsonPath, modifiedPackageJson);
401
+ console.log('');
402
+ console.log(`✏️ Modified ${_chalk().default.cyan(projectPackageJsonPath)}`);
403
+ }
404
+ const generatedConfig = (0, _generateConfigFile.default)(results, projectPackageJson.type === 'module' || jestConfigPath.endsWith(JEST_CONFIG_EXT_MJS));
405
+ fs().writeFileSync(jestConfigPath, generatedConfig);
406
+ console.log('');
407
+ console.log(`📝 Configuration file created at ${_chalk().default.cyan(jestConfigPath)}`);
408
+ }
409
+
410
+ /***/ }
411
+
412
+ /******/ });
413
+ /************************************************************************/
414
+ /******/ // The module cache
415
+ /******/ var __webpack_module_cache__ = {};
416
+ /******/
417
+ /******/ // The require function
418
+ /******/ function __webpack_require__(moduleId) {
419
+ /******/ // Check if module is in cache
420
+ /******/ var cachedModule = __webpack_module_cache__[moduleId];
421
+ /******/ if (cachedModule !== undefined) {
422
+ /******/ return cachedModule.exports;
423
+ /******/ }
424
+ /******/ // Create a new module (and put it into the cache)
425
+ /******/ var module = __webpack_module_cache__[moduleId] = {
426
+ /******/ // no module.id needed
427
+ /******/ // no module.loaded needed
428
+ /******/ exports: {}
429
+ /******/ };
430
+ /******/
431
+ /******/ // Execute the module function
432
+ /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
433
+ /******/
434
+ /******/ // Return the exports of the module
435
+ /******/ return module.exports;
436
+ /******/ }
437
+ /******/
438
+ /************************************************************************/
439
+ var __webpack_exports__ = {};
440
+ // This entry needs to be wrapped in an IIFE because it uses a non-standard name for the exports (exports).
441
+ (() => {
442
+ var exports = __webpack_exports__;
443
+
444
+
445
+ Object.defineProperty(exports, "__esModule", ({
446
+ value: true
447
+ }));
448
+ Object.defineProperty(exports, "runCLI", ({
449
+ enumerable: true,
450
+ get: function () {
451
+ return _runCreate.runCLI;
452
+ }
453
+ }));
454
+ Object.defineProperty(exports, "runCreate", ({
455
+ enumerable: true,
456
+ get: function () {
457
+ return _runCreate.runCreate;
458
+ }
459
+ }));
460
+ var _runCreate = __webpack_require__("./src/runCreate.ts");
461
+ })();
462
+
463
+ module.exports = __webpack_exports__;
464
+ /******/ })()
465
+ ;
@@ -0,0 +1,4 @@
1
+ import cjsModule from './index.js';
2
+
3
+ export const runCLI = cjsModule.runCLI;
4
+ export const runCreate = cjsModule.runCreate;
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@pkg-nec/create-jest",
3
+ "description": "Create a new Jest project",
4
+ "version": "30.4.2",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/jestjs/jest.git",
8
+ "directory": "packages/create-jest"
9
+ },
10
+ "license": "MIT",
11
+ "bin": "./bin/create-jest.js",
12
+ "main": "./build/index.js",
13
+ "types": "./build/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./build/index.d.ts",
17
+ "require": "./build/index.js",
18
+ "import": "./build/index.mjs",
19
+ "default": "./build/index.js"
20
+ },
21
+ "./package.json": "./package.json",
22
+ "./bin/create-jest": "./bin/create-jest.js"
23
+ },
24
+ "dependencies": {
25
+ "@pkg-nec/jest-config": "30.4.2",
26
+ "@pkg-nec/jest-types": "30.4.1",
27
+ "@pkg-nec/jest-util": "30.4.1",
28
+ "chalk": "^4.1.2",
29
+ "exit-x": "^0.2.2",
30
+ "graceful-fs": "^4.2.11",
31
+ "prompts": "^2.4.2"
32
+ },
33
+ "engines": {
34
+ "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "devDependencies": {
40
+ "@types/graceful-fs": "^4.1.9",
41
+ "@types/prompts": "^2.4.9"
42
+ }
43
+ }