diff --git a/.cspell.json b/.cspell.json index 565018f91da..3d9a5243b1c 100644 --- a/.cspell.json +++ b/.cspell.json @@ -64,6 +64,7 @@ "Nitin", "nwjs", "Oikawa", + "PATHEXT", "pathinfo", "plopfile", "pnpm", diff --git a/CHANGELOG.md b/CHANGELOG.md index e8dc883569e..1291ee10bed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Change Log +## 7.3.1 + +### Patch Changes + +- fix: detect missing package managers and failed installations, without a lock file the CLI chose npm even when it wasn't installed instead of yarn or pnpm, and it continued after a package failed to install (by [@alexander-akait](https://github.com/alexander-akait) in [#4889](https://github.com/webpack/webpack-cli/pull/4889)) + +- chore: replace the `import-local` and `cross-spawn` dependencies with Node.js built-ins (by [@alexander-akait](https://github.com/alexander-akait) in [#4889](https://github.com/webpack/webpack-cli/pull/4889)) + +- chore: load configuration files with `import()` instead of `eval` (by [@alexander-akait](https://github.com/alexander-akait) in [#4893](https://github.com/webpack/webpack-cli/pull/4893)) + ## 7.3.0 ### Minor Changes diff --git a/package-lock.json b/package-lock.json index 49a920cf6da..dea3a27f952 100644 --- a/package-lock.json +++ b/package-lock.json @@ -39,7 +39,7 @@ "json5": "^2.2.3", "lint-staged": "^17.6.0", "mini-css-extract-plugin": "^2.10.2", - "pkg-pr-new": "^0.0.91", + "pkg-pr-new": "^0.0.92", "prettier": "^3.9.10", "readable-stream": "^4.8.0", "sass": "^1.105.2", @@ -3283,23 +3283,23 @@ } }, "node_modules/@inquirer/ansi": { - "version": "2.0.9", - "resolved": "https://registry.npmjs.org/@inquirer/ansi/-/ansi-2.0.9.tgz", - "integrity": "sha512-0Ywt3S8tqM6TWUcsRlBFQ1x+X3/o8kktX0ZiKAnByYb9GFDknnOhse1PVtfiD2BXPI8ar+BWx9PV9R0lQIcygw==", + "version": "2.0.10", + "resolved": "https://registry.npmjs.org/@inquirer/ansi/-/ansi-2.0.10.tgz", + "integrity": "sha512-dwrc+1aqVZpHNkNDswXGtn1typ+Pxpo5FHZRyBw1le7onEJUkPUkYOY1FIFC1LvFMYUqqLuWBwElhAmencL7MQ==", "license": "MIT", "engines": { "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" } }, "node_modules/@inquirer/core": { - "version": "12.0.5", - "resolved": "https://registry.npmjs.org/@inquirer/core/-/core-12.0.5.tgz", - "integrity": "sha512-c0ZSnO9oVk/IlEGoZK3u8b3IZQeu9I6jUkXJSQnQEVRXsjKvtAq3AGqFL2LgfJhlzMZne08pZHWRWasIcI3Rew==", + "version": "12.0.6", + "resolved": "https://registry.npmjs.org/@inquirer/core/-/core-12.0.6.tgz", + "integrity": "sha512-5yxn2LsJ8Tu4ei2a+yNkmFRhM/cb+JMEsEs/AW6CCOnBnpMy4IjYiPMFyHtYq8weOmlTyqqCx40y0DsD7OsEPw==", "license": "MIT", "dependencies": { - "@inquirer/ansi": "^2.0.9", - "@inquirer/figures": "^2.0.9", - "@inquirer/type": "4.2.0", + "@inquirer/ansi": "^2.0.10", + "@inquirer/figures": "^2.0.10", + "@inquirer/type": "4.2.1", "cli-width": "^4.1.0", "fast-wrap-ansi": "^0.2.0", "mute-stream": "^3.0.0", @@ -3318,13 +3318,13 @@ } }, "node_modules/@inquirer/expand": { - "version": "5.1.7", - "resolved": "https://registry.npmjs.org/@inquirer/expand/-/expand-5.1.7.tgz", - "integrity": "sha512-eiJ31YFCaB6fLoJCqLIn8S6eqUyME6vwr8KcP5h8cxmA+bV9RRVPO+kywoxb7G63HduDXV6sN/SM7o2R+ahEcQ==", + "version": "5.1.8", + "resolved": "https://registry.npmjs.org/@inquirer/expand/-/expand-5.1.8.tgz", + "integrity": "sha512-dMEnTkpLqzM/sbILwL7QJgx9iX5hoEM8+bh6shgwd9mYJamdOnth7y2mMaFd08Glj9AXEFKllWcGYyBqnJsHrA==", "license": "MIT", "dependencies": { - "@inquirer/core": "^12.0.5", - "@inquirer/type": "4.2.0" + "@inquirer/core": "^12.0.6", + "@inquirer/type": "4.2.1" }, "engines": { "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" @@ -3360,24 +3360,24 @@ } }, "node_modules/@inquirer/figures": { - "version": "2.0.9", - "resolved": "https://registry.npmjs.org/@inquirer/figures/-/figures-2.0.9.tgz", - "integrity": "sha512-EAWgUTGQ/Umgga51dE3B2PUHbufuXarDfg86uVgoSgNHNNQnyFKcOrQLWVqYMghuSyHh8+2HUH0Js9cTC1WAdg==", + "version": "2.0.10", + "resolved": "https://registry.npmjs.org/@inquirer/figures/-/figures-2.0.10.tgz", + "integrity": "sha512-51elrUJV3jZpvD0ygz8+U10Kc6+Lzqln+/tYmnbhy6jo5oXpE6hMCcv+OTBC0enwJXsb3JIuT3VtEinRNCSK2A==", "license": "MIT", "engines": { "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" } }, "node_modules/@inquirer/select": { - "version": "5.2.7", - "resolved": "https://registry.npmjs.org/@inquirer/select/-/select-5.2.7.tgz", - "integrity": "sha512-pRDWO4dTqSAvFQdO8yclKMtXNDm9K9HmvWB5UZmT3clw2OlOBNXveHzhyFmO/0d0yJMqlPcNITus1Jtpm6t8VQ==", + "version": "5.2.8", + "resolved": "https://registry.npmjs.org/@inquirer/select/-/select-5.2.8.tgz", + "integrity": "sha512-BklkkAAOpjdCfuQw5fVGcDuhKxA7T1iBpn6b2JUvDDdkIsO3Ftlg+WnWUCVpkUBFagL2o036OFW+xL4lC9wIPw==", "license": "MIT", "dependencies": { - "@inquirer/ansi": "^2.0.9", - "@inquirer/core": "^12.0.5", - "@inquirer/figures": "^2.0.9", - "@inquirer/type": "4.2.0" + "@inquirer/ansi": "^2.0.10", + "@inquirer/core": "^12.0.6", + "@inquirer/figures": "^2.0.10", + "@inquirer/type": "4.2.1" }, "engines": { "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" @@ -3392,9 +3392,9 @@ } }, "node_modules/@inquirer/type": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.2.0.tgz", - "integrity": "sha512-2rnHX8RPo4glJYqnFc/v3nQeIhDcjyRRyaT7MGcfL/8xv/8K03SXYoA2tX06WVSKywWOE/ncbG3dtuzLjR5TCQ==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.2.1.tgz", + "integrity": "sha512-lDkPsnv5M5CcYB2T1qTc3dobNTPkVr4DU3Ic2Q6SW8/qVRHgvzdRdmVZ6YqG9Ag1aJTeMsLU0s0WPRh3CZWDQQ==", "license": "MIT", "engines": { "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" @@ -8891,9 +8891,9 @@ } }, "node_modules/coffeescript": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/coffeescript/-/coffeescript-2.7.0.tgz", - "integrity": "sha512-hzWp6TUE2d/jCcN67LrW1eh5b/rSDKQK6oD6VMLlggYVUUFexgTH9z3dNYihzX4RMhze5FTUsUmOXViJKFQR/A==", + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/coffeescript/-/coffeescript-2.7.1.tgz", + "integrity": "sha512-zDQ0M/Ad05+5eudURWh31RIQc8i1TxIWuUgidoRx7gtrcQnDwSwSckVaJLg3AGKE+z0PuKnIOZ1DZnYvebuvIg==", "dev": true, "license": "MIT", "bin": { @@ -12416,6 +12416,7 @@ "version": "3.2.0", "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.2.0.tgz", "integrity": "sha512-2SPlun1JUPWoM6t3F0dw0FkCF/jWY8kttcY4f599GLTSjh2OCuuhdTkJQsEcZzBqbXZGKMK2OqW1oZsjtf/gQA==", + "dev": true, "license": "MIT", "dependencies": { "pkg-dir": "^4.2.0", @@ -17290,6 +17291,7 @@ "version": "2.2.0", "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "dev": true, "license": "MIT", "engines": { "node": ">=6" @@ -17404,6 +17406,7 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -17484,6 +17487,7 @@ "version": "4.2.0", "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", + "dev": true, "license": "MIT", "dependencies": { "find-up": "^4.0.0" @@ -17496,6 +17500,7 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dev": true, "license": "MIT", "dependencies": { "locate-path": "^5.0.0", @@ -17509,6 +17514,7 @@ "version": "5.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dev": true, "license": "MIT", "dependencies": { "p-locate": "^4.1.0" @@ -17521,6 +17527,7 @@ "version": "2.3.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, "license": "MIT", "dependencies": { "p-try": "^2.0.0" @@ -17536,6 +17543,7 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dev": true, "license": "MIT", "dependencies": { "p-limit": "^2.2.0" @@ -17545,9 +17553,9 @@ } }, "node_modules/pkg-pr-new": { - "version": "0.0.91", - "resolved": "https://registry.npmjs.org/pkg-pr-new/-/pkg-pr-new-0.0.91.tgz", - "integrity": "sha512-FQPmjspKRKYV4MlHQnun9snJqlYm6Yhmo12x1O3pgE2Akim/y/BZjMOppK//BFdh222WOj6WGqlmeZfrtUtfgQ==", + "version": "0.0.92", + "resolved": "https://registry.npmjs.org/pkg-pr-new/-/pkg-pr-new-0.0.92.tgz", + "integrity": "sha512-l9HE4y0LmS5n3pw9vKby7m9O+SBzjWF5HXGH6Z8jdPWW7OW7hFMKsFOrgubc0JuPz8gYEuIw1mLaU3GEmPuukQ==", "dev": true, "license": "MIT", "bin": { @@ -18254,6 +18262,7 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", + "dev": true, "license": "MIT", "dependencies": { "resolve-from": "^5.0.0" @@ -18266,6 +18275,7 @@ "version": "5.0.0", "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -18486,9 +18496,9 @@ } }, "node_modules/sass-loader": { - "version": "17.0.1", - "resolved": "https://registry.npmjs.org/sass-loader/-/sass-loader-17.0.1.tgz", - "integrity": "sha512-pgJMwCuLjVTSIWsv/2luVRXKlCeaViUGcgSe8dx95zMG4hUwqIMFmjbhq29ypFLflJU0GyiJZeLM9iI1n3KYAA==", + "version": "17.1.0", + "resolved": "https://registry.npmjs.org/sass-loader/-/sass-loader-17.1.0.tgz", + "integrity": "sha512-EZ/u/bLkAErTKvIq/f81Bz6tgL/5Brt8hWOABdTsVdO+nX0PWx2rQhR6fyxVME+MhnQrrwecMDlm2G1y07hhpQ==", "dev": true, "license": "MIT", "engines": { @@ -21025,11 +21035,11 @@ } }, "packages/create-webpack-app": { - "version": "2.2.0", + "version": "2.2.1", "license": "MIT", "dependencies": { - "@inquirer/expand": "^5.1.7", - "@inquirer/select": "^5.2.7", + "@inquirer/expand": "^5.1.8", + "@inquirer/select": "^5.2.8", "colorette": "^2.0.20", "commander": "^14.0.3", "cross-spawn": "^7.0.6", @@ -21061,14 +21071,12 @@ } }, "packages/webpack-cli": { - "version": "7.2.3", + "version": "7.3.0", "license": "MIT", "dependencies": { "@discoveryjs/json-ext": "^1.1.0", "commander": "^14.0.3", - "cross-spawn": "^7.0.6", "envinfo": "^7.21.0", - "import-local": "^3.2.0", "interpret": "^3.1.1", "rechoir": "^1.0.0", "webpack-merge": "^6.0.1" diff --git a/package.json b/package.json index f7ea0b1baa7..e603dba6a5d 100644 --- a/package.json +++ b/package.json @@ -83,7 +83,7 @@ "json5": "^2.2.3", "lint-staged": "^17.6.0", "mini-css-extract-plugin": "^2.10.2", - "pkg-pr-new": "^0.0.91", + "pkg-pr-new": "^0.0.92", "prettier": "^3.9.10", "readable-stream": "^4.8.0", "sass": "^1.105.2", diff --git a/packages/create-webpack-app/package.json b/packages/create-webpack-app/package.json index c3e5ce0d183..4496b4e0320 100644 --- a/packages/create-webpack-app/package.json +++ b/packages/create-webpack-app/package.json @@ -39,8 +39,8 @@ "watch": "tsc --watch" }, "dependencies": { - "@inquirer/expand": "^5.1.7", - "@inquirer/select": "^5.2.7", + "@inquirer/expand": "^5.1.8", + "@inquirer/select": "^5.2.8", "colorette": "^2.0.20", "commander": "^14.0.3", "cross-spawn": "^7.0.6", diff --git a/packages/webpack-cli/CHANGELOG.md b/packages/webpack-cli/CHANGELOG.md index e8dc883569e..1291ee10bed 100644 --- a/packages/webpack-cli/CHANGELOG.md +++ b/packages/webpack-cli/CHANGELOG.md @@ -1,5 +1,15 @@ # Change Log +## 7.3.1 + +### Patch Changes + +- fix: detect missing package managers and failed installations, without a lock file the CLI chose npm even when it wasn't installed instead of yarn or pnpm, and it continued after a package failed to install (by [@alexander-akait](https://github.com/alexander-akait) in [#4889](https://github.com/webpack/webpack-cli/pull/4889)) + +- chore: replace the `import-local` and `cross-spawn` dependencies with Node.js built-ins (by [@alexander-akait](https://github.com/alexander-akait) in [#4889](https://github.com/webpack/webpack-cli/pull/4889)) + +- chore: load configuration files with `import()` instead of `eval` (by [@alexander-akait](https://github.com/alexander-akait) in [#4893](https://github.com/webpack/webpack-cli/pull/4893)) + ## 7.3.0 ### Minor Changes diff --git a/packages/webpack-cli/bin/cli.js b/packages/webpack-cli/bin/cli.js index 0ebc85ef4ac..7575a0dc556 100755 --- a/packages/webpack-cli/bin/cli.js +++ b/packages/webpack-cli/bin/cli.js @@ -25,10 +25,56 @@ if (enableCompileCache) { } } +/** + * Runs the local installation of `webpack-cli` resolved from the current directory, unless it is + * this file, the same as `import-local` does. + * @returns {boolean} whether the local installation was run + */ +const runLocalCLI = () => { + const path = require("node:path"); + + let cwd; + + try { + cwd = require("node:fs").realpathSync(process.cwd()); + } catch (error) { + if (error.code !== "ENOENT") { + return false; + } + + cwd = path.resolve(process.cwd()); + } + + let localFile; + + try { + localFile = require("node:module") + .createRequire(path.join(cwd, "noop.js")) + .resolve("webpack-cli/bin/cli.js"); + } catch { + return false; + } + + const localNodeModules = path.join(process.cwd(), "node_modules"); + const isInLocalNodeModules = + !path.relative(localNodeModules, __filename).startsWith("..") && + // On Windows, `path.relative()` returns the second path when the paths are on different drives + path.parse(localNodeModules).root === path.parse(__filename).root; + + // `path.relative()` because the case of `__filename` is inconsistent on Windows + if (isInLocalNodeModules || path.relative(localFile, __filename) === "") { + return false; + } + + require(localFile); + + return true; +}; + // Prefer the local installation of `webpack-cli` when one exists. Run this // before requiring the (heavier) CLI implementation: a delegated run then never -// loads it, and `WEBPACK_CLI_SKIP_IMPORT_LOCAL` skips loading `import-local` too. -if (!process.env.WEBPACK_CLI_SKIP_IMPORT_LOCAL && require("import-local")(__filename)) { +// loads it, and `WEBPACK_CLI_SKIP_IMPORT_LOCAL` skips the lookup too. +if (!process.env.WEBPACK_CLI_SKIP_IMPORT_LOCAL && runLocalCLI()) { return; } diff --git a/packages/webpack-cli/package.json b/packages/webpack-cli/package.json index 944acfa7547..ce9ecd36f17 100644 --- a/packages/webpack-cli/package.json +++ b/packages/webpack-cli/package.json @@ -1,6 +1,6 @@ { "name": "webpack-cli", - "version": "7.3.0", + "version": "7.3.1", "description": "CLI for webpack & friends", "keywords": [ "webpack", @@ -33,9 +33,7 @@ "dependencies": { "@discoveryjs/json-ext": "^1.1.0", "commander": "^14.0.3", - "cross-spawn": "^7.0.6", "envinfo": "^7.21.0", - "import-local": "^3.2.0", "interpret": "^3.1.1", "rechoir": "^1.0.0", "webpack-merge": "^6.0.1" diff --git a/packages/webpack-cli/src/webpack-cli.ts b/packages/webpack-cli/src/webpack-cli.ts index 6633eb7ef60..250cd0558bf 100644 --- a/packages/webpack-cli/src/webpack-cli.ts +++ b/packages/webpack-cli/src/webpack-cli.ts @@ -1,3 +1,4 @@ +import { type SpawnOptions } from "node:child_process"; import fs from "node:fs"; import { createRequire } from "node:module"; import path from "node:path"; @@ -628,9 +629,93 @@ class WebpackCLI { }; } - async getDefaultPackageManager(): Promise { - const { sync } = await import("cross-spawn"); + /** + * Runs a command, the same as `cross-spawn` does. + * @param {string} command command + * @param {string[]} args arguments + * @param {SpawnOptions} options options + * @returns {Promise<{ status: number | null, error?: Error }>} exit status, or the error when the command fails to start + */ + async #spawn( + command: string, + args: string[], + options: SpawnOptions = {}, + ): Promise<{ status: number | null; error?: Error }> { + const { spawn } = await import("node:child_process"); + const run = (command: string, args: string[], options: SpawnOptions) => + new Promise<{ status: number | null; error?: Error }>((resolve) => { + spawn(command, args, options) + .once("error", (error) => resolve({ status: null, error })) + .once("close", (status) => resolve({ status })); + }); + + if (process.platform !== "win32") { + return run(command, args, options); + } + + // Find the file of the command like `which`, on Windows the current directory goes first + const extensions = (process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM").split(";"); + + if (command.includes(".") && extensions[0] !== "") { + extensions.unshift(""); + } + + const directories = /[/\\]/.test(command) + ? [""] + : [process.cwd(), ...(process.env.PATH || "").split(";")]; + let file: string | undefined; + + search: for (const directory of directories) { + for (const extension of extensions) { + const candidate = path.resolve( + path.join(directory.replace(/^"(.*)"$/, "$1"), command) + extension, + ); + + try { + if ( + (await fs.promises.stat(candidate)).isFile() && + extensions.some( + (extension) => + extension !== "" && candidate.toLowerCase().endsWith(extension.toLowerCase()), + ) + ) { + file = candidate; + + break search; + } + } catch { + // Not found + } + } + } + + // Executables run directly + if (file && /\.(?:com|exe)$/i.test(file)) { + return run(command, args, options); + } + + // Other files, e.g. `npm.cmd`, only run in a shell, which doesn't escape arguments, and the + // `.cmd` shims of packages pass them to another shell, so they are escaped twice + const isShim = Boolean(file && /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i.test(file)); + const metaChars = /([()\][%!^"`<>&|;, *?])/g; + const escapedArgs = args.map((arg) => { + const quoted = `"${arg + // Double the backslashes before a quote and escape the quote + .replaceAll(/(?=(\\+?)?)\1"/g, '$1$1\\"') + // Double the backslashes at the end, they precede the closing quote + .replace(/(?=(\\+?)?)\1$/, "$1$1")}"`.replaceAll(metaChars, "^$1"); + + return isShim ? quoted.replaceAll(metaChars, "^$1") : quoted; + }); + return run( + [path.normalize(command).replaceAll(metaChars, "^$1"), ...escapedArgs].join(" "), + [], + { ...options, shell: true }, + ); + } + + async getDefaultPackageManager(): Promise { try { await fs.promises.access(path.resolve(process.cwd(), "package-lock.json"), fs.constants.F_OK); return "npm"; @@ -652,37 +737,20 @@ class WebpackCLI { // Nothing } - try { - // the sync function below will fail if npm is not installed, - // an error will be thrown - if (sync("npm", ["--version"])) { - return "npm"; - } - } catch { - // Nothing - } + // A missing package manager fails to start, or exits with an error in the shell on Windows + for (const packageManager of ["npm", "yarn", "pnpm"] as const) { + const { error, status } = await this.#spawn(packageManager, ["--version"], { + stdio: "ignore", + }); - try { - // the sync function below will fail if yarn is not installed, - // an error will be thrown - if (sync("yarn", ["--version"])) { - return "yarn"; + if (!error && status === 0) { + return packageManager; } - } catch { - // Nothing } - try { - // the sync function below will fail if pnpm is not installed, - // an error will be thrown - if (sync("pnpm", ["--version"])) { - return "pnpm"; - } - } catch { - this.logger.error("No package manager found."); + this.logger.error("No package manager found."); - process.exit(2); - } + process.exit(2); } async isPackageInstalled(packageName: string): Promise { @@ -812,10 +880,18 @@ class WebpackCLI { } if (needInstall) { - const { sync } = await import("cross-spawn"); - try { - sync(packageManager, commandArguments, { stdio: "inherit" }); + const { error, status } = await this.#spawn(packageManager, commandArguments, { + stdio: "inherit", + }); + + if (error) { + throw error; + } + + if (status !== 0) { + throw new Error(`'${commandToBeRun}' exited with code ${status}`); + } } catch (error) { this.logger.error(error); @@ -3262,9 +3338,8 @@ class WebpackCLI { let loadingError; try { - options = // eslint-disable-next-line no-eval - (await eval(`import("${isFileURL ? configPath : pathToFileURL(configPath)}")`)) - .default; + options = (await import(isFileURL ? configPath : pathToFileURL(configPath).href)) + .default; } catch (err) { if (this.isValidationError(err) || process.env?.WEBPACK_CLI_FORCE_LOAD_ESM_CONFIG) { throw err; diff --git a/test/api/get-default-package-manager.test.js b/test/api/get-default-package-manager.test.js index 349a6f1cd66..e252b1fc86e 100644 --- a/test/api/get-default-package-manager.test.js +++ b/test/api/get-default-package-manager.test.js @@ -1,13 +1,29 @@ +const { EventEmitter } = require("node:events"); const fs = require("node:fs"); const path = require("node:path"); const CLI = require("../../packages/webpack-cli/lib/webpack-cli").default; -const syncMock = jest.fn(() => ({ - stdout: "1.0.0", -})); -jest.setMock("cross-spawn", { - sync: syncMock, -}); +/** + * Creates a process which exits with the status, or fails to start with the error. + * @param {number | Error} result exit status or error + * @returns {() => EventEmitter} process + */ +const processWith = (result) => () => { + // eslint-disable-next-line unicorn/prefer-event-target -- Child processes are event emitters + const child = new EventEmitter(); + + process.nextTick(() => + result instanceof Error ? child.emit("error", result) : child.emit("close", result), + ); + + return child; +}; + +const installed = processWith(0); +const missing = processWith(Object.assign(new Error("spawn ENOENT"), { code: "ENOENT" })); +const spawnMock = jest.fn(installed); + +jest.unstable_mockModule("node:child_process", () => ({ spawn: spawnMock })); describe("getPackageManager", () => { let cli; @@ -39,70 +55,86 @@ describe("getPackageManager", () => { beforeEach(() => { cli = new CLI(); - syncMock.mockClear(); + spawnMock.mockClear(); + spawnMock.mockImplementation(installed); }); it("should find yarn.lock", async () => { cwdSpy.mockReturnValue(testYarnLockPath); expect(await cli.getDefaultPackageManager()).toBe("yarn"); - expect(syncMock).not.toHaveBeenCalled(); + expect(spawnMock).not.toHaveBeenCalled(); }); it("should find package-lock.json", async () => { cwdSpy.mockReturnValue(testNpmLockPath); expect(await cli.getDefaultPackageManager()).toBe("npm"); - expect(syncMock).not.toHaveBeenCalled(); + expect(spawnMock).not.toHaveBeenCalled(); }); it("should find pnpm-lock.yaml", async () => { cwdSpy.mockReturnValue(testPnpmLockPath); expect(await cli.getDefaultPackageManager()).toBe("pnpm"); - expect(syncMock).not.toHaveBeenCalled(); + expect(spawnMock).not.toHaveBeenCalled(); }); it("should prioritize npm over pnpm", async () => { cwdSpy.mockReturnValue(testNpmAndPnpmPath); expect(await cli.getDefaultPackageManager()).toBe("npm"); - expect(syncMock).not.toHaveBeenCalled(); + expect(spawnMock).not.toHaveBeenCalled(); }); it("should prioritize npm over yarn", async () => { cwdSpy.mockReturnValue(testNpmAndYarnPath); expect(await cli.getDefaultPackageManager()).toBe("npm"); - expect(syncMock).not.toHaveBeenCalled(); + expect(spawnMock).not.toHaveBeenCalled(); }); it("should prioritize yarn over pnpm", async () => { cwdSpy.mockReturnValue(testYarnAndPnpmPath); expect(await cli.getDefaultPackageManager()).toBe("yarn"); - expect(syncMock).not.toHaveBeenCalled(); + expect(spawnMock).not.toHaveBeenCalled(); }); it("should prioritize npm with many lock files", async () => { cwdSpy.mockReturnValue(testAllPath); expect(await cli.getDefaultPackageManager()).toBe("npm"); - expect(syncMock).not.toHaveBeenCalled(); + expect(spawnMock).not.toHaveBeenCalled(); }); it("should prioritize global npm over other package managers", async () => { cwdSpy.mockReturnValue(noLockPath); expect(await cli.getDefaultPackageManager()).toBe("npm"); - expect(syncMock).toHaveBeenCalledTimes(1); + expect(spawnMock).toHaveBeenCalledTimes(1); + }); + + it("should find yarn when npm is missing", async () => { + cwdSpy.mockReturnValue(noLockPath); + spawnMock.mockImplementationOnce(missing); + + expect(await cli.getDefaultPackageManager()).toBe("yarn"); + expect(spawnMock).toHaveBeenCalledTimes(2); + }); + + it("should find pnpm when npm fails and yarn is missing", async () => { + cwdSpy.mockReturnValue(noLockPath); + // On Windows a missing command fails in the shell + spawnMock.mockImplementationOnce(processWith(1)).mockImplementationOnce(missing); + + expect(await cli.getDefaultPackageManager()).toBe("pnpm"); + expect(spawnMock).toHaveBeenCalledTimes(3); }); it("should throw error if no package manager is found", async () => { cwdSpy.mockReturnValue(noLockPath); - syncMock.mockImplementation(() => { - throw new Error("error"); - }); + spawnMock.mockImplementation(missing); const mockExit = jest.spyOn(process, "exit").mockImplementation(() => {}); // Do not print warning in CI const consoleMock = jest.spyOn(console, "error").mockImplementation(() => {}); @@ -110,6 +142,9 @@ describe("getPackageManager", () => { expect(await cli.getDefaultPackageManager()).toBeFalsy(); expect(mockExit).toHaveBeenCalledWith(2); expect(consoleMock).toHaveBeenCalledTimes(1); - expect(syncMock).toHaveBeenCalledTimes(3); // 3 calls for npm, yarn and pnpm + expect(spawnMock).toHaveBeenCalledTimes(3); // 3 calls for npm, yarn and pnpm + + mockExit.mockRestore(); + consoleMock.mockRestore(); }); }); diff --git a/test/api/install-package.test.js b/test/api/install-package.test.js index 51907d6555d..1f9976a4b49 100644 --- a/test/api/install-package.test.js +++ b/test/api/install-package.test.js @@ -1,5 +1,9 @@ "use strict"; +const { EventEmitter } = require("node:events"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); const { stripVTControlCharacters } = require("node:util"); const CLI = require("../../packages/webpack-cli/lib/webpack-cli").default; @@ -12,9 +16,37 @@ jest.unstable_mockModule("node:readline", () => ({ }), })); -const spawnMock = jest.fn(); +// A process which exits successfully +const spawnMock = jest.fn(() => { + // eslint-disable-next-line unicorn/prefer-event-target -- Child processes are event emitters + const child = new EventEmitter(); -jest.mock("cross-spawn", () => ({ sync: spawnMock })); + process.nextTick(() => child.emit("close", 0)); + + return child; +}); + +jest.unstable_mockModule("node:child_process", () => ({ spawn: spawnMock })); + +/** + * Checks the command which installs the package. + * @param {string} packageManager package manager + * @param {string[]} args arguments + */ +const expectInstallCommand = (packageManager, args) => { + expect(spawnMock).toHaveBeenCalledTimes(1); + + if (process.platform === "win32") { + // Package managers are `.cmd` files on Windows, so they run in a shell with escaped arguments + expect(spawnMock).toHaveBeenCalledWith( + [packageManager, ...args.map((arg) => `^"${arg}^"`)].join(" "), + [], + { stdio: "inherit", shell: true }, + ); + } else { + expect(spawnMock).toHaveBeenCalledWith(packageManager, args, { stdio: "inherit" }); + } +}; describe("installPackage", () => { let cli; @@ -45,9 +77,7 @@ describe("installPackage", () => { "Would you like to install 'test-package' package? (That will run 'npm install -D test-package')", ); - // install the package using npm - expect(spawnMock.mock.calls[0][0]).toBe("npm"); - expect(spawnMock.mock.calls[0][1]).toEqual(["install", "-D", "test-package"]); + expectInstallCommand("npm", ["install", "-D", "test-package"]); }); it("should prompt to install using yarn if yarn is package manager", async () => { @@ -63,9 +93,7 @@ describe("installPackage", () => { "Would you like to install 'test-package' package? (That will run 'yarn add -D test-package')", ); - // install the package using yarn - expect(spawnMock.mock.calls[0][0]).toBe("yarn"); - expect(spawnMock.mock.calls[0][1]).toEqual(["add", "-D", "test-package"]); + expectInstallCommand("yarn", ["add", "-D", "test-package"]); }); it("should prompt to install using pnpm if pnpm is package manager", async () => { @@ -81,9 +109,76 @@ describe("installPackage", () => { "Would you like to install 'test-package' package? (That will run 'pnpm install -D test-package')", ); - // install the package using npm - expect(spawnMock.mock.calls[0][0]).toBe("pnpm"); - expect(spawnMock.mock.calls[0][1]).toEqual(["install", "-D", "test-package"]); + expectInstallCommand("pnpm", ["install", "-D", "test-package"]); + }); + + describe("on Windows", () => { + let directory; + let platform; + let env; + + beforeEach(() => { + directory = fs.mkdtempSync(path.join(os.tmpdir(), "webpack-cli-install-package-")); + platform = Object.getOwnPropertyDescriptor(process, "platform"); + env = { PATH: process.env.PATH, PATHEXT: process.env.PATHEXT }; + + Object.defineProperty(process, "platform", { value: "win32" }); + process.env.PATH = directory; + process.env.PATHEXT = ".exe;.cmd"; + readlineQuestionMock.mockImplementation((_questionTest, cb) => cb("y")); + getDefaultPackageManagerSpy.mockReturnValue("npm"); + }); + + afterEach(() => { + Object.defineProperty(process, "platform", platform); + + for (const [name, value] of Object.entries(env)) { + if (typeof value === "undefined") { + delete process.env[name]; + } else { + process.env[name] = value; + } + } + + fs.rmSync(directory, { recursive: true, force: true }); + }); + + it("should escape the arguments for the shell", async () => { + fs.writeFileSync(path.join(directory, "npm.cmd"), ""); + + await cli.installPackage('a"b&c'); + + expect(spawnMock).toHaveBeenCalledWith('npm ^"install^" ^"-D^" ^"a\\^"b^&c^"', [], { + stdio: "inherit", + shell: true, + }); + }); + + it("should escape the arguments twice for the shims of packages", async () => { + const bin = path.join(directory, "node_modules", ".bin"); + + fs.mkdirSync(bin, { recursive: true }); + fs.writeFileSync(path.join(bin, "npm.cmd"), ""); + process.env.PATH = bin; + + await cli.installPackage('a"b&c'); + + expect(spawnMock).toHaveBeenCalledWith( + 'npm ^^^"install^^^" ^^^"-D^^^" ^^^"a\\^^^"b^^^&c^^^"', + [], + { stdio: "inherit", shell: true }, + ); + }); + + it("should run executables without a shell", async () => { + fs.writeFileSync(path.join(directory, "npm.exe"), ""); + + await cli.installPackage("test-package"); + + expect(spawnMock).toHaveBeenCalledWith("npm", ["install", "-D", "test-package"], { + stdio: "inherit", + }); + }); }); it("should support pre message", async () => { @@ -101,9 +196,7 @@ describe("installPackage", () => { "Would you like to install 'test-package' package? (That will run 'npm install -D test-package')", ); - // install the package using npm - expect(spawnMock.mock.calls[0][0]).toBe("npm"); - expect(spawnMock.mock.calls[0][1]).toEqual(["install", "-D", "test-package"]); + expectInstallCommand("npm", ["install", "-D", "test-package"]); }); it("should prompt to install and install using 'y'", async () => { @@ -119,9 +212,7 @@ describe("installPackage", () => { "Would you like to install 'test-package' package? (That will run 'npm install -D test-package')", ); - // install the package using npm - expect(spawnMock.mock.calls[0][0]).toBe("npm"); - expect(spawnMock.mock.calls[0][1]).toEqual(["install", "-D", "test-package"]); + expectInstallCommand("npm", ["install", "-D", "test-package"]); }); it("should prompt to install and install using 'yes'", async () => { @@ -137,9 +228,7 @@ describe("installPackage", () => { "Would you like to install 'test-package' package? (That will run 'npm install -D test-package')", ); - // install the package using npm - expect(spawnMock.mock.calls[0][0]).toBe("npm"); - expect(spawnMock.mock.calls[0][1]).toEqual(["install", "-D", "test-package"]); + expectInstallCommand("npm", ["install", "-D", "test-package"]); }); it("should prompt to install and install using 'yEs'", async () => { @@ -155,9 +244,43 @@ describe("installPackage", () => { "Would you like to install 'test-package' package? (That will run 'npm install -D test-package')", ); - // install the package using npm - expect(spawnMock.mock.calls[0][0]).toBe("npm"); - expect(spawnMock.mock.calls[0][1]).toEqual(["install", "-D", "test-package"]); + expectInstallCommand("npm", ["install", "-D", "test-package"]); + }); + + it.each([ + [ + "exits with an error", + (child) => child.emit("close", 1), + "'npm install -D test-package' exited with code 1", + ], + [ + "fails to start", + (child) => child.emit("error", new Error("spawn npm ENOENT")), + "spawn npm ENOENT", + ], + ])("should exit when the installation %s", async (_name, fail, message) => { + readlineQuestionMock.mockImplementation((_questionTest, cb) => cb("y")); + getDefaultPackageManagerSpy.mockReturnValue("npm"); + spawnMock.mockImplementationOnce(() => { + // eslint-disable-next-line unicorn/prefer-event-target -- Child processes are event emitters + const child = new EventEmitter(); + + process.nextTick(() => fail(child)); + + return child; + }); + + const mockExit = jest.spyOn(process, "exit").mockImplementation(() => {}); + const consoleMock = jest.spyOn(console, "error").mockImplementation(() => {}); + + await cli.installPackage("test-package"); + + expect(mockExit).toHaveBeenCalledWith(2); + expect(consoleMock).toHaveBeenCalledTimes(1); + expect(stripVTControlCharacters(consoleMock.mock.calls[0][0])).toContain(message); + + mockExit.mockRestore(); + consoleMock.mockRestore(); }); it("should not install if install is not confirmed", async () => { diff --git a/test/build/config/basic/basic-config.test.js b/test/build/config/basic/basic-config.test.js index 4f861f55f71..b7f44998d05 100644 --- a/test/build/config/basic/basic-config.test.js +++ b/test/build/config/basic/basic-config.test.js @@ -1,5 +1,8 @@ "use strict"; +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); const { resolve } = require("node:path"); const { pathToFileURL } = require("node:url"); const { cleanStderr, run } = require("../../../utils/test-utils"); @@ -40,6 +43,24 @@ describe("basic config file", () => { expect(stdout).toBeTruthy(); }); + it("should load a configuration path as a module specifier and not run it as code", async () => { + const marker = path.join( + fs.mkdtempSync(path.join(os.tmpdir(), "webpack-cli-config-path-")), + "executed", + ); + const configPath = `file:///webpack.config.js"),require("node:fs").writeFileSync(${JSON.stringify(marker)},""),import("file:///webpack.config.js`; + + try { + const { exitCode, stderr } = await run(__dirname, ["-c", configPath]); + + expect(exitCode).toBe(2); + expect(stderr).toContain("Failed to load"); + expect(fs.existsSync(marker)).toBe(false); + } finally { + fs.rmSync(path.dirname(marker), { recursive: true, force: true }); + } + }); + it("should build and not throw error with a basic using weird path", async () => { const { exitCode, stderr, stdout } = await run(__dirname, [ "-c", diff --git a/test/build/import-local/import-local.test.js b/test/build/import-local/import-local.test.js index f9c086114a1..0001f41d82f 100644 --- a/test/build/import-local/import-local.test.js +++ b/test/build/import-local/import-local.test.js @@ -1,20 +1,52 @@ "use strict"; +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); const { cleanStderr, run } = require("../../utils/test-utils"); -const importLocalMock = jest.fn(); -jest.setMock("import-local", importLocalMock); - describe("import local", () => { - beforeEach(() => { - importLocalMock.mockClear(); + let directory; + + beforeAll(() => { + // A project with its own installation of `webpack-cli` + directory = fs.mkdtempSync(path.join(os.tmpdir(), "webpack-cli-import-local-")); + + const bin = path.join(directory, "node_modules", "webpack-cli", "bin"); + + fs.mkdirSync(bin, { recursive: true }); + fs.writeFileSync( + path.join(directory, "node_modules", "webpack-cli", "package.json"), + JSON.stringify({ name: "webpack-cli", main: "bin/cli.js" }), + ); + fs.writeFileSync(path.join(bin, "cli.js"), 'console.log("local webpack-cli");\n'); }); - it("should skip import local when supplied", async () => { - const { exitCode, stderr, stdout } = await run(__dirname, [], { + afterAll(() => { + fs.rmSync(directory, { recursive: true, force: true }); + }); + + it("should run the local installation", async () => { + const { exitCode, stderr, stdout } = await run(directory, ["--version"]); + + expect(exitCode).toBe(0); + expect(cleanStderr(stderr)).toBeFalsy(); + expect(stdout.trim()).toBe("local webpack-cli"); + }); + + it("should skip the local installation when supplied", async () => { + const { exitCode, stdout } = await run(directory, ["--version"], { env: { WEBPACK_CLI_SKIP_IMPORT_LOCAL: true }, }); - expect(importLocalMock).not.toHaveBeenCalled(); + + expect(exitCode).toBe(0); + expect(stdout).toBeTruthy(); + expect(stdout).not.toContain("local webpack-cli"); + }); + + it("should build without a local installation", async () => { + const { exitCode, stderr, stdout } = await run(__dirname, []); + expect(exitCode).toBe(0); expect(cleanStderr(stderr)).toBeFalsy(); expect(stdout).toBeTruthy(); diff --git a/test/create-webpack-app/test.utils.js b/test/create-webpack-app/test.utils.js index 541bcfad14b..6721fff7c91 100644 --- a/test/create-webpack-app/test.utils.js +++ b/test/create-webpack-app/test.utils.js @@ -22,6 +22,9 @@ const packageManagerEnv = { os.tmpdir(), `webpack-cli-yarn-cache-${process.env.JEST_WORKER_ID || 1}`, ), + // Yarn 1 fails on packages which require a newer Node.js version than the one running tests, + // the tests check the generated projects and not the engines of the installed packages + YARN_IGNORE_ENGINES: "true", }; /**