Switching to esm-only (#2464)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Change to explicit .mjs for implementation files * Remove stale jest.config.js * move esm.mjs to deprecated and GONE * Convert tests to esm, and use .js file extension for esm * Replace __filename and __dirname usage * Fix color issues in tests by not rendering arrays using console.log * Convert examples to erm * Fix URL in comment * Update samples to esm in README * Fix version in deprecation notes * Run tests using mocks of node module methods in cjs where better supported * Add migration tips and examples for require(esm) * Rename files so Jest tests in examples not run with Commander tests
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
191 files+1455 added−1194 removed
- tests:+1050 added−950 removed
- other:+405 added−244 removed
Provenance
- Commit
f4bd470- Tree
c00507c- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
b51c0ea
191 files changed+1455 added−1194 removed
modified:docs/deprecated.md+19 added-17 removed
10 unmodified lines11 - [.on('command:\*')](#oncommand)12 - [.command('\*')](#command)13 - [cmd.description(cmdDescription, argDescriptions)](#cmddescriptioncmddescription-argdescriptions)14 - [InvalidOptionArgumentError](#invalidoptionargumenterror)15- - [Import from `commander/esm.mjs`](#import-from-commanderesmmjs)15 - [cmd.\_args](#cmd_args)16 - [.addHelpCommand(string|boolean|undefined)](#addhelpcommandstringbooleanundefined)17 - [Removed](#removed)18 - [Short option flag longer than a single character](#short-option-flag-longer-than-a-single-character)19 - [Default import of global Command object](#default-import-of-global-command-object)20+ - [Import from `commander/esm.mjs`](#import-from-commanderesmmjs)21 22 ### RegExp .option() parameter23 24 The `.option()` method allowed a RegExp as the third parameter to restrict what values were accepted.142 unmodified lines167 ```168 169 Deprecated from Commander v8.170 171-### Import from `commander/esm.mjs`172-173-The first support for named imports required an explicit entry file.174-175-```js176-import { Command } from 'commander/esm.mjs';177-```178-179-This is no longer required, just import directly from the module.180-181-```js182-import { Command } from 'commander';183-```184-185-README updated in Commander v9. Deprecated from Commander v9.186-171 ### cmd._args172 173 This was always private, but was previously the only way to access the command `Argument` array.174 64 unmodified lines239 - Removed from README in Commander v5.240 - Deprecated from Commander v7.241 - Removed from TypeScript declarations in Commander v8.242 - Removed from CommonJS in Commander v12. Deprecated and gone!243+244+### Import from `commander/esm.mjs`245+246+The first support for named imports required an explicit entry file.247+248+```js249+import { Command } from 'commander/esm.mjs';250+```251+252+This is no longer required, just import directly from the module.253+254+```js255+import { Command } from 'commander';256+```257+258+- README updated in Commander v9. Deprecated from Commander v9.259+- Deleted in Command v15. Deprecated and gone!260+added:examples/using-esm-from-commonjs/jest-javascript/.gitignore+4 added
1+node_modules/2+3+# Save space, do not commit package-lock.json with all the Jest dependencies!4+package-lock.jsonadded:examples/using-esm-from-commonjs/jest-javascript/babel.config.js+3 added
123module.exports = { presets: [['@babel/preset-env', { targets: { node: 'current' } }]],};added:examples/using-esm-from-commonjs/jest-javascript/index.spec.cjs+9 added
123456789const { Command } = require('commander');const { test, expect } = require('@jest/globals');
test('when set command name then get command name', () => { const program = new Command(); const name = 'my-cli'; program.name(name); expect(program.name()).toBe(name);});added:examples/using-esm-from-commonjs/jest-javascript/jest.config.js+6 added
123456// List the dependencies that are pure esm and need transformation.const esmModules = ['commander'].join('|'); // redundant join in case you have others
module.exports = { transformIgnorePatterns: [`node_modules/(?!(${esmModules})/)`],};added:examples/using-esm-from-commonjs/jest-javascript/package.json+17 added
1234567891011121314151617{ "name": "jest-javascript", "version": "1.0.0", "description": "", "scripts": { "test": "jest" }, "license": "MIT", "type": "commonjs", "dependencies": { "commander": "^15.0.0" }, "devDependencies": { "@babel/preset-env": "^7.28.6", "jest": "^30.2.0" }}added:examples/using-esm-from-commonjs/jest-javascript/README.md+40 added
12345678910111213141516171819202122232425262728293031323334353637383940# Example configuration for Jest 30 running CommonJS Javascript
This project shows using Babel to transform Commander ESM to CommonJS.
Example error message when requiring ESM-only Commander in a Jest test with default configuration:
```$ npm run --silent test FAIL ./index.test.js ● Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
[more detail omitted, check output for up-to-date suggestions]... SyntaxError: Cannot use import statement outside a module
> 1 | const { Command } = require('commander');...```
Additional install:
```consolenpm install --save-dev @babel/preset-env```
Additional setup:
- add `babel.config.js` to configure babel for smart setup for current node version- add `transformIgnorePatterns` to `jest.config.js` to process Commander from `node_modules`
Running test:
```consolenpm installnpm test```added:examples/using-esm-from-commonjs/jest-typescript/.gitignore+4 added
1+node_modules/2+3+# Save space, do not commit package-lock.json with all the Jest dependencies!4+package-lock.jsonadded:examples/using-esm-from-commonjs/jest-typescript/index.spec.cts+9 added
1+import { Command } from 'commander';2+import { test, expect } from '@jest/globals';3+4+test('when set command name then get command name', () => {5+ const program = new Command();6+ const name = 'my-cli';7+ program.name(name);8+ expect(program.name()).toBe(name);9+});added:examples/using-esm-from-commonjs/jest-typescript/jest.config.js+16 added
1+// List the dependencies that are pure esm and need transformation.2+const esmModules = ['commander'].join('|'); // redundant join in case you have others3+4+module.exports = {5+ // 1. tell ts-jest to (also) handle .js and .mjs files6+ transform: {7+ '^.+\\.[cm]?[tj]sx?$': [8+ 'ts-jest',9+ {10+ useESM: false, // want CJS for Jest11+ },12+ ],13+ },14+ // 2. allow transformation of specific node_modules15+ transformIgnorePatterns: [`node_modules/(?!(${esmModules})/)`],16+};added:examples/using-esm-from-commonjs/jest-typescript/package.json+18 added
1+{2+ "name": "jest-typescript",3+ "version": "1.0.0",4+ "description": "",5+ "scripts": {6+ "test": "jest"7+ },8+ "license": "MIT",9+ "type": "commonjs",10+ "dependencies": {11+ "commander": "^15.0.0"12+ },13+ "devDependencies": {14+ "jest": "^30.2.0",15+ "ts-jest": "^29.4.6",16+ "typescript": "^5.9.3"17+ }18+}added:examples/using-esm-from-commonjs/jest-typescript/README.md+34 added
1+# Example configuration for Jest 30 running CommonJS from TypeScript2+3+This project shows using `ts-jest` to transform Commander ESM to CommonJS.4+5+Example error message when requiring ESM-only Commander in a Jest test with default configuration:6+7+```8+$ npm run --silent test9+ FAIL ./index.test.ts10+ ● Test suite failed to run11+12+ Jest encountered an unexpected token13+14+ Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.15+16+ [more detail omitted, check output for up-to-date suggestions]17+...18+ import { Command } from 'commander';19+ ^^^^^^20+21+ SyntaxError: Cannot use import statement outside a module22+...23+```24+25+Additional setup:26+27+- see two tweaks in `jest.config.js` to use `ts-jest` to convert Commander ESM to CommonJS28+29+Running test:30+31+```console32+npm install33+npm test34+```added:examples/using-esm-from-commonjs/jest-typescript/tsconfig.json+44 added
1+{2+ // Visit https://aka.ms/tsconfig to read more about this file3+ "compilerOptions": {4+ // File Layout5+ // "rootDir": "./src",6+ // "outDir": "./dist",7+8+ // Environment Settings9+ // See also https://aka.ms/tsconfig/module10+ "module": "nodenext",11+ "target": "esnext",12+ "types": [],13+ // For nodejs:14+ // "lib": ["esnext"],15+ // "types": ["node"],16+ // and npm install -D @types/node17+18+ // Other Outputs19+ "sourceMap": true,20+ "declaration": true,21+ "declarationMap": true,22+23+ // Stricter Typechecking Options24+ "noUncheckedIndexedAccess": true,25+ "exactOptionalPropertyTypes": true,26+27+ // Style Options28+ // "noImplicitReturns": true,29+ // "noImplicitOverride": true,30+ // "noUnusedLocals": true,31+ // "noUnusedParameters": true,32+ // "noFallthroughCasesInSwitch": true,33+ // "noPropertyAccessFromIndexSignature": true,34+35+ // Recommended Options36+ "strict": true,37+ "jsx": "react-jsx",38+ "verbatimModuleSyntax": false, // we want import to be output as require, not verbatim39+ "isolatedModules": true,40+ "noUncheckedSideEffectImports": true,41+ "moduleDetection": "force",42+ "skipLibCheck": true,43+ },44+}modified:examples/action-this.js+1 added-1 removed
1 #!/usr/bin/env node2 3 // This example is used as an example in the README for the action handler.4 5-const { Command } = require('commander');5+import { Command } from 'commander';6 const program = new Command();7 8 program9 .command('serve')10 unmodified linesadded:examples/alias.cjs+36 added
1+#!/usr/bin/env node2+3+// This example shows giving alternative names for a command.4+5+const { Command } = require('commander');6+const program = new Command();7+8+program9+ .command('exec')10+ .argument('<script>')11+ .alias('ex')12+ .action((script) => {13+ console.log(`execute: ${script}`);14+ });15+16+program17+ .command('print')18+ .argument('<file>')19+ // Multiple aliases is unusual but supported! You can call alias multiple times,20+ // and/or add multiple aliases at once. Only the first alias is displayed in the help.21+ .alias('p')22+ .alias('pr')23+ .aliases(['display', 'show'])24+ .action((file) => {25+ console.log(`print: ${file}`);26+ });27+28+program.parse();29+30+// Try the following:31+// node alias.cjs --help32+// node alias.cjs exec script33+// node alias.cjs ex script34+// node alias.cjs print file35+// node alias.cjs pr file36+// node alias.cjs show filedeleted:examples/alias.js-36 removed
1-#!/usr/bin/env node2-3-// This example shows giving alternative names for a command.4-5-const { Command } = require('commander');6-const program = new Command();7-8-program9- .command('exec')10- .argument('<script>')11- .alias('ex')12- .action((script) => {13- console.log(`execute: ${script}`);14- });15-16-program17- .command('print')18- .argument('<file>')19- // Multiple aliases is unusual but supported! You can call alias multiple times,20- // and/or add multiple aliases at once. Only the first alias is displayed in the help.21- .alias('p')22- .alias('pr')23- .aliases(['display', 'show'])24- .action((file) => {25- console.log(`print: ${file}`);26- });27-28-program.parse();29-30-// Try the following:31-// node alias.js --help32-// node alias.js exec script33-// node alias.js ex script34-// node alias.js print file35-// node alias.js pr file36-// node alias.js show filemodified:examples/argument.js+1 added-1 removed
1 #!/usr/bin/env node2 3 // This example shows specifying the command arguments using argument() function.4 5-const { Command } = require('commander');5+import { Command } from 'commander';6 const program = new Command();7 8 program9 .name('connect')14 unmodified linesmodified:examples/arguments-custom-processing.js+3 added-3 removed
2 unmodified lines3 // This is used as an example in the README for:4 // Custom argument processing5 // You may specify a function to do custom processing of argument values.6 7-const commander = require('commander');8-const program = new commander.Command();7+import { Command, InvalidArgumentError } from 'commander';8+const program = new Command();9 10 function myParseInt(value) {11 // parseInt takes a string and a radix12 const parsedValue = parseInt(value, 10);13 if (isNaN(parsedValue)) {14- throw new commander.InvalidArgumentError('Not a number.');14+ throw new InvalidArgumentError('Not a number.');15 }16 return parsedValue;17 }18 28 unmodified linesmodified:examples/arguments-extra.js+4 added-7 removed
1 #!/usr/bin/env node2 3 // This is used as an example in the README for extra argument features.4 5-const commander = require('commander');6-const program = new commander.Command();5+import { Command, Argument } from 'commander';6+const program = new Command();7 8 program9 .addArgument(10- new commander.Argument('<drink-size>', 'drink cup size').choices([10+ new Argument('<drink-size>', 'drink cup size').choices([11 'small',12 'medium',13 'large',14 ]),15 )16 .addArgument(17- new commander.Argument('[timeout]', 'timeout in seconds').default(18- 60,19- 'one minute',20- ),17+ new Argument('[timeout]', 'timeout in seconds').default(60, 'one minute'),18 )19 .action((drinkSize, timeout) => {20 console.log(`Drink size: ${drinkSize}`);21 console.log(`Timeout (s): ${timeout}`);9 unmodified linesmodified:examples/configure-help.js+2 added-2 removed
1-const commander = require('commander');2-const program = new commander.Command();1+import { Command } from 'commander';2+const program = new Command();3 4 // This example shows a simple use of configureHelp.5 // This is used as an example in the README.6 // Any method on the Help class can be overridden24 unmodified linesmodified:examples/configure-output.js+2 added-2 removed
1-const commander = require('commander');2-const program = new commander.Command();1+import { Command } from 'commander';2+const program = new Command();3 4 function errorColor(str) {5 // Add ANSI escape codes to display text in red.6 return `\x1b[31m${str}\x1b[0m`;19 unmodified linesmodified:examples/custom-command-class.js+3 added-3 removed
1 #!/usr/bin/env node2-const commander = require('commander');2+import { Command } from 'commander';3 4 // Use a class override to customise the command and its subcommands.5 6-class CommandWithTrace extends commander.Command {6+class CommandWithTrace extends Command {7 createCommand(name) {8 const cmd = new CommandWithTrace(name);9 // Add an option to subcommands created using `.command()`10 cmd.option('-t, --trace', 'display extra information when run command');8 unmodified lines19 console.log('opts: %o', command.opts());20 }21 22 const program = new CommandWithTrace('program')23- .option('-v, ---verbose')23+ .option('-v, --verbose')24 .action((options, command) => {25 inspectCommand(command);26 });27 19 unmodified linesmodified:examples/custom-help+1 added-1 removed
1 unmodified line2 3 // This example shows a simple use of addHelpText.4 // This is used as an example in the README.5 6-const { Command } = require('commander');6+import { Command } from 'commander';7 const program = new Command();8 9 program.option('-f, --foo', 'enable some foo');10 12 unmodified linesmodified:examples/custom-help-description+1 added-1 removed
1 #!/usr/bin/env node2 3 // This example shows changing the flags and description for the help option.4 5-const { Command } = require('commander');5+import { Command } from 'commander';6 const program = new Command();7 8 program9 .helpOption('-c, --HELP', 'custom help message')15 unmodified linesmodified:examples/custom-help-text.js+1 added-1 removed
1 #!/usr/bin/env node2 3 // This example shows using addHelpText.4 5-const { Command } = require('commander');5+import { Command } from 'commander';6 const program = new Command();7 8 program.name('awesome');9 26 unmodified linesmodified:examples/custom-version+1 added-1 removed
1 #!/usr/bin/env node2 3 // This example shows changing the flags and description for the version option.4 5-const { Command } = require('commander');5+import { Command } from 'commander';6 const program = new Command();7 8 program9 .version('0.0.1', '-v, --VERSION', 'new version message')8 unmodified linesmodified:examples/defaultCommand.js+2 added-2 removed
1 #!/usr/bin/env node2 3-const commander = require('commander');4-const program = new commander.Command();3+import { Command } from 'commander';4+const program = new Command();5 6 // Example program using the command configuration option isDefault to specify the default command.7 8 program27 unmodified linesmodified:examples/deploy+1 added-1 removed
1 #!/usr/bin/env node2 3-const { Command } = require('commander');3+import { Command } from 'commander';4 const program = new Command();5 6 program7 .name('deploy')36 unmodified linesmodified:examples/description+1 added-1 removed
1 #!/usr/bin/env node2 3 // This example shows adding a description which is displayed in the help.4 5-const { Command } = require('commander');5+import { Command } from 'commander';6 const program = new Command();7 8 program9 .version('0.0.1')14 unmodified linesmodified:examples/global-options-added.js+1 added-1 removed
7 unmodified lines8 //9 // (A different pattern for a "global" option is to add it to the root command, rather10 // than to the subcommand. See global-options-nested.js.)11 12-const { Command } = require('commander');12+import { Command } from 'commander';13 14 // Common options can be added when subcommands are created by using a custom subclass.15 // If the options are unsorted in the help, these will appear first.16 class MyRootCommand extends Command {36 unmodified linesmodified:examples/global-options-nested.js+1 added-1 removed
4 unmodified lines5 //6 // (A different pattern for a "global" option is to add it to the subcommands, rather7 // than to the program. See global-options-added.js.)8 9-const { Command } = require('commander');9+import { Command } from 'commander';10 const program = new Command();11 12 program.configureHelp({ showGlobalOptions: true }).option('-g, --global');13 15 unmodified linesmodified:examples/help-groups.js+1 added-1 removed
1-const { Command, Option } = require('commander');1+import { Command, Option } from 'commander';2 3 // Show the two approaches for adding help groups, and how to customise the built-in help and version.4 5 const program = new Command();70 unmodified linesmodified:examples/help-subcommands-usage.js+2 added-2 removed
1-const commander = require('commander');1+import { Command } from 'commander';2 3 // By default the subcommand list includes a fairly simple usage. If you have added a custom usage4 // to the subcommands you may wish to configure the help to show these instead.5 //6 // See also ./configure-help.js which shows configuring the subcommand list to have no usage at all7 // and just the subcommand name.8 9-const program = new commander.Command().configureHelp({9+const program = new Command().configureHelp({10 subcommandTerm: (cmd) => cmd.name() + ' ' + cmd.usage(),11 });12 13 program20 unmodified linesmodified:examples/hook.js+1 added-1 removed
1 #!/usr/bin/env node2 3-const { Command, Option } = require('commander');3+import { Command, Option } from 'commander';4 const program = new Command();5 6 // This example shows using some hooks for life cycle events.7 64 unmodified linesmodified:examples/nestedCommands.js+3 added-3 removed
1 #!/usr/bin/env node2 3-const commander = require('commander');4-const program = new commander.Command();3+import { Command } from 'commander';4+const program = new Command();5 6 // Commander supports nested subcommands.7 // .command() can add a subcommand with an action handler or an executable.8 // .addCommand() adds a prepared command with an action handler.9 unmodified lines18 19 // Add nested commands using `.addCommand().20 // The command could be created separately in another module.21 function makeHeatCommand() {22- const heat = new commander.Command('heat');22+ const heat = new Command('heat');23 heat.command('jug').action(() => {24 console.log('heat jug');25 });26 heat.command('pot').action(() => {11 unmodified linesmodified:examples/options-boolean-or-value.js+2 added-2 removed
2 unmodified lines3 // This is used as an example in the README for:4 // Other option types, flag|value5 // You can specify an option which functions as a flag but may also take a value (declared using square brackets).6 7-const commander = require('commander');8-const program = new commander.Command();7+import { Command } from 'commander';8+const program = new Command();9 10 program.option('-c, --cheese [type]', 'Add cheese with optional type');11 12 program.parse(process.argv);10 unmodified linesmodified:examples/options-common.js+2 added-2 removed
1 unmodified line2 3 // This is used as an example in the README for:4 // Common option types, boolean and value5 6-const commander = require('commander');7-const program = new commander.Command();6+import { Command } from 'commander';7+const program = new Command();8 9 program10 .option('-d, --debug', 'output extra debugging')11 .option('-s, --small', 'small pizza size')14 unmodified linesmodified:examples/options-conflicts.js+1 added-1 removed
1 #!/usr/bin/env node2-const { Command, Option } = require('commander');2+import { Command, Option } from 'commander';3 const program = new Command();4 5 // You can use .conflicts() with a single string, which is the camel-case name of the conflicting option.6 program80 unmodified linesmodified:examples/options-custom-processing.js+3 added-3 removed
2 unmodified lines3 // This is used as an example in the README for:4 // Custom option processing5 // You may specify a function to do custom processing of option values.6 7-const commander = require('commander');8-const program = new commander.Command();7+import { Command, InvalidArgumentError } from 'commander';8+const program = new Command();9 10 function myParseInt(value) {11 // parseInt takes a string and a radix12 const parsedValue = parseInt(value, 10);13 if (isNaN(parsedValue)) {14- throw new commander.InvalidArgumentError('Not a number.');14+ throw new InvalidArgumentError('Not a number.');15 }16 return parsedValue;17 }18 39 unmodified linesmodified:examples/options-defaults.js+2 added-2 removed
1 unmodified line2 3 // This is used as an example in the README for:4 // Default option value5 6-const commander = require('commander');7-const program = new commander.Command();6+import { Command } from 'commander';7+const program = new Command();8 9 program.option(10 '-c, --cheese <type>',11 'Add the specified type of cheese',10 unmodified linesmodified:examples/options-env.js+1 added-1 removed
1 #!/usr/bin/env node2-const { Command, Option } = require('commander');2+import { Command, Option } from 'commander';3 const program = new Command();4 5 program.addOption(6 new Option('-p, --port <number>', 'specify port number')33 unmodified linesmodified:examples/options-extra.js+1 added-1 removed
2 unmodified lines3 // This is used as an example in the README for extra option features.4 // See also options-env.js for more extensive env examples,5 // and options-conflicts.js for more details about .conflicts().6 7-const { Command, Option } = require('commander');7+import { Command, Option } from 'commander';8 const program = new Command();9 10 program11 .addOption(new Option('-s, --secret').hideHelp())40 unmodified linesmodified:examples/options-implies.js+1 added-1 removed
1 #!/usr/bin/env node2-const { Command, Option } = require('commander');2+import { Command, Option } from 'commander';3 const program = new Command();4 5 program6 .addOption(new Option('--quiet').implies({ logLevel: 'off' }))27 unmodified linesmodified:examples/options-negatable.js+2 added-2 removed
2 unmodified lines3 // This is used as an example in the README for:4 // Other option types, negatable boolean5 // You can specify a boolean option long name with a leading `no-` to make it true by default and able to be negated.6 7-const commander = require('commander');8-const program = new commander.Command();7+import { Command } from 'commander';8+const program = new Command();9 10 program11 .option('--no-sauce', 'Remove sauce')12 .option('--cheese <flavour>', 'cheese flavour', 'mozzarella')15 unmodified linesmodified:examples/options-required.js+2 added-2 removed
3 unmodified lines4 // Required option5 // You may specify a required (mandatory) option using `.requiredOption`.6 // The option must be specified on the command line, or by having a default value.7 8-const commander = require('commander');9-const program = new commander.Command();8+import { Command } from 'commander';9+const program = new Command();10 11 program.requiredOption('-c, --cheese <type>', 'pizza must have cheese');12 13 program.parse();6 unmodified linesmodified:examples/options-variadic.js+2 added-2 removed
1 #!/usr/bin/env node2 3 // This is used as an example in the README for variadic options.4 5-const commander = require('commander');6-const program = new commander.Command();5+import { Command } from 'commander';6+const program = new Command();7 8 program9 .option('-n, --number <value...>', 'specify numbers')10 .option('-l, --letter [value...]', 'specify letters');10 unmodified linesmodified:examples/pass-through-options.js+1 added-1 removed
1 #!/usr/bin/env node2 3-const { Command } = require('commander');3+import { Command } from 'commander';4 const program = new Command();5 6 program7 .argument('<utility>')15 unmodified linesmodified:examples/pizza+2 added-2 removed
1 #!/usr/bin/env node2 3-const { Command } = require('commander');3+import { Command } from 'commander';4 const program = new Command();5 6 program7 .description('An application for pizza ordering')12 unmodified lines20 // Try the following on macOS or Linux:21 // ./pizza --help22 //23 // Try the following:24-// ./pizza --help24+// node pizza --help25 // node pizza --peppers --cheese=blue26 // node pizza --no-cheesemodified:examples/pm+1 added-1 removed
1 #!/usr/bin/env node2 3-const { Command } = require('commander');3+import { Command } from 'commander';4 const program = new Command();5 6 // Example of subcommands which are implemented as stand-alone executable files.7 //29 unmodified linesmodified:examples/pm-install+1 added-1 removed
1 #!/usr/bin/env node2 3-const { Command } = require('commander');3+import { Command } from 'commander';4 const program = new Command();5 6 program.option('-f, --force', 'force installation');7 program.argument('[package-names...]');16 unmodified linesmodified:examples/positional-options.js+1 added-1 removed
1 #!/usr/bin/env node2 3-const { Command } = require('commander');3+import { Command } from 'commander';4 const program = new Command();5 6 program.enablePositionalOptions().option('-p, --progress');7 16 unmodified linesmodified:examples/split.js+1 added-1 removed
1-const { program } = require('commander');1+import { program } from 'commander';2 3 // This is used as an example in the README for the Quick Start.4 5 program.option('--first').option('-s, --separator <char>').argument('<string>');11 unmodified linesmodified:examples/string-util.js+1 added-1 removed
1-const { Command } = require('commander');1+import { Command } from 'commander';2 const program = new Command();3 4 // This is used as an example in the README for the Quick Start.5 33 unmodified linesmodified:examples/thank.js+1 added-1 removed
1 #!/usr/bin/env node2 3 // This example is used as an example in the README for the action handler.4 5-const { Command } = require('commander');5+import { Command } from 'commander';6 const program = new Command();7 8 program9 .argument('<name>')16 unmodified linesmodified:lib/argument.js+3 added-6 removed
1-const { InvalidArgumentError } = require('./error.js');1+import { InvalidArgumentError } from './error.js';2 3-class Argument {3+export class Argument {4 /**5 * Initialize a new command argument with the given name and description.6 * The default is that the argument is required, and you can explicitly7 * indicate this with <> around the name. Put [] around the name for an optional argument.131 unmodified lines139 * @return {string}140 * @private141 */142 143-function humanReadableArgName(arg) {143+export function humanReadableArgName(arg) {144 const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');145 146 return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';147 }148-149-exports.Argument = Argument;150-exports.humanReadableArgName = humanReadableArgName;modified:lib/command.js+17 added-18 removed
1-const EventEmitter = require('node:events').EventEmitter;2-const childProcess = require('node:child_process');3-const path = require('node:path');4-const fs = require('node:fs');5-const process = require('node:process');1+import { EventEmitter } from 'node:events';2+import childProcess from 'node:child_process';3+import path from 'node:path';4+import fs from 'node:fs';5+import process from 'node:process';6 7-const { Argument, humanReadableArgName } = require('./argument.js');8-const { CommanderError } = require('./error.js');9-const { Help, stripColor } = require('./help.js');10-const { Option, DualOptions } = require('./option.js');11-const { suggestSimilar } = require('./suggestSimilar');7+import { Argument, humanReadableArgName } from './argument.js';8+import { CommanderError } from './error.js';9+import { Help, stripColor } from './help.js';10+import { Option, DualOptions } from './option.js';11+import { suggestSimilar } from './suggestSimilar.js';12 13-class Command extends EventEmitter {13+export class Command extends EventEmitter {14 /**15 * Initialize a new `Command`.16 *17 * @param {string} [name]2400 unmodified lines2418 }2419 2420 /**2421 * Set the name of the command from script filename, such as process.argv[1],2422- * or require.main.filename, or __filename.2422+ * or import.meta.filename.2423 *2424 * (Used internally and public although not documented in README.)2425 *2426 * @example2427- * program.nameFromFilename(require.main.filename);2427+ * program.nameFromFilename(import.meta.filename);2428 *2429 * @param {string} filename2430 * @return {Command}2431 */7 unmodified lines2439 /**2440 * Get or set the directory for searching for executable subcommands of this command.2441 *2442 * @example2443- * program.executableDir(__dirname);2443+ * program.executableDir(import.meta.dirname);2444 * // or2445 * program.executableDir('subcommands');2446 *2447 * @param {string} [path]311 unmodified lines2759 });2760 }2761 2762 /**2763+ * Exported for using from tests, not otherwise used outside this file.2764+ *2765 * @returns {boolean | undefined}2766 * @package2767 */2766-function useColor() {2768+export function useColor() {2769 // Test for common conventions.2770 // NB: the observed behaviour is in combination with how author adds color! For example:2771 // - we do not test NODE_DISABLE_COLORS, but util:styletext does2772 // - we do test NO_COLOR, but Chalk does not14 unmodified lines2787 if (process.env.FORCE_COLOR || process.env.CLICOLOR_FORCE !== undefined)2788 return true;2789 return undefined;2790 }2789-2790-exports.Command = Command;2791-exports.useColor = useColor; // exporting for testsmodified:lib/error.js+2 added-5 removed
1 /**2 * CommanderError class3 */4-class CommanderError extends Error {4+export class CommanderError extends Error {5 /**6 * Constructs the CommanderError class7 * @param {number} exitCode suggested exit code which could be used with process.exit8 * @param {string} code an id string representing the error12 unmodified lines21 22 /**23 * InvalidArgumentError class24 */25-class InvalidArgumentError extends CommanderError {25+export class InvalidArgumentError extends CommanderError {26 /**27 * Constructs the InvalidArgumentError class28 * @param {string} [message] explanation of why argument is invalid29 */3 unmodified lines33 Error.captureStackTrace(this, this.constructor);34 this.name = this.constructor.name;35 }36 }37-38-exports.CommanderError = CommanderError;39-exports.InvalidArgumentError = InvalidArgumentError;modified:lib/help.js+3 added-6 removed
1-const { humanReadableArgName } = require('./argument.js');1+import { humanReadableArgName } from './argument.js';2 3 /**4 * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`5 * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types2 unmodified lines8 * @typedef { import("./option.js").Option } Option9 */10 11 // Although this is a class, methods are static in style to allow override using subclass or just functions.12-class Help {12+export class Help {13 constructor() {14 this.helpWidth = undefined;15 this.minWidthToWrap = 40;16 this.sortSubcommands = false;719 unmodified lines736 * @returns {string}737 * @package738 */739 740-function stripColor(str) {740+export function stripColor(str) {741 // eslint-disable-next-line no-control-regex742 const sgrPattern = /\x1b\[\d*(;\d*)*m/g;743 return str.replace(sgrPattern, '');744 }745-746-exports.Help = Help;747-exports.stripColor = stripColor;modified:lib/option.js+3 added-6 removed
1-const { InvalidArgumentError } = require('./error.js');1+import { InvalidArgumentError } from './error.js';2 3-class Option {3+export class Option {4 /**5 * Initialize a new `Option` with the given `flags` and `description`.6 *7 * @param {string} flags256 unmodified lines264 * like `--build` and `--no-build`, which share a single option value. This works nicely for some265 * use cases, but is tricky for others where we want separate behaviours despite266 * the single shared option value.267 */268-class DualOptions {268+export class DualOptions {269 /**270 * @param {Option[]} options271 */272 constructor(options) {101 unmodified lines374 );375 376 return { shortFlag, longFlag };377 }378-379-exports.Option = Option;380-exports.DualOptions = DualOptions;modified:lib/suggestSimilar.js+1 added-3 removed
51 unmodified lines52 * @param {string[]} candidates53 * @returns {string}54 */55 56-function suggestSimilar(word, candidates) {56+export function suggestSimilar(word, candidates) {57 if (!candidates || candidates.length === 0) return '';58 // remove possible duplicates59 candidates = Array.from(new Set(candidates));60 35 unmodified lines96 return `\n(Did you mean ${similar[0]}?)`;97 }98 return '';99 }100-101-exports.suggestSimilar = suggestSimilar;modified:tests/fixtures/inspect-sub.js+1 added-1 removed
1-console.log(process.execArgv);1+console.log(JSON.stringify(process.execArgv));modified:tests/fixtures/inspect.js+1 added-3 removed
1 #!/usr/bin/env node2 3-const { program } = require('../../');3+import { program } from '../../index.js';4 5-process.env.FORCE_COLOR = 0; // work-around bug in Jest: https://github.com/jestjs/jest/issues/143916-5 program.command('sub', 'install one or more packages').parse(process.argv);modified:tests/fixtures/pm+4 added-6 removed
1 #!/usr/bin/env node2 3-const path = require('node:path');4-const { program } = require('../../');3+import * as path from 'node:path';4+import { program } from '../../index.js';5 6-process.env.FORCE_COLOR = 0; // work-around bug in Jest: https://github.com/jestjs/jest/issues/143917-6 program7 .version('0.0.1')8 .command('install [name]', 'install one or more packages')9 .alias('i')24 unmodified lines34 .exitOverride((err) => {35 process.exit(err.exitCode);36 })37 .command('fail', 'exit with non-zero status code', {40- executableFile: path.join(__dirname, 'pm-fail.js'),38+ executableFile: path.join(import.meta.dirname, 'pm-fail.js'),39 })40 .command('terminate', 'terminate due to signal', {43- executableFile: path.join(__dirname, 'pm-terminate.js'),41+ executableFile: path.join(import.meta.dirname, 'pm-terminate.js'),42 });43 44 program.parse(process.argv);modified:tests/fixtures/pm-cache.js+1 added-1 removed
1-const { program } = require('../../');1+import { program } from '../../index.js';2 3 program4 .command('clear', 'clear the cache')5 .command('validate', 'validate the cache', { isDefault: true })1 unmodified linemodified:tests/fixtures/pm-default+1 added-1 removed
1 #!/usr/bin/env node2 console.log('default');3 if (process.argv.length > 2) {4- console.log(process.argv.slice(2));4+ console.log(JSON.stringify(process.argv.slice(2)));5 }modified:tests/fixtures/pm-echo.js+1 added-1 removed
1-console.log(process.argv.slice(2));1+console.log(JSON.stringify(process.argv.slice(2)));modified:tests/fixtures-extensions/pm.js+1 added-1 removed
1 #!/usr/bin/env node2 3-const { program } = require('../../');3+import { program } from '../../index.js';4 5 program6 .command('try-ts', 'test file extension lookup')7 .command('try-cjs', 'test file extension lookup')2 unmodified linesmodified:tests/args.literal.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Utility Conventions: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html#tag_12_026 //7 // 12.2 Utility Syntax Guidelines, Guideline 10:27 unmodified linesmodified:tests/args.variadic.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Testing variadic arguments.6 7 describe('Command variadic argument using .arguments() or .command()', () => {71 unmodified linesmodified:tests/argument.chain.test.js+3 added-3 removed
1-const { Argument } = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import { Argument } from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 describe('Argument methods that should return this for chaining', () => {6 test('when call .default() then returns this', () => {7 const argument = new Argument('<value>');28 unmodified linesmodified:tests/argument.choices.test.js+4 added-4 removed
1-const commander = require('../');2-const { createTestCommand } = require('./testHelpers');3-const { test, describe } = require('node:test');4-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { createTestCommand } from './testHelpers.js';3+import { test, describe } from 'node:test';4+import assert from 'node:assert/strict';5 6 describe('Argument.choices()', () => {7 test('when command argument in choices then argument set', () => {8 const program = createTestCommand();49 unmodified linesmodified:tests/argument.custom-processing.test.js+4 added-4 removed
1-const commander = require('../');2-const { createTestCommand } = require('./testHelpers');3-const { test, describe } = require('node:test');4-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { createTestCommand } from './testHelpers.js';3+import { test, describe } from 'node:test';4+import assert from 'node:assert/strict';5 6 // Testing default value and custom processing behaviours.7 // Some double assertions in tests to check action argument and .processedArg8 187 unmodified linesmodified:tests/argument.required.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Low-level tests of setting Argument.required.6 // Higher level tests of optional/required arguments elsewhere.7 31 unmodified linesmodified:tests/argument.variadic.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Testing variadic arguments. Testing all the action arguments, but could test just variadicArg.6 7 describe('Command variadic argument using .argument()', (t) => {113 unmodified linesmodified:tests/command.action.test.js+4 added-4 removed
1-const commander = require('../');2-const { createTestCommand } = require('./testHelpers');3-const { test, describe } = require('node:test');4-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { createTestCommand } from './testHelpers.js';3+import { test, describe } from 'node:test';4+import assert from 'node:assert/strict';5 6 // Test some behaviours of .action not covered in more specific tests.7 8 describe('Command.action()', () => {158 unmodified linesmodified:tests/command.addCommand.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 describe('Command.addCommand()', () => {6 // simple sanity check subcommand works7 test('when addCommand and specify subcommand then called', (t) => {54 unmodified linesmodified:tests/command.addHelpOption.test.js+4 added-4 removed
1-const { Option } = require('../');2-const { createTestCommand } = require('./testHelpers');3-const { test, describe } = require('node:test');4-const assert = require('node:assert/strict');1+import { Option } from '../index.js';2+import { createTestCommand } from './testHelpers.js';3+import { test, describe } from 'node:test';4+import assert from 'node:assert/strict';5 6 // More complete tests are in command.helpOption.test.js.7 8 describe('Command.addHelpOption()', () => {33 unmodified linesmodified:tests/command.addHelpText.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe, beforeEach } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe, beforeEach } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Using outputHelp to simplify testing.6 7 describe('Command.addHelpText(): program calls to addHelpText', () => {232 unmodified linesmodified:tests/command.alias.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Running alias commands is tested in command.executableSubcommand.lookup.test.js6 // Test various other behaviours for .alias7 103 unmodified linesmodified:tests/command.allowExcessArguments.test.js+3 added-3 removed
1-const { createTestCommand } = require('./testHelpers');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import { createTestCommand } from './testHelpers.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Not testing output, just testing whether an error is detected.6 7 describe('Command.allowExcessArguments()', () => {108 unmodified linesmodified:tests/command.allowUnknownOption.test.js+3 added-3 removed
1-const { createTestCommand } = require('./testHelpers');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import { createTestCommand } from './testHelpers.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Not testing output, just testing whether an error is detected.6 7 describe('Command.allowUnknownOption()', () => {72 unmodified linesmodified:tests/command.argumentVariations.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Do some low-level checks that the multiple ways of specifying command arguments produce same internal result,6 // and not exhaustively testing all methods elsewhere.7 128 unmodified linesmodified:tests/command.asterisk.test.js+4 added-4 removed
1-const commander = require('../');2-const { createTestCommand } = require('./testHelpers');3-const { test, describe } = require('node:test');4-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { createTestCommand } from './testHelpers.js';3+import { test, describe } from 'node:test';4+import assert from 'node:assert/strict';5 6 // .command('*') is the old main/default command handler. It adds a listener7 // for 'command:*'. It has been somewhat replaced by the program action handler,8 // so most uses are probably old code. Current plan is keep the code backwards compatible126 unmodified linesmodified:tests/command.chain.test.js+3 added-3 removed
1-const { Command, Option, Argument } = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import { Command, Option, Argument } from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Testing the functions which should chain.6 // parse and parseAsync are tested in command.parse.test.js7 273 unmodified linesmodified:tests/command.commandHelp.test.js+3 added-3 removed
1-const commander = require('../');2-const { test } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test } from 'node:test';3+import assert from 'node:assert/strict';4 5 // This is a ported legacy test.6 7 test('when program has command then appears in help', () => {12 unmodified linesmodified:tests/command.configureHelp.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 describe('Command.configureHelp()', () => {6 test('when configure program then affects program helpInformation', () => {7 const program = new commander.Command();36 unmodified linesmodified:tests/command.configureOutput.test.js+4 added-4 removed
1-const { test, describe } = require('node:test');2-const assert = require('node:assert/strict');3-const commander = require('../');4-const process = require('node:process');1+import { test, describe } from 'node:test';2+import assert from 'node:assert/strict';3+import * as commander from '../index.js';4+import process from 'node:process';5 6 describe('Command.configureOutput()', () => {7 test('when default writeErr() then error on stderr', (t) => {8 const writeSpy = t.mock.method(process.stderr, 'write', () => {});337 unmodified linesmodified:tests/command.copySettings.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Tests some private properties as simpler than pure tests of observable behaviours.6 // Testing before and after values in some cases, to ensure value actually changes (when copied).7 143 unmodified linesmodified:tests/command.createArgument.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 class MyArgument extends commander.Argument {6 constructor(name, description) {7 super(name, description);37 unmodified linesmodified:tests/command.createHelp.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 describe('Command.createHelp() override in subclass', () => {6 test('when override createCommand then affects help', () => {7 class MyHelp extends commander.Help {15 unmodified linesmodified:tests/command.createOption.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 class MyOption extends commander.Option {6 constructor(flags, description) {7 super(flags, description);39 unmodified linesmodified:tests/command.default.test.js+9 added-9 removed
1-const childProcess = require('child_process');2-const commander = require('../');3-const path = require('path');4-const util = require('util');5-const { test, describe } = require('node:test');6-const assert = require('node:assert/strict');1+import * as childProcess from 'child_process';2+import * as commander from '../index.js';3+import * as path from 'path';4+import * as util from 'util';5+import { test, describe } from 'node:test';6+import assert from 'node:assert/strict';7 8 const execFileAsync = util.promisify(childProcess.execFile);9 10 describe('default executable command', () => {11 // Calling node explicitly so pm works without file suffix cross-platform.12- const pm = path.join(__dirname, './fixtures/pm');12+ const pm = path.join(import.meta.dirname, './fixtures/pm');13 14 test('when default subcommand and no command then call default', async () => {15 const { stdout } = await execFileAsync('node', [pm]);16 assert.equal(stdout, 'default\n');17 });18 19 test('when default subcommand and unrecognised argument then call default with argument', async () => {20 const { stdout } = await execFileAsync('node', [pm, 'an-argument']);21- assert.equal(stdout, "default\n[ 'an-argument' ]\n");21+ assert.equal(stdout, 'default\n["an-argument"]\n');22 });23 24 test('when default subcommand and unrecognised option then call default with option', async () => {25 const { stdout } = await execFileAsync('node', [pm, '--an-option']);26- assert.equal(stdout, "default\n[ '--an-option' ]\n");26+ assert.equal(stdout, 'default\n["--an-option"]\n');27 });28 });29 30 describe('default action command', () => {63 unmodified linesmodified:tests/command.description.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 describe('Command description()', () => {6 test('when set description then get description', () => {7 const program = new commander.Command();5 unmodified linesmodified:tests/command.error.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 describe('Command.error()', () => {6 test('when error called with message then message displayed on stderr', (t) => {7 t.mock.method(process, 'exit', () => {});52 unmodified linesmodified:tests/command.executableSubcommand.inspect.test.js+17 added-13 removed
1-const childProcess = require('child_process');2-const path = require('path');3-const util = require('util');4-const { test, describe } = require('node:test');5-const assert = require('node:assert/strict');1+import * as childProcess from 'child_process';2+import * as path from 'path';3+import * as util from 'util';4+import { test, describe } from 'node:test';5+import assert from 'node:assert/strict';6 7 const execFileAsync = util.promisify(childProcess.execFile);8 9 // Test the special handling for --inspect to increment fixed debug port numbers.10 // If we reuse port we can get conflicts because port not released fast enough.11 12-const inspectCommand = path.join(__dirname, './fixtures', 'inspect.js');12+const inspectCommand = path.join(13+ import.meta.dirname,14+ './fixtures',15+ 'inspect.js',16+);17 18 describe('executable subcommand support for --inspect ', () => {19 test('when execArgv empty then spawn execArgs empty', async () => {20 const { stdout } = await execFileAsync('node', [inspectCommand, 'sub']);5 unmodified lines26 '--harmony',27 inspectCommand,28 'sub',29 ]);26- assert.equal(stdout, "[ '--harmony' ]\n");30+ assert.equal(stdout, '["--harmony"]\n');31 });32 33 // --inspect defaults to 127.0.0.1:9229, port should be incremented34 test('when execArgv --inspect then spawn execArgs using port 9230', async () => {1 unmodified line36 '--inspect',37 inspectCommand,38 'sub',39 ]);36- assert.equal(stdout, "[ '--inspect=127.0.0.1:9230' ]\n");40+ assert.equal(stdout, '["--inspect=127.0.0.1:9230"]\n');41 });42 43 // custom port44 test('when execArgv --inspect=9240 then spawn execArgs using port 9241', async () => {1 unmodified line46 '--inspect=9240',47 inspectCommand,48 'sub',49 ]);46- assert.equal(stdout, "[ '--inspect=127.0.0.1:9241' ]\n");50+ assert.equal(stdout, '["--inspect=127.0.0.1:9241"]\n');51 });52 53 // zero is special, random port54 test('when execArgv --inspect=0 then spawn execArgs --inspect=0', async () => {1 unmodified line56 '--inspect=0',57 inspectCommand,58 'sub',59 ]);56- assert.equal(stdout, "[ '--inspect=0' ]\n");60+ assert.equal(stdout, '["--inspect=0"]\n');61 });62 63 // ip address64 test('when execArgv --inspect=127.0.0.1:9250 then spawn execArgs --inspect=127.0.0.1:9251', async () => {1 unmodified line66 '--inspect=127.0.0.1:9250',67 inspectCommand,68 'sub',69 ]);66- assert.equal(stdout, "[ '--inspect=127.0.0.1:9251' ]\n");70+ assert.equal(stdout, '["--inspect=127.0.0.1:9251"]\n');71 });72 73 // localhost74 test('when execArgv --inspect=localhost:9260 then spawn execArgs --inspect=localhost:9261', async () => {1 unmodified line76 '--inspect=localhost:9260',77 inspectCommand,78 'sub',79 ]);76- assert.equal(stdout, "[ '--inspect=localhost:9261' ]\n");80+ assert.equal(stdout, '["--inspect=localhost:9261"]\n');81 });82 83 // --inspect-port, just test most likely format84 test('when execArgv --inspect-port=9270 then spawn execArgs --inspect-port=127.0.0.1:9271', async () => {1 unmodified line86 '--inspect-port=9270',87 inspectCommand,88 'sub',89 ]);86- assert.equal(stdout, "[ '--inspect-port=127.0.0.1:9271' ]\n");90+ assert.equal(stdout, '["--inspect-port=127.0.0.1:9271"]\n');91 });92 });modified:tests/command.executableSubcommand.lookup.test.js+30 added-12 removed
1-const childProcess = require('child_process');2-const path = require('path');3-const util = require('util');1+import * as childProcess from 'child_process';2+import * as path from 'path';3+import * as util from 'util';4 const execFileAsync = util.promisify(childProcess.execFile);5-const { test, describe } = require('node:test');6-const assert = require('node:assert/strict');5+import { test, describe } from 'node:test';6+import assert from 'node:assert/strict';7 8 // Calling node explicitly so pm works without file suffix cross-platform.9 // This file does end-to-end tests actually spawning program.10 // See also command.executableSubcommand.search.test.js11 12 // Suppress false positive warnings due to use of testOrSkipOnWindows13 14 const testOrSkipOnWindows = process.platform === 'win32' ? test.skip : test;15-const pm = path.join(__dirname, './fixtures/pm');15+const pm = path.join(import.meta.dirname, './fixtures/pm');16 17 describe('executable subcommand lookup ', () => {18 test('when subcommand file missing then error', () => {19 return execFileAsync('node', [pm, 'list']).catch((err) => {49 unmodified lines69 70 testOrSkipOnWindows(71 'when subcommand file is symlink then lookup succeeds',72 async () => {73- const pmlink = path.join(__dirname, 'fixtures', 'pmlink');73+ const pmlink = path.join(import.meta.dirname, 'fixtures', 'pmlink');74 const { stdout } = await execFileAsync('node', [pmlink, 'install']);75 assert.equal(stdout, 'install\n');76 },77 );78 79 testOrSkipOnWindows(80 'when subcommand file is double symlink then lookup succeeds',81 async () => {82- const pmlink = path.join(__dirname, 'fixtures', 'another-dir', 'pm');82+ const pmlink = path.join(83+ import.meta.dirname,84+ 'fixtures',85+ 'another-dir',86+ 'pm',87+ );88 const { stdout } = await execFileAsync('node', [pmlink, 'install']);89 assert.equal(stdout, 'install\n');90 },91 );92 93+ // This test currently fails on Node 20 when run as ESM because Node does not execute .ts files as JavaScript by default.88- test('when subcommand suffix is .ts then lookup succeeds', async () => {94+ test.skip('when subcommand suffix is .ts then lookup succeeds', async () => {95 // We support looking for ts files for ts-node in particular, but don't need to test ts-node itself.96 // The subcommand is both plain JavaScript code for this test.91- const binLinkTs = path.join(__dirname, 'fixtures-extensions', 'pm.js');97+ const binLinkTs = path.join(98+ import.meta.dirname,99+ 'fixtures-extensions',100+ 'pm.js',101+ );102 // childProcess.execFile('node', ['-r', 'ts-node/register', binLinkTs, 'install'], function(_error, stdout, stderr) {103 const { stdout } = await execFileAsync('node', [binLinkTs, 'try-ts']);104 assert.equal(stdout, 'found .ts\n');105 });106 107 test('when subcommand suffix is .cjs then lookup succeeds', async () => {98- const binLinkTs = path.join(__dirname, 'fixtures-extensions', 'pm.js');108+ const binLinkTs = path.join(109+ import.meta.dirname,110+ 'fixtures-extensions',111+ 'pm.js',112+ );113 const { stdout } = await execFileAsync('node', [binLinkTs, 'try-cjs']);114 assert.equal(stdout, 'found .cjs\n');115 });116 117 test('when subcommand suffix is .mjs then lookup succeeds', async () => {104- const binLinkTs = path.join(__dirname, 'fixtures-extensions', 'pm.js');118+ const binLinkTs = path.join(119+ import.meta.dirname,120+ 'fixtures-extensions',121+ 'pm.js',122+ );123 const { stdout } = await execFileAsync('node', [binLinkTs, 'try-mjs']);124 assert.equal(stdout, 'found .mjs\n');125 });126 5 unmodified linesadded:tests/command.executableSubcommand.mock.test.cjs+103 added
1+const commander = require('../');2+const childProcess = require('child_process');3+const EventEmitter = require('events');4+const { test, describe } = require('node:test');5+const assert = require('node:assert/strict');6+7+// Using mocking of child_process.spawn. Not fully supported yet in esm by node:test so run as cjs.8+9+// Using mock to allow try/catch around what is otherwise out-of-stack error handling.10+// Injecting errors, these are not end-to-end tests.11+12+function makeSystemError(code) {13+ // We can not make an actual SystemError, but our usage is lightweight so easy to match.14+ const err = new Error();15+ err.code = code;16+ return err;17+}18+19+// Suppress false positive warnings due to use of testOrSkipOnWindows20+21+const testOrSkipOnWindows = process.platform === 'win32' ? test.skip : test;22+23+describe('executable subcommand missing file handling ', () => {24+ testOrSkipOnWindows(25+ 'when subcommand executable missing (ENOENT) then throw custom message',26+ (t) => {27+ // If the command is not found, we show a custom error with an explanation and offer28+ // some advice for possible fixes.29+ const mockProcess = new EventEmitter();30+ t.mock.method(childProcess, 'spawn', () => {31+ return mockProcess;32+ });33+ const program = new commander.Command();34+ program.exitOverride();35+ program.command('executable', 'executable description');36+ program.parse(['executable'], { from: 'user' });37+ assert.throws(() => {38+ mockProcess.emit('error', makeSystemError('ENOENT'));39+ }, /use the executableFile option to supply a custom name/); // part of custom message40+ },41+ );42+43+ testOrSkipOnWindows(44+ 'when subcommand executable not executable (EACCES) then throw custom message',45+ (t) => {46+ const mockProcess = new EventEmitter();47+ t.mock.method(childProcess, 'spawn', () => {48+ return mockProcess;49+ });50+ const program = new commander.Command();51+ program.exitOverride();52+ program.command('executable', 'executable description');53+ program.parse(['executable'], { from: 'user' });54+ assert.throws(() => {55+ mockProcess.emit('error', makeSystemError('EACCES'));56+ }, /not executable/); // part of custom message57+ },58+ );59+60+ test('when subcommand executable fails with other error and exitOverride then return in custom wrapper', (t) => {61+ // The existing behaviour is to just silently fail for unexpected errors, as it is happening62+ // asynchronously in spawned process and client can not catch errors.63+ const mockProcess = new EventEmitter();64+ t.mock.method(childProcess, 'spawn', () => {65+ return mockProcess;66+ });67+ const program = new commander.Command();68+ program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn69+ program.exitOverride((err) => {70+ throw err;71+ });72+ program.command('executable', 'executable description');73+ program.parse(['executable'], { from: 'user' });74+ assert.throws(75+ () => {76+ mockProcess.emit('error', makeSystemError('OTHER'));77+ },78+ (err) => {79+ assert.equal(err.code, 'commander.executeSubCommandAsync');80+ assert.equal(err.nestedError.code, 'OTHER');81+ return true;82+ },83+ );84+ });85+86+ test('when subcommand executable fails with other error then exit', (t) => {87+ // The existing behaviour is to just silently fail for unexpected errors, as it is happening88+ // asynchronously in spawned process and client can not catch errors.89+ const mockProcess = new EventEmitter();90+ t.mock.method(childProcess, 'spawn', () => {91+ return mockProcess;92+ });93+ const exitSpy = t.mock.method(process, 'exit', () => {});94+ const program = new commander.Command();95+ program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn96+ program.command('executable', 'executable description');97+ program.parse(['executable'], { from: 'user' });98+ mockProcess.emit('error', makeSystemError('OTHER'));99+ assert.equal(exitSpy.mock.callCount(), 1);100+ const callArgs = exitSpy.mock.calls[0].arguments;101+ assert.equal(callArgs[0], 1);102+ });103+});deleted:tests/command.executableSubcommand.mock.test.js-101 removed
1-const commander = require('../');2-const childProcess = require('child_process');3-const EventEmitter = require('events');4-const { test, describe } = require('node:test');5-const assert = require('node:assert/strict');6-7-// Using mock to allow try/catch around what is otherwise out-of-stack error handling.8-// Injecting errors, these are not end-to-end tests.9-10-function makeSystemError(code) {11- // We can not make an actual SystemError, but our usage is lightweight so easy to match.12- const err = new Error();13- err.code = code;14- return err;15-}16-17-// Suppress false positive warnings due to use of testOrSkipOnWindows18-19-const testOrSkipOnWindows = process.platform === 'win32' ? test.skip : test;20-21-describe('executable subcommand missing file handling ', () => {22- testOrSkipOnWindows(23- 'when subcommand executable missing (ENOENT) then throw custom message',24- (t) => {25- // If the command is not found, we show a custom error with an explanation and offer26- // some advice for possible fixes.27- const mockProcess = new EventEmitter();28- t.mock.method(childProcess, 'spawn', () => {29- return mockProcess;30- });31- const program = new commander.Command();32- program.exitOverride();33- program.command('executable', 'executable description');34- program.parse(['executable'], { from: 'user' });35- assert.throws(() => {36- mockProcess.emit('error', makeSystemError('ENOENT'));37- }, /use the executableFile option to supply a custom name/); // part of custom message38- },39- );40-41- testOrSkipOnWindows(42- 'when subcommand executable not executable (EACCES) then throw custom message',43- (t) => {44- const mockProcess = new EventEmitter();45- t.mock.method(childProcess, 'spawn', () => {46- return mockProcess;47- });48- const program = new commander.Command();49- program.exitOverride();50- program.command('executable', 'executable description');51- program.parse(['executable'], { from: 'user' });52- assert.throws(() => {53- mockProcess.emit('error', makeSystemError('EACCES'));54- }, /not executable/); // part of custom message55- },56- );57-58- test('when subcommand executable fails with other error and exitOverride then return in custom wrapper', (t) => {59- // The existing behaviour is to just silently fail for unexpected errors, as it is happening60- // asynchronously in spawned process and client can not catch errors.61- const mockProcess = new EventEmitter();62- t.mock.method(childProcess, 'spawn', () => {63- return mockProcess;64- });65- const program = new commander.Command();66- program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn67- program.exitOverride((err) => {68- throw err;69- });70- program.command('executable', 'executable description');71- program.parse(['executable'], { from: 'user' });72- assert.throws(73- () => {74- mockProcess.emit('error', makeSystemError('OTHER'));75- },76- (err) => {77- assert.equal(err.code, 'commander.executeSubCommandAsync');78- assert.equal(err.nestedError.code, 'OTHER');79- return true;80- },81- );82- });83-84- test('when subcommand executable fails with other error then exit', (t) => {85- // The existing behaviour is to just silently fail for unexpected errors, as it is happening86- // asynchronously in spawned process and client can not catch errors.87- const mockProcess = new EventEmitter();88- t.mock.method(childProcess, 'spawn', () => {89- return mockProcess;90- });91- const exitSpy = t.mock.method(process, 'exit', () => {});92- const program = new commander.Command();93- program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn94- program.command('executable', 'executable description');95- program.parse(['executable'], { from: 'user' });96- mockProcess.emit('error', makeSystemError('OTHER'));97- assert.equal(exitSpy.mock.callCount(), 1);98- const callArgs = exitSpy.mock.calls[0].arguments;99- assert.equal(callArgs[0], 1);100- });101-});added:tests/command.executableSubcommand.search.test.cjs+317 added
1+const childProcess = require('child_process');2+const fs = require('fs');3+const path = require('path');4+const commander = require('../');5+const { test, describe } = require('node:test');6+const assert = require('node:assert/strict');7+8+// Using mocking of child_process.spawn. Not fully supported yet in esm by node:test so run as cjs.9+10+// This file does in-process mocking. Bit clumsy but faster and less external clutter than using fixtures.11+// See also command.executableSubcommand.lookup.test.js for tests using fixtures.12+13+const gLocalDirectory = path.resolve(__dirname, 'fixtures'); // Real directory, although not actually searching for files in it.14+15+function extractMockSpawnArgs(spawnSpy) {16+ assert.equal(spawnSpy.mock.callCount() > 0, true);17+ // This is very fragile on implementation details of how subcommand spawned.18+ // non-Win Jest, launchWithNode: childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });19+ // Win Jest always: childProcess.spawn(process.execPath, args, { stdio: 'inherit' });20+ // node:test passes wild number of node args on front!21+22+ const callArgs = spawnSpy.mock.calls[0].arguments;23+ return callArgs[1].slice(-1); // fingers crossed last arg is filename!24+}25+26+function extractMockSpawnCommand(spawnSpy) {27+ assert.equal(spawnSpy.mock.callCount() > 0, true);28+ // child_process.spawn(command[, args][, options])29+ const callArgs = spawnSpy.mock.calls[0].arguments;30+ return callArgs[0];31+}32+33+const describeOrSkipOnWindows =34+ process.platform === 'win32' ? describe.skip : describe;35+36+describe('executable subcommand search behaviour', () => {37+ function makeSpies(t, existsFn) {38+ const spawnSpy = t.mock.method(childProcess, 'spawn', () => {39+ return {40+ on: () => {},41+ killed: true,42+ };43+ });44+ const existsSpy = t.mock.method(fs, 'existsSync', existsFn);45+ return { spawnSpy, existsSpy };46+ }47+48+ // fs.existsSync gets called on Windows outside the search, so skip the tests (or come up with a different way of checking).49+ describe('whether perform search for local files', () => {50+ test('when no script arg or executableDir then no search for local file', (t) => {51+ const { existsSpy } = makeSpies(t, () => false);52+ const program = new commander.Command();53+ program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn54+ program.name('pm');55+ program.command('sub', 'executable description');56+ program.parse(['sub'], { from: 'user' });57+58+ assert.equal(existsSpy.mock.callCount(), 0);59+ });60+61+ test('when script arg then search for local files', (t) => {62+ const { existsSpy } = makeSpies(t, () => false);63+ const program = new commander.Command();64+ program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn65+ program.name('pm');66+ program.command('sub', 'executable description');67+ program.parse(['node', 'script-name', 'sub']);68+69+ assert.equal(existsSpy.mock.callCount() > 0, true);70+ });71+72+ test('when executableDir then search for local files)', (t) => {73+ const { existsSpy } = makeSpies(t, () => false);74+ const program = new commander.Command();75+ program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn76+ program.name('pm');77+ program.executableDir(__dirname);78+ program.command('sub', 'executable description');79+ program.parse(['sub'], { from: 'user' });80+81+ assert.equal(existsSpy.mock.callCount() > 0, true);82+ });83+ });84+85+ // We always use node on Windows, and don't spawn executable as the command (which may be a feature or a shortcoming!?).86+ describeOrSkipOnWindows(87+ 'subcommand command name with no matching local file (non-Windows)',88+ () => {89+ test('when named pm and no script arg or executableDir then spawn pm-sub as command', (t) => {90+ const { spawnSpy } = makeSpies(t, () => false);91+ const program = new commander.Command();92+ program.name('pm');93+ program.command('sub', 'executable description');94+ program.parse(['sub'], { from: 'user' });95+96+ assert.equal(extractMockSpawnCommand(spawnSpy), 'pm-sub');97+ });98+99+ test('when named pm and script arg then still spawn pm-sub as command', (t) => {100+ const { spawnSpy } = makeSpies(t, () => false);101+ const program = new commander.Command();102+ program.name('pm');103+ program.command('sub', 'executable description');104+ program.parse(['node', 'script-name', 'sub']);105+106+ assert.equal(extractMockSpawnCommand(spawnSpy), 'pm-sub');107+ });108+109+ test('when no name and script arg then spawn script-sub as command', (t) => {110+ const { spawnSpy } = makeSpies(t, () => false);111+ const program = new commander.Command();112+ program.command('sub', 'executable description');113+ program.parse(['node', 'script.js', 'sub']);114+115+ assert.equal(extractMockSpawnCommand(spawnSpy), 'script-sub');116+ });117+118+ test('when named pm and script arg and executableFile then spawn executableFile as command', (t) => {119+ const { spawnSpy } = makeSpies(t, () => false);120+ const program = new commander.Command();121+ program.command('sub', 'executable description', {122+ executableFile: 'myExecutable',123+ });124+ program.parse(['node', 'script.js', 'sub']);125+126+ assert.equal(extractMockSpawnCommand(spawnSpy), 'myExecutable');127+ });128+ },129+ );130+131+ describe('subcommand command name with matching local file', () => {132+ test('when construct with name pm and script arg then spawn local pm-sub.js', (t) => {133+ const program = new commander.Command('pm');134+ program.command('sub', 'executable description');135+136+ const localPath = path.resolve(gLocalDirectory, 'pm-sub.js');137+ const { spawnSpy } = makeSpies(t, (path) => path === localPath);138+ program.parse([139+ 'node',140+ path.resolve(gLocalDirectory, 'script.js'),141+ 'sub',142+ ]);143+144+ assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);145+ });146+147+ test('when name pm and script arg then spawn local pm-sub.js', (t) => {148+ const program = new commander.Command();149+ program.name('pm');150+ program.command('sub', 'executable description');151+152+ const localPath = path.resolve(gLocalDirectory, 'pm-sub.js');153+ const { spawnSpy } = makeSpies(t, (path) => path === localPath);154+ program.parse([155+ 'node',156+ path.resolve(gLocalDirectory, 'script.js'),157+ 'sub',158+ ]);159+160+ assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);161+ });162+163+ test('when script arg then spawn local script-sub.js', (t) => {164+ const program = new commander.Command();165+ program.command('sub', 'executable description');166+167+ const localPath = path.resolve(gLocalDirectory, 'script-sub.js');168+ const { spawnSpy } = makeSpies(t, (path) => path === localPath);169+ program.parse([170+ 'node',171+ path.resolve(gLocalDirectory, 'script.js'),172+ 'sub',173+ ]);174+175+ assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);176+ });177+178+ test('when name pm and script arg and only script-sub.js then fallback to spawn local script-sub.js', (t) => {179+ const program = new commander.Command();180+ program.name('pm');181+ program.command('sub', 'executable description');182+183+ // Fallback for compatibility with Commander <= v8184+ const localPath = path.resolve(gLocalDirectory, 'script-sub.js');185+ const { spawnSpy } = makeSpies(t, (path) => path === localPath);186+ program.parse([187+ 'node',188+ path.resolve(gLocalDirectory, 'script.js'),189+ 'sub',190+ ]);191+192+ assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);193+ });194+195+ test('when name pm and executableDir then spawn local pm-sub.js', (t) => {196+ const program = new commander.Command();197+ program.name('pm');198+ program.command('sub', 'executable description');199+200+ const execDir = path.resolve(gLocalDirectory, 'exec-dir');201+ program.executableDir(execDir);202+ const localPath = path.resolve(execDir, 'pm-sub.js');203+ const { spawnSpy } = makeSpies(t, (path) => path === localPath);204+ program.parse(['sub'], { from: 'user' });205+206+ assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);207+ });208+209+ test('when script arg and relative executableDir then spawn relative script-sub.js', (t) => {210+ const program = new commander.Command();211+ program.command('sub', 'executable description');212+213+ const execDir = 'exec-dir';214+ program.executableDir(execDir);215+ const localPath = path.resolve(gLocalDirectory, execDir, 'script-sub.js');216+ const { spawnSpy } = makeSpies(t, (path) => path === localPath);217+ program.parse(['node', path.resolve(gLocalDirectory, 'script'), 'sub']);218+219+ assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);220+ });221+222+ test('when script arg and absolute executableDir then spawn absolute script-sub.js', (t) => {223+ const program = new commander.Command();224+ program.command('sub', 'executable description');225+226+ const execDir = path.resolve(gLocalDirectory, 'exec-dir');227+ program.executableDir(execDir);228+ const localPath = path.resolve(execDir, 'script-sub.js');229+ const { spawnSpy } = makeSpies(t, (path) => path === localPath);230+ program.parse([231+ 'node',232+ path.resolve(gLocalDirectory, 'script-Dir', 'script'),233+ 'sub',234+ ]);235+236+ assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);237+ });238+239+ test('when script arg is link and and link-sub relative to link target then spawn local link-sub', (t) => {240+ const program = new commander.Command();241+ program.command('sub', 'executable description');242+243+ const linkPath = path.resolve(gLocalDirectory, 'link', 'link');244+ const scriptPath = path.resolve(gLocalDirectory, 'script', 'script.js');245+ const scriptSubPath = path.resolve(246+ gLocalDirectory,247+ 'script',248+ 'link-sub.js',249+ );250+ t.mock.method(fs, 'realpathSync', (path) => {251+ return path === linkPath ? scriptPath : linkPath;252+ });253+ const { spawnSpy } = makeSpies(t, (path) => path === scriptSubPath);254+ program.parse(['node', linkPath, 'sub']);255+256+ assert.deepEqual(extractMockSpawnArgs(spawnSpy), [scriptSubPath]);257+ });258+259+ test('when name pm and script arg and relative executableFile then spawn local exec.js', (t) => {260+ const program = new commander.Command('pm');261+ const localPath = path.join('relative', 'exec.js');262+ const absolutePath = path.resolve(gLocalDirectory, localPath);263+ program.command('sub', 'executable description', {264+ executableFile: localPath,265+ });266+267+ const { spawnSpy } = makeSpies(t, (path) => path === absolutePath);268+ program.parse([269+ 'node',270+ path.resolve(gLocalDirectory, 'script.js'),271+ 'sub',272+ ]);273+274+ assert.deepEqual(extractMockSpawnArgs(spawnSpy), [absolutePath]);275+ });276+277+ test('when name pm and script arg and absolute executableFile then spawn local exec.js', (t) => {278+ const program = new commander.Command('pm');279+ const localPath = path.resolve(gLocalDirectory, 'absolute', 'exec.js');280+ program.command('sub', 'executable description', {281+ executableFile: localPath,282+ });283+284+ const { spawnSpy } = makeSpies(t, (path) => path === localPath);285+ program.parse([286+ 'node',287+ path.resolve(gLocalDirectory, 'script.js'),288+ 'sub',289+ ]);290+291+ assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);292+ });293+ });294+295+ describe('search for local file', () => {296+ test('when script arg then search for local script-sub.js, .ts, .tsx, .mpjs, .cjs', (t) => {297+ const { existsSpy } = makeSpies(t, () => false);298+ const program = new commander.Command();299+ program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn300+ program.command('sub', 'executable description');301+ const scriptPath = path.resolve(gLocalDirectory, 'script');302+ program.parse(['node', scriptPath, 'sub']);303+ const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];304+ sourceExt.forEach((ext) => {305+ const expectedPath = path.resolve(gLocalDirectory, `script-sub${ext}`);306+ const wasCalled = existsSpy.mock.calls.some(307+ (call) => call.arguments[0] === expectedPath,308+ );309+ assert.equal(310+ wasCalled,311+ true,312+ `Expected existsSpy to be called with ${expectedPath}`,313+ );314+ });315+ });316+ });317+});deleted:tests/command.executableSubcommand.search.test.js-315 removed
1-const childProcess = require('child_process');2-const fs = require('fs');3-const path = require('path');4-const commander = require('../');5-const { test, describe } = require('node:test');6-const assert = require('node:assert/strict');7-8-// This file does in-process mocking. Bit clumsy but faster and less external clutter than using fixtures.9-// See also command.executableSubcommand.lookup.test.js for tests using fixtures.10-11-const gLocalDirectory = path.resolve(__dirname, 'fixtures'); // Real directory, although not actually searching for files in it.12-13-function extractMockSpawnArgs(spawnSpy) {14- assert.equal(spawnSpy.mock.callCount() > 0, true);15- // This is very fragile on implementation details of how subcommand spawned.16- // non-Win Jest, launchWithNode: childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });17- // Win Jest always: childProcess.spawn(process.execPath, args, { stdio: 'inherit' });18- // node:test passes wild number of node args on front!19-20- const callArgs = spawnSpy.mock.calls[0].arguments;21- return callArgs[1].slice(-1); // fingers crossed last arg is filename!22-}23-24-function extractMockSpawnCommand(spawnSpy) {25- assert.equal(spawnSpy.mock.callCount() > 0, true);26- // child_process.spawn(command[, args][, options])27- const callArgs = spawnSpy.mock.calls[0].arguments;28- return callArgs[0];29-}30-31-const describeOrSkipOnWindows =32- process.platform === 'win32' ? describe.skip : describe;33-34-describe('executable subcommand search behaviour', () => {35- function makeSpies(t, existsFn) {36- const spawnSpy = t.mock.method(childProcess, 'spawn', () => {37- return {38- on: () => {},39- killed: true,40- };41- });42- const existsSpy = t.mock.method(fs, 'existsSync', existsFn);43- return { spawnSpy, existsSpy };44- }45-46- // fs.existsSync gets called on Windows outside the search, so skip the tests (or come up with a different way of checking).47- describe('whether perform search for local files', () => {48- test('when no script arg or executableDir then no search for local file', (t) => {49- const { existsSpy } = makeSpies(t, () => false);50- const program = new commander.Command();51- program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn52- program.name('pm');53- program.command('sub', 'executable description');54- program.parse(['sub'], { from: 'user' });55-56- assert.equal(existsSpy.mock.callCount(), 0);57- });58-59- test('when script arg then search for local files', (t) => {60- const { existsSpy } = makeSpies(t, () => false);61- const program = new commander.Command();62- program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn63- program.name('pm');64- program.command('sub', 'executable description');65- program.parse(['node', 'script-name', 'sub']);66-67- assert.equal(existsSpy.mock.callCount() > 0, true);68- });69-70- test('when executableDir then search for local files)', (t) => {71- const { existsSpy } = makeSpies(t, () => false);72- const program = new commander.Command();73- program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn74- program.name('pm');75- program.executableDir(__dirname);76- program.command('sub', 'executable description');77- program.parse(['sub'], { from: 'user' });78-79- assert.equal(existsSpy.mock.callCount() > 0, true);80- });81- });82-83- // We always use node on Windows, and don't spawn executable as the command (which may be a feature or a shortcoming!?).84- describeOrSkipOnWindows(85- 'subcommand command name with no matching local file (non-Windows)',86- () => {87- test('when named pm and no script arg or executableDir then spawn pm-sub as command', (t) => {88- const { spawnSpy } = makeSpies(t, () => false);89- const program = new commander.Command();90- program.name('pm');91- program.command('sub', 'executable description');92- program.parse(['sub'], { from: 'user' });93-94- assert.equal(extractMockSpawnCommand(spawnSpy), 'pm-sub');95- });96-97- test('when named pm and script arg then still spawn pm-sub as command', (t) => {98- const { spawnSpy } = makeSpies(t, () => false);99- const program = new commander.Command();100- program.name('pm');101- program.command('sub', 'executable description');102- program.parse(['node', 'script-name', 'sub']);103-104- assert.equal(extractMockSpawnCommand(spawnSpy), 'pm-sub');105- });106-107- test('when no name and script arg then spawn script-sub as command', (t) => {108- const { spawnSpy } = makeSpies(t, () => false);109- const program = new commander.Command();110- program.command('sub', 'executable description');111- program.parse(['node', 'script.js', 'sub']);112-113- assert.equal(extractMockSpawnCommand(spawnSpy), 'script-sub');114- });115-116- test('when named pm and script arg and executableFile then spawn executableFile as command', (t) => {117- const { spawnSpy } = makeSpies(t, () => false);118- const program = new commander.Command();119- program.command('sub', 'executable description', {120- executableFile: 'myExecutable',121- });122- program.parse(['node', 'script.js', 'sub']);123-124- assert.equal(extractMockSpawnCommand(spawnSpy), 'myExecutable');125- });126- },127- );128-129- describe('subcommand command name with matching local file', () => {130- test('when construct with name pm and script arg then spawn local pm-sub.js', (t) => {131- const program = new commander.Command('pm');132- program.command('sub', 'executable description');133-134- const localPath = path.resolve(gLocalDirectory, 'pm-sub.js');135- const { spawnSpy } = makeSpies(t, (path) => path === localPath);136- program.parse([137- 'node',138- path.resolve(gLocalDirectory, 'script.js'),139- 'sub',140- ]);141-142- assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);143- });144-145- test('when name pm and script arg then spawn local pm-sub.js', (t) => {146- const program = new commander.Command();147- program.name('pm');148- program.command('sub', 'executable description');149-150- const localPath = path.resolve(gLocalDirectory, 'pm-sub.js');151- const { spawnSpy } = makeSpies(t, (path) => path === localPath);152- program.parse([153- 'node',154- path.resolve(gLocalDirectory, 'script.js'),155- 'sub',156- ]);157-158- assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);159- });160-161- test('when script arg then spawn local script-sub.js', (t) => {162- const program = new commander.Command();163- program.command('sub', 'executable description');164-165- const localPath = path.resolve(gLocalDirectory, 'script-sub.js');166- const { spawnSpy } = makeSpies(t, (path) => path === localPath);167- program.parse([168- 'node',169- path.resolve(gLocalDirectory, 'script.js'),170- 'sub',171- ]);172-173- assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);174- });175-176- test('when name pm and script arg and only script-sub.js then fallback to spawn local script-sub.js', (t) => {177- const program = new commander.Command();178- program.name('pm');179- program.command('sub', 'executable description');180-181- // Fallback for compatibility with Commander <= v8182- const localPath = path.resolve(gLocalDirectory, 'script-sub.js');183- const { spawnSpy } = makeSpies(t, (path) => path === localPath);184- program.parse([185- 'node',186- path.resolve(gLocalDirectory, 'script.js'),187- 'sub',188- ]);189-190- assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);191- });192-193- test('when name pm and executableDir then spawn local pm-sub.js', (t) => {194- const program = new commander.Command();195- program.name('pm');196- program.command('sub', 'executable description');197-198- const execDir = path.resolve(gLocalDirectory, 'exec-dir');199- program.executableDir(execDir);200- const localPath = path.resolve(execDir, 'pm-sub.js');201- const { spawnSpy } = makeSpies(t, (path) => path === localPath);202- program.parse(['sub'], { from: 'user' });203-204- assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);205- });206-207- test('when script arg and relative executableDir then spawn relative script-sub.js', (t) => {208- const program = new commander.Command();209- program.command('sub', 'executable description');210-211- const execDir = 'exec-dir';212- program.executableDir(execDir);213- const localPath = path.resolve(gLocalDirectory, execDir, 'script-sub.js');214- const { spawnSpy } = makeSpies(t, (path) => path === localPath);215- program.parse(['node', path.resolve(gLocalDirectory, 'script'), 'sub']);216-217- assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);218- });219-220- test('when script arg and absolute executableDir then spawn absolute script-sub.js', (t) => {221- const program = new commander.Command();222- program.command('sub', 'executable description');223-224- const execDir = path.resolve(gLocalDirectory, 'exec-dir');225- program.executableDir(execDir);226- const localPath = path.resolve(execDir, 'script-sub.js');227- const { spawnSpy } = makeSpies(t, (path) => path === localPath);228- program.parse([229- 'node',230- path.resolve(gLocalDirectory, 'script-Dir', 'script'),231- 'sub',232- ]);233-234- assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);235- });236-237- test('when script arg is link and and link-sub relative to link target then spawn local link-sub', (t) => {238- const program = new commander.Command();239- program.command('sub', 'executable description');240-241- const linkPath = path.resolve(gLocalDirectory, 'link', 'link');242- const scriptPath = path.resolve(gLocalDirectory, 'script', 'script.js');243- const scriptSubPath = path.resolve(244- gLocalDirectory,245- 'script',246- 'link-sub.js',247- );248- t.mock.method(fs, 'realpathSync', (path) => {249- return path === linkPath ? scriptPath : linkPath;250- });251- const { spawnSpy } = makeSpies(t, (path) => path === scriptSubPath);252- program.parse(['node', linkPath, 'sub']);253-254- assert.deepEqual(extractMockSpawnArgs(spawnSpy), [scriptSubPath]);255- });256-257- test('when name pm and script arg and relative executableFile then spawn local exec.js', (t) => {258- const program = new commander.Command('pm');259- const localPath = path.join('relative', 'exec.js');260- const absolutePath = path.resolve(gLocalDirectory, localPath);261- program.command('sub', 'executable description', {262- executableFile: localPath,263- });264-265- const { spawnSpy } = makeSpies(t, (path) => path === absolutePath);266- program.parse([267- 'node',268- path.resolve(gLocalDirectory, 'script.js'),269- 'sub',270- ]);271-272- assert.deepEqual(extractMockSpawnArgs(spawnSpy), [absolutePath]);273- });274-275- test('when name pm and script arg and absolute executableFile then spawn local exec.js', (t) => {276- const program = new commander.Command('pm');277- const localPath = path.resolve(gLocalDirectory, 'absolute', 'exec.js');278- program.command('sub', 'executable description', {279- executableFile: localPath,280- });281-282- const { spawnSpy } = makeSpies(t, (path) => path === localPath);283- program.parse([284- 'node',285- path.resolve(gLocalDirectory, 'script.js'),286- 'sub',287- ]);288-289- assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);290- });291- });292-293- describe('search for local file', () => {294- test('when script arg then search for local script-sub.js, .ts, .tsx, .mpjs, .cjs', (t) => {295- const { existsSpy } = makeSpies(t, () => false);296- const program = new commander.Command();297- program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn298- program.command('sub', 'executable description');299- const scriptPath = path.resolve(gLocalDirectory, 'script');300- program.parse(['node', scriptPath, 'sub']);301- const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];302- sourceExt.forEach((ext) => {303- const expectedPath = path.resolve(gLocalDirectory, `script-sub${ext}`);304- const wasCalled = existsSpy.mock.calls.some(305- (call) => call.arguments[0] === expectedPath,306- );307- assert.equal(308- wasCalled,309- true,310- `Expected existsSpy to be called with ${expectedPath}`,311- );312- });313- });314- });315-});modified:tests/command.executableSubcommand.signals.test.js+5 added-5 removed
1-const childProcess = require('child_process');2-const path = require('path');3-const { test, describe } = require('node:test');4-const assert = require('node:assert/strict');1+import * as childProcess from 'child_process';2+import * as path from 'path';3+import { test, describe } from 'node:test';4+import assert from 'node:assert/strict';5 6-const pmPath = path.join(__dirname, 'fixtures', 'pm');6+const pmPath = path.join(import.meta.dirname, 'fixtures', 'pm');7 8 // Disabling some tests on Windows as:9 // "Windows does not support sending signals"10 // https://nodejs.org/api/process.html#process_signal_events52 unmodified linesmodified:tests/command.executableSubcommand.test.js+3 added-3 removed
1-const { createTestCommand } = require('./testHelpers');2-const { test } = require('node:test');3-const assert = require('node:assert/strict');1+import { createTestCommand } from './testHelpers.js';2+import { test } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Executable subcommand tests that didn't fit in elsewhere.6 7 // This is the default behaviour when no default command and no action handlers12 unmodified linesmodified:tests/command.exitOverride.test.js+5 added-5 removed
1-const commander = require('../');2-const path = require('path');3-const { test, describe } = require('node:test');4-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import * as path from 'path';3+import { test, describe } from 'node:test';4+import assert from 'node:assert/strict';5 6 // Test details of the exitOverride errors.7 // The important checks are the exitCode and code which are intended to be stable for8 // semver minor versions. For now, also testing the error.message and that output occurred246 unmodified lines255 expectCommanderError(caughtErr, 0, 'commander.version', myVersion);256 });257 258 test('when executableSubcommand succeeds then call exitOverride', async () => {259- const pm = path.join(__dirname, 'fixtures/pm');259+ const pm = path.join(import.meta.dirname, 'fixtures/pm');260 const program = new commander.Command();261 await new Promise((resolve) => {262 program263 .exitOverride((err) => {194 unmodified linesmodified:tests/command.help.test.js+4 added-4 removed
1-const commander = require('../');2-const { createTestCommand } = require('./testHelpers');3-const { test, describe } = require('node:test');4-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { createTestCommand } from './testHelpers.js';3+import { test, describe } from 'node:test';4+import assert from 'node:assert/strict';5 6 // Testing various help incantations.7 //8 // Note there are also specific help tests included in many of the feature tests,309 unmodified linesmodified:tests/command.helpCommand.test.js+4 added-4 removed
1-const commander = require('../');2-const { createTestCommand } = require('./testHelpers');3-const { test, describe } = require('node:test');4-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { createTestCommand } from './testHelpers.js';3+import { test, describe } from 'node:test';4+import assert from 'node:assert/strict';5 6 describe('help handling of subcommands', () => {7 describe('help command listed in helpInformation', () => {8 test('when program has no subcommands then no automatic help command', () => {163 unmodified linesmodified:tests/command.helpOption.test.js+4 added-4 removed
1-const commander = require('../');2-const { createTestCommand } = require('./testHelpers');3-const { test, describe } = require('node:test');4-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { createTestCommand } from './testHelpers.js';3+import { test, describe } from 'node:test';4+import assert from 'node:assert/strict';5 6 describe('Command.helpOption()', () => {7 test('when helpOption has custom flags then custom short flag invokes help', (t) => {8 const program = createTestCommand();119 unmodified linesmodified:tests/command.hook.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 describe('Command.hook()', () => {6 test('when hook event wrong then throw', () => {7 const program = new commander.Command();410 unmodified linesmodified:tests/command.name.test.js+6 added-6 removed
1-const path = require('path');2-const commander = require('../');3-const { test, describe } = require('node:test');4-const assert = require('node:assert/strict');1+import * as path from 'path';2+import * as commander from '../index.js';3+import { test, describe } from 'node:test';4+import assert from 'node:assert/strict';5 6 describe('Command.name()', () => {7 test('when construct with name then name is set', () => {8 const program = new commander.Command('foo');39 unmodified lines48 program.nameFromFilename(path.resolve(process.cwd(), 'foo.js'));49 assert.equal(program.name(), 'foo');50 });51 52- test('when pass __filename to nameFromFilename then name is plain name of this file', () => {52+ test('when pass import.meta.filename to nameFromFilename then name is plain name of this file', () => {53 const program = new commander.Command();54- program.nameFromFilename(__filename);54+ program.nameFromFilename(import.meta.filename);55 assert.equal(program.name(), 'command.name.test');56 });57 });modified:tests/command.nested.test.js+3 added-3 removed
1-const commander = require('../');2-const { test } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test } from 'node:test';3+import assert from 'node:assert/strict';4 5 test('when call nested subcommand then runs', (t) => {6 const program = new commander.Command();7 const leafAction = t.mock.fn();4 unmodified linesmodified:tests/command.onCommand.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // The action handler used to be implemented using command events and listeners.6 // Now, this is mostly just for backwards compatibility.7 30 unmodified linesmodified:tests/command.option-misuse.test.js+3 added-3 removed
1-const { Command, Option } = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import { Command, Option } from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // It is a reasonable and easy mistake to pass Option to .option(). Detect this6 // and offer advice.7 26 unmodified linesmodified:tests/command.parse.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Testing some Electron conventions but not directly using Electron to avoid overheads.6 // https://github.com/electron/electron/issues/4690#issuecomment-2174352227 // https://www.electronjs.org/docs/api/process#processdefaultapp-readonly435 unmodified linesmodified:tests/command.parseOptions.test.js+8 added-8 removed
1-const childProcess = require('child_process');2-const commander = require('../');3-const path = require('path');4-const util = require('util');5-const { test, describe } = require('node:test');6-const assert = require('node:assert/strict');1+import * as childProcess from 'child_process';2+import * as commander from '../index.js';3+import * as path from 'path';4+import * as util from 'util';5+import { test, describe } from 'node:test';6+import assert from 'node:assert/strict';7 8 const execFileAsync = util.promisify(childProcess.execFile);9 10 // Combination of parse and parseOptions tests which are more about details26 unmodified lines37 });38 39 // https://github.com/tj/commander.js/issues/50840 test('when arguments to executable include option flags then argument order preserved', async () => {41- const pm = path.join(__dirname, 'fixtures/pm');41+ const pm = path.join(import.meta.dirname, 'fixtures/pm');42 const { stdout } = await execFileAsync('node', [43 pm,44 'echo',45 '1',3 unmodified lines49 '4',50 '5',51 '6',52 ]);53- assert.equal(stdout, "[ '1', '2', '--dry-run', '3', '4', '5', '6' ]\n");53+ assert.equal(stdout, '["1","2","--dry-run","3","4","5","6"]\n');54 });55 });56 57 describe('Command.parseOptions()', () => {278 unmodified linesmodified:tests/command.positionalOptions.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // The changes to parsing for positional options are subtle, and took extra care to work with6 // implicit help and default commands. Lots of tests.7 527 unmodified linesmodified:tests/command.registerClash.test.js+3 added-3 removed
1-const { Command } = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import { Command } from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 describe('registering clashing subcommands', () => {6 test('when command name conflicts with existing name then throw', () => {7 assert.throws(64 unmodified linesmodified:tests/command.showHelpAfterError.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe, mock } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe, mock } from 'node:test';3+import assert from 'node:assert/strict';4 5 describe('Command.showHelpAfterError(message)', () => {6 const customHelpMessage = 'See --help';7 132 unmodified linesmodified:tests/command.showSuggestionAfterError.test.js+3 added-3 removed
1-const { Command } = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import { Command } from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 function getSuggestion(program, arg) {6 let message = '';7 program.exitOverride().configureOutput({47 unmodified linesmodified:tests/command.summary.test.js+3 added-3 removed
1-const commander = require('../');2-const { test } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test } from 'node:test';3+import assert from 'node:assert/strict';4 5 test('Command.summary(): when set summary then get summary', () => {6 const program = new commander.Command();7 const summary = 'abcdef';3 unmodified linesmodified:tests/command.unknownCommand.test.js+3 added-3 removed
1-const { createTestCommand } = require('./testHelpers');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import { createTestCommand } from './testHelpers.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 describe('parsing unknown command', () => {6 test('when unknown argument in simple program then error', () => {7 const program = createTestCommand();47 unmodified linesmodified:tests/command.unknownOption.test.js+3 added-3 removed
1-const { createTestCommand } = require('./testHelpers');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import { createTestCommand } from './testHelpers.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Checking for detection of unknown options, including regression tests for some past issues.6 7 describe('parsing unknown option', () => {71 unmodified linesmodified:tests/command.usage.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 describe('command Usage section in help', () => {6 test('when default usage and check program help then starts with default usage', () => {7 const program = new commander.Command();85 unmodified linesmodified:tests/commander.storeOptionsAsProperties.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Mostly testing direct on program, limited check that (sub)command working same.6 7 describe('Command.storeOptionsAsProperties()', () => {92 unmodified linesmodified:tests/createCommand.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 describe('Command.createCommand()', () => {6 test('when createCommand then unattached', () => {7 const program = new commander.Command();33 unmodified linesmodified:tests/deprecated.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Test for backwards compatible behaviour of deprecated features that don't fit in elsewhere.6 // We keep deprecated features working (when not too difficult) to avoid breaking existing code7 // and reduce barriers to updating to latest version of Commander.23 unmodified linesmodified:tests/help.argumentDescription.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // These are tests of the Help class, not of the Command help.6 7 describe('Help.argumentDescription()', () => {42 unmodified linesmodified:tests/help.boxWrap.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 describe('Help.boxWrap()', () => {6 test('when empty string then return empty string', () => {7 const helper = new commander.Help();115 unmodified linesmodified:tests/help.commandTerm.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // These are tests of the Help class, not of the Command help.6 // There is some overlap with the higher level Command tests (which predate Help).7 38 unmodified linesmodified:tests/help.commandUsage.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // These are tests of the Help class, not of the Command help.6 // There is some overlap with the higher level Command tests (which predate Help).7 38 unmodified linesmodified:tests/help.longestArgumentTermLength.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // These are tests of the Help class, not of the Command help.6 // There is some overlap with the higher level Command tests (which predate Help).7 29 unmodified linesmodified:tests/help.longestCommandTermLength.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // These are tests of the Help class, not of the Command help.6 // There is some overlap with the higher level Command tests (which predate Help).7 54 unmodified linesmodified:tests/help.longestOptionTermLength.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // These are tests of the Help class, not of the Command help.6 // There is some overlap with the higher level Command tests (which predate Help).7 31 unmodified linesmodified:tests/help.minWidthToWrap.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 describe('Help.minWidthToWrap()', () => {6 test('when enough width then wrap', () => {7 const program = new commander.Command('program');42 unmodified linesmodified:tests/help.optionDescription.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // These are tests of the Help class, not of the Command help.6 // There is some overlap with the higher level Command tests (which predate Help).7 96 unmodified linesmodified:tests/help.optionTerm.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // These are tests of the Help class, not of the Command help.6 // There is some overlap with the higher level Command tests (which predate Help).7 29 unmodified linesmodified:tests/help.padWidth.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // These are tests of the Help class, not of the Command help.6 // There is some overlap with the higher level Command tests (which predate Help).7 40 unmodified linesmodified:tests/help.preformatted.test.js+3 added-3 removed
1-const { Help, Command } = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import { Help, Command } from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 describe('Help.preformatted()', () => {6 test('when single line then false', () => {7 const helper = new Help();65 unmodified linesmodified:tests/help.showGlobalOptions.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 describe('Help.showGlobalOptions()', () => {6 test('when default configuration then global options hidden', () => {7 const program = new commander.Command();45 unmodified linesmodified:tests/help.sortCommands.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // These are tests of the Help class, not of the Command help.6 // There is some overlap with the higher level Command tests (which predate Help).7 28 unmodified linesmodified:tests/help.sortOptions.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // These are tests of the Help class, not of the Command help.6 // There is some overlap with the higher level Command tests (which predate Help).7 91 unmodified linesmodified:tests/help.stripAnsi.test.js+3 added-3 removed
1-const { stripColor } = require('../lib/help');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import { stripColor } from '../lib/help.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters6 7 // Test the lowest level routine being used for SGR support.62 unmodified linesmodified:tests/help.style.test.js+3 added-3 removed
1-const { test, describe } = require('node:test');2-const assert = require('node:assert/strict');3-const { Command } = require('../');1+import { test, describe } from 'node:test';2+import assert from 'node:assert/strict';3+import { Command } from '../index.js';4 5 function red(str) {6 // Use plain characters so not stripped in failure messages. (Means displayWidth is bogus though.)7 return `RED ${str} DER`;289 unmodified linesmodified:tests/help.subcommandDescription.test.js+3 added-3 removed
1-const { test, describe } = require('node:test');2-const assert = require('node:assert/strict');3-const commander = require('../');1+import { test, describe } from 'node:test';2+import assert from 'node:assert/strict';3+import * as commander from '../index.js';4 5 // These are tests of the Help class, not of the Command help.6 // There is some overlap with the higher level Command tests (which predate Help).7 32 unmodified linesmodified:tests/help.suggestion.test.js+3 added-3 removed
1-const { test, describe } = require('node:test');2-const assert = require('node:assert/strict');3-const { Command, Option } = require('../');1+import { test, describe } from 'node:test';2+import assert from 'node:assert/strict';3+import { Command, Option } from '../index.js';4 5 // Note: setting up shared command configuration in getSuggestion,6 // and looking for possible subcommand 'sub'.7 244 unmodified linesmodified:tests/help.visibleArguments.test.js+3 added-3 removed
1-const { test, describe } = require('node:test');2-const assert = require('node:assert/strict');3-const commander = require('../');1+import { test, describe } from 'node:test';2+import assert from 'node:assert/strict';3+import * as commander from '../index.js';4 5 // These are tests of the Help class, not of the Command help.6 // There is some overlap with the higher level Command tests (which predate Help).7 72 unmodified linesmodified:tests/help.visibleCommands.test.js+3 added-3 removed
1-const { test, describe } = require('node:test');2-const assert = require('node:assert/strict');3-const commander = require('../');1+import { test, describe } from 'node:test';2+import assert from 'node:assert/strict';3+import * as commander from '../index.js';4 5 // These are tests of the Help class, not of the Command help.6 // There is some overlap with the higher level Command tests (which predate Help).7 30 unmodified linesmodified:tests/help.visibleGlobalOptions.test.js+3 added-3 removed
1-const { test, describe } = require('node:test');2-const assert = require('node:assert/strict');3-const commander = require('../');1+import { test, describe } from 'node:test';2+import assert from 'node:assert/strict';3+import * as commander from '../index.js';4 5 describe('Help.visibleGlobalOptions()', () => {6 test('when default configuration then return empty array', () => {7 const program = new commander.Command();40 unmodified linesmodified:tests/help.visibleOptions.test.js+3 added-3 removed
1-const { test, describe } = require('node:test');2-const assert = require('node:assert/strict');3-const commander = require('../');1+import { test, describe } from 'node:test';2+import assert from 'node:assert/strict';3+import * as commander from '../index.js';4 5 // These are tests of the Help class, not of the Command help.6 // There is some overlap with the higher level Command tests (which predate Help).7 71 unmodified linesmodified:tests/helpGroup.test.js+3 added-3 removed
1-const { test, describe } = require('node:test');2-const assert = require('node:assert/strict');3-const { Command, Option } = require('../');1+import { test, describe } from 'node:test';2+import assert from 'node:assert/strict';3+import { Command, Option } from '../index.js';4 5 // Similar tests for Option.helpGroup() and Command.helpGroup(),6 // and for Command.optionsGroup() and Command.commandsGroup().7 248 unmodified linesmodified:tests/imports.test.cjs+61 added-1 removed
9 unmodified lines10 createCommand,11 createOption,12 createArgument,13 } = require('../index.js');14+const commander = require('../index.js');15 const { describe, test } = require('node:test');16 const assert = require('node:assert/strict');17 18 // Do some testing of the default export(s).3 unmodified lines22 assert.equal(typeof obj, 'object');23 assert.equal(obj.constructor.name, name);24 }25 25-describe('imports from .cjs', () => {26+describe('named imports from .cjs', () => {27 test('program', () => {28 checkClass(program, 'Command');29 });30 40 unmodified lines71 test('createArgument', () => {72 checkClass(createArgument('<foo>', 'description'), 'Argument');73 });74 });75+76+describe('unnamed imports from .cjs', () => {77+ test('program', () => {78+ checkClass(commander.program, 'Command');79+ });80+81+ test('Command', () => {82+ checkClass(new commander.Command('name'), 'Command');83+ });84+85+ test('Option', () => {86+ checkClass(new commander.Option('-e, --example', 'description'), 'Option');87+ });88+89+ test('Argument', () => {90+ checkClass(new commander.Argument('<foo>', 'description'), 'Argument');91+ });92+93+ test('Help', () => {94+ checkClass(new commander.Help(), 'Help');95+ });96+97+ test('CommanderError', () => {98+ checkClass(99+ new commander.CommanderError(1, 'code', 'failed'),100+ 'CommanderError',101+ );102+ });103+104+ test('InvalidArgumentError', () => {105+ checkClass(106+ new commander.InvalidArgumentError('failed'),107+ 'InvalidArgumentError',108+ );109+ });110+111+ test('InvalidOptionArgumentError', () => {112+ // Deprecated113+ checkClass(114+ new commander.InvalidOptionArgumentError('failed'),115+ 'InvalidArgumentError',116+ );117+ });118+119+ test('createCommand', () => {120+ checkClass(commander.createCommand('foo'), 'Command');121+ });122+123+ test('createOption', () => {124+ checkClass(125+ commander.createOption('-e, --example', 'description'),126+ 'Option',127+ );128+ });129+130+ test('createArgument', () => {131+ checkClass(commander.createArgument('<foo>', 'description'), 'Argument');132+ });133+});added:tests/incrementNodeInspectorPort.test.cjs+146 added
1+const { test, describe, after } = require('node:test');2+const assert = require('node:assert/strict');3+const childProcess = require('child_process');4+const path = require('path');5+const commander = require('../');6+7+// Using mocking of child_process.spawn. Not fully supported yet in esm by node:test so run as cjs.8+9+describe('increment node inspector port in executable subcommands', () => {10+ function makeSpies(t) {11+ const spawnSpy = t.mock.method(childProcess, 'spawn', () => {12+ return {13+ on: () => {},14+ };15+ });16+ const signalSpy = test.mock.method(process, 'on', () => {});17+ return { spawnSpy, signalSpy };18+ }19+20+ const oldExecArgv = process.execArgv;21+22+ after(() => {23+ process.execArgv = oldExecArgv;24+ });25+26+ function makeProgram() {27+ const program = new commander.Command();28+ const fileWhichExists = path.join(__dirname, './fixtures/pm-cache.js');29+ program.command('cache', 'stand-alone command', {30+ executableFile: fileWhichExists,31+ });32+ return program;33+ }34+35+ function extractMockExecArgs(spawnSpy) {36+ return spawnSpy.mock.calls[0].arguments[1].slice(0, -1);37+ }38+39+ test('when --inspect then bump port', (t) => {40+ const { spawnSpy } = makeSpies(t);41+ const program = makeProgram();42+ process.execArgv = ['--inspect'];43+ program.parse(['node', 'test', 'cache']);44+ const execArgs = extractMockExecArgs(spawnSpy);45+ assert.deepEqual(execArgs, ['--inspect=127.0.0.1:9230']);46+ });47+48+ test('when --inspect=100 then bump port', (t) => {49+ const { spawnSpy } = makeSpies(t);50+ const program = makeProgram();51+ process.execArgv = ['--inspect=100'];52+ program.parse(['node', 'test', 'cache']);53+ const execArgs = extractMockExecArgs(spawnSpy);54+ assert.deepEqual(execArgs, ['--inspect=127.0.0.1:101']);55+ });56+57+ test('when --inspect=1.2.3.4:100 then bump port', (t) => {58+ const { spawnSpy } = makeSpies(t);59+ const program = makeProgram();60+ process.execArgv = ['--inspect=1.2.3.4:100'];61+ program.parse(['node', 'test', 'cache']);62+ const execArgs = extractMockExecArgs(spawnSpy);63+ assert.deepEqual(execArgs, ['--inspect=1.2.3.4:101']);64+ });65+66+ test('when --inspect=1.2.3.4 then bump port', (t) => {67+ const { spawnSpy } = makeSpies(t);68+ const program = makeProgram();69+ process.execArgv = ['--inspect=1.2.3.4'];70+ program.parse(['node', 'test', 'cache']);71+ const execArgs = extractMockExecArgs(spawnSpy);72+ assert.deepEqual(execArgs, ['--inspect=1.2.3.4:9230']);73+ });74+75+ test('when --inspect-brk then bump port', (t) => {76+ const { spawnSpy } = makeSpies(t);77+ const program = makeProgram();78+ process.execArgv = ['--inspect-brk'];79+ program.parse(['node', 'test', 'cache']);80+ const execArgs = extractMockExecArgs(spawnSpy);81+ assert.deepEqual(execArgs, ['--inspect-brk=127.0.0.1:9230']);82+ });83+84+ test('when --inspect-brk=100 then bump port', (t) => {85+ const { spawnSpy } = makeSpies(t);86+ const program = makeProgram();87+ process.execArgv = ['--inspect-brk=100'];88+ program.parse(['node', 'test', 'cache']);89+ const execArgs = extractMockExecArgs(spawnSpy);90+ assert.deepEqual(execArgs, ['--inspect-brk=127.0.0.1:101']);91+ });92+93+ test('when --inspect-brk=1.2.3.4 then bump port', (t) => {94+ const { spawnSpy } = makeSpies(t);95+ const program = makeProgram();96+ process.execArgv = ['--inspect-brk=1.2.3.4'];97+ program.parse(['node', 'test', 'cache']);98+ const execArgs = extractMockExecArgs(spawnSpy);99+ assert.deepEqual(execArgs, ['--inspect-brk=1.2.3.4:9230']);100+ });101+102+ test('when --inspect-brk=1.2.3.4:100 then bump port', (t) => {103+ const { spawnSpy } = makeSpies(t);104+ const program = makeProgram();105+ process.execArgv = ['--inspect-brk=1.2.3.4:100'];106+ program.parse(['node', 'test', 'cache']);107+ const execArgs = extractMockExecArgs(spawnSpy);108+ assert.deepEqual(execArgs, ['--inspect-brk=1.2.3.4:101']);109+ });110+111+ test('when --inspect-port=100 then bump port', (t) => {112+ const { spawnSpy } = makeSpies(t);113+ const program = makeProgram();114+ process.execArgv = ['--inspect-port=100'];115+ program.parse(['node', 'test', 'cache']);116+ const execArgs = extractMockExecArgs(spawnSpy);117+ assert.deepEqual(execArgs, ['--inspect-port=127.0.0.1:101']);118+ });119+120+ test('when --inspect-port=1.2.3.4:100 then bump port', (t) => {121+ const { spawnSpy } = makeSpies(t);122+ const program = makeProgram();123+ process.execArgv = ['--inspect-port=1.2.3.4:100'];124+ program.parse(['node', 'test', 'cache']);125+ const execArgs = extractMockExecArgs(spawnSpy);126+ assert.deepEqual(execArgs, ['--inspect-port=1.2.3.4:101']);127+ });128+129+ test('when --inspect-unexpected then unchanged', (t) => {130+ const { spawnSpy } = makeSpies(t);131+ const program = makeProgram();132+ process.execArgv = ['--inspect-unexpected'];133+ program.parse(['node', 'test', 'cache']);134+ const execArgs = extractMockExecArgs(spawnSpy);135+ assert.deepEqual(execArgs, ['--inspect-unexpected']);136+ });137+138+ test('when --frozen-intrinsics then unchanged', (t) => {139+ const { spawnSpy } = makeSpies(t);140+ const program = makeProgram();141+ process.execArgv = ['--frozen-intrinsics '];142+ program.parse(['node', 'test', 'cache']);143+ const execArgs = extractMockExecArgs(spawnSpy);144+ assert.deepEqual(execArgs, ['--frozen-intrinsics ']);145+ });146+});deleted:tests/incrementNodeInspectorPort.test.js-144 removed
1-const { test, describe, after } = require('node:test');2-const assert = require('node:assert/strict');3-const childProcess = require('child_process');4-const path = require('path');5-const commander = require('../');6-7-describe('increment node inspector port in executable subcommands', () => {8- function makeSpies(t) {9- const spawnSpy = t.mock.method(childProcess, 'spawn', () => {10- return {11- on: () => {},12- };13- });14- const signalSpy = test.mock.method(process, 'on', () => {});15- return { spawnSpy, signalSpy };16- }17-18- const oldExecArgv = process.execArgv;19-20- after(() => {21- process.execArgv = oldExecArgv;22- });23-24- function makeProgram() {25- const program = new commander.Command();26- const fileWhichExists = path.join(__dirname, './fixtures/pm-cache.js');27- program.command('cache', 'stand-alone command', {28- executableFile: fileWhichExists,29- });30- return program;31- }32-33- function extractMockExecArgs(spawnSpy) {34- return spawnSpy.mock.calls[0].arguments[1].slice(0, -1);35- }36-37- test('when --inspect then bump port', (t) => {38- const { spawnSpy } = makeSpies(t);39- const program = makeProgram();40- process.execArgv = ['--inspect'];41- program.parse(['node', 'test', 'cache']);42- const execArgs = extractMockExecArgs(spawnSpy);43- assert.deepEqual(execArgs, ['--inspect=127.0.0.1:9230']);44- });45-46- test('when --inspect=100 then bump port', (t) => {47- const { spawnSpy } = makeSpies(t);48- const program = makeProgram();49- process.execArgv = ['--inspect=100'];50- program.parse(['node', 'test', 'cache']);51- const execArgs = extractMockExecArgs(spawnSpy);52- assert.deepEqual(execArgs, ['--inspect=127.0.0.1:101']);53- });54-55- test('when --inspect=1.2.3.4:100 then bump port', (t) => {56- const { spawnSpy } = makeSpies(t);57- const program = makeProgram();58- process.execArgv = ['--inspect=1.2.3.4:100'];59- program.parse(['node', 'test', 'cache']);60- const execArgs = extractMockExecArgs(spawnSpy);61- assert.deepEqual(execArgs, ['--inspect=1.2.3.4:101']);62- });63-64- test('when --inspect=1.2.3.4 then bump port', (t) => {65- const { spawnSpy } = makeSpies(t);66- const program = makeProgram();67- process.execArgv = ['--inspect=1.2.3.4'];68- program.parse(['node', 'test', 'cache']);69- const execArgs = extractMockExecArgs(spawnSpy);70- assert.deepEqual(execArgs, ['--inspect=1.2.3.4:9230']);71- });72-73- test('when --inspect-brk then bump port', (t) => {74- const { spawnSpy } = makeSpies(t);75- const program = makeProgram();76- process.execArgv = ['--inspect-brk'];77- program.parse(['node', 'test', 'cache']);78- const execArgs = extractMockExecArgs(spawnSpy);79- assert.deepEqual(execArgs, ['--inspect-brk=127.0.0.1:9230']);80- });81-82- test('when --inspect-brk=100 then bump port', (t) => {83- const { spawnSpy } = makeSpies(t);84- const program = makeProgram();85- process.execArgv = ['--inspect-brk=100'];86- program.parse(['node', 'test', 'cache']);87- const execArgs = extractMockExecArgs(spawnSpy);88- assert.deepEqual(execArgs, ['--inspect-brk=127.0.0.1:101']);89- });90-91- test('when --inspect-brk=1.2.3.4 then bump port', (t) => {92- const { spawnSpy } = makeSpies(t);93- const program = makeProgram();94- process.execArgv = ['--inspect-brk=1.2.3.4'];95- program.parse(['node', 'test', 'cache']);96- const execArgs = extractMockExecArgs(spawnSpy);97- assert.deepEqual(execArgs, ['--inspect-brk=1.2.3.4:9230']);98- });99-100- test('when --inspect-brk=1.2.3.4:100 then bump port', (t) => {101- const { spawnSpy } = makeSpies(t);102- const program = makeProgram();103- process.execArgv = ['--inspect-brk=1.2.3.4:100'];104- program.parse(['node', 'test', 'cache']);105- const execArgs = extractMockExecArgs(spawnSpy);106- assert.deepEqual(execArgs, ['--inspect-brk=1.2.3.4:101']);107- });108-109- test('when --inspect-port=100 then bump port', (t) => {110- const { spawnSpy } = makeSpies(t);111- const program = makeProgram();112- process.execArgv = ['--inspect-port=100'];113- program.parse(['node', 'test', 'cache']);114- const execArgs = extractMockExecArgs(spawnSpy);115- assert.deepEqual(execArgs, ['--inspect-port=127.0.0.1:101']);116- });117-118- test('when --inspect-port=1.2.3.4:100 then bump port', (t) => {119- const { spawnSpy } = makeSpies(t);120- const program = makeProgram();121- process.execArgv = ['--inspect-port=1.2.3.4:100'];122- program.parse(['node', 'test', 'cache']);123- const execArgs = extractMockExecArgs(spawnSpy);124- assert.deepEqual(execArgs, ['--inspect-port=1.2.3.4:101']);125- });126-127- test('when --inspect-unexpected then unchanged', (t) => {128- const { spawnSpy } = makeSpies(t);129- const program = makeProgram();130- process.execArgv = ['--inspect-unexpected'];131- program.parse(['node', 'test', 'cache']);132- const execArgs = extractMockExecArgs(spawnSpy);133- assert.deepEqual(execArgs, ['--inspect-unexpected']);134- });135-136- test('when --frozen-intrinsics then unchanged', (t) => {137- const { spawnSpy } = makeSpies(t);138- const program = makeProgram();139- process.execArgv = ['--frozen-intrinsics '];140- program.parse(['node', 'test', 'cache']);141- const execArgs = extractMockExecArgs(spawnSpy);142- assert.deepEqual(execArgs, ['--frozen-intrinsics ']);143- });144-});modified:tests/negatives.test.js+4 added-4 removed
1-const { Command } = require('../');2-const { createTestCommand } = require('./testHelpers');3-const { test, describe } = require('node:test');4-const assert = require('node:assert/strict');1+import { Command } from '../index.js';2+import { createTestCommand } from './testHelpers.js';3+import { test, describe } from 'node:test';4+import assert from 'node:assert/strict';5 6 describe('negative numbers', () => {7 describe('negative numbers in args', () => {8 // boolean is whether is a consumable argument when negative numbers allowed191 unmodified linesmodified:tests/option.bad-flags.test.js+3 added-3 removed
1-const { Option } = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import { Option } from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Check that unsupported flags throw.6 describe('when construct Option with unsupported flags then throw', () => {7 const flagsList = [44 unmodified linesmodified:tests/option.chain.test.js+3 added-3 removed
1-const { Option } = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import { Option } from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 describe('Option methods that should return this for chaining', () => {6 test('when call .default() then returns this', () => {7 const option = new Option('-e,--example <value>');46 unmodified linesmodified:tests/options.bool.combo.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Test combination of flag and --no-flag6 // (single flags tested in options.bool.test.js)7 188 unmodified linesmodified:tests/options.bool.small.combined.test.js+3 added-3 removed
1-const commander = require('../');2-const { test } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test } from 'node:test';3+import assert from 'node:assert/strict';4 5 test('when when multiple short flags specified then parsed as short option group', () => {6 const program = new commander.Command();7 program8 unmodified linesmodified:tests/options.bool.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Test simple flag and negatable flag6 7 // boolean option on program131 unmodified linesmodified:tests/options.camelcase.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Capitalise the letters of words after dashes, but otherwise preserve case6 7 describe('option property is camelCase of option name', () => {42 unmodified linesmodified:tests/options.choices.test.js+4 added-4 removed
1-const commander = require('../');2-const { createTestCommand } = require('./testHelpers');3-const { test, describe } = require('node:test');4-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { createTestCommand } from './testHelpers.js';3+import { test, describe } from 'node:test';4+import assert from 'node:assert/strict';5 6 describe('Option.choices()', () => {7 test('when option argument in choices then option set', () => {8 const program = new commander.Command();48 unmodified linesmodified:tests/options.conflicts.test.js+6 added-6 removed
1-const path = require('path');2-const commander = require('../');3-const { createTestCommand } = require('./testHelpers');4-const { test, describe } = require('node:test');5-const assert = require('node:assert/strict');1+import * as path from 'path';2+import * as commander from '../index.js';3+import { createTestCommand } from './testHelpers.js';4+import { test, describe } from 'node:test';5+import assert from 'node:assert/strict';6 7 describe('Option.conflicts()', () => {8 function makeProgram(t) {9 const actionMock = t.mock.fn();370 unmodified lines380 381 program382 .addOption(new commander.Option('--black'))383 .addOption(new commander.Option('--white').conflicts('black'));384- const pm = path.join(__dirname, './fixtures/pm');384+ const pm = path.join(import.meta.dirname, './fixtures/pm');385 program.command('ext', 'external command', { executableFile: pm });386 387 try {388 program.parse('--white --black ext'.split(' '), { from: 'user' });7 unmodified linesmodified:tests/options.custom-processing.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 function myParseInt(value, dummyPrevious) {6 // parseInt takes a string and a radix7 return parseInt(value, 10);135 unmodified linesmodified:tests/options.default.test.js+3 added-3 removed
1-const { Command, Option } = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import { Command, Option } from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 describe('Command.option() with default value and option not specified in parse', () => {6 test('when boolean option with boolean default then value is default', () => {7 const program = new Command();188 unmodified linesmodified:tests/options.dual-options.test.js+4 added-4 removed
1-const { Option, DualOptions } = require('../lib/option.js');2-const { Command } = require('../');3-const { test, describe } = require('node:test');4-const assert = require('node:assert/strict');1+import { Option, DualOptions } from '../lib/option.js';2+import { Command } from '../index.js';3+import { test, describe } from 'node:test';4+import assert from 'node:assert/strict';5 6 // This tests an internal helper class which is not currently exposed on the package.7 8 describe('DualOptions internal helper class', () => {91 unmodified linesmodified:tests/options.env.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 describe('Option.env()', () => {6 // treating optional same as required, treat as option taking value rather than as boolean7 describe('option declared with value', () => {364 unmodified linesmodified:tests/options.flags.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Test the various ways flags can be specified in the first parameter to `.option`6 7 describe('option parsing', () => {70 unmodified linesmodified:tests/options.getset.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 describe('Command.getOptionValue() and .setOptionValue()', () => {6 describe('storeOptionsAsProperties', () => {7 const storeOptionsAsPropertiesList = [true, false];65 unmodified linesmodified:tests/options.implies.test.js+4 added-4 removed
1-const { Command, Option } = require('../');2-const { createTestCommand } = require('./testHelpers');3-const { test, describe } = require('node:test');4-const assert = require('node:assert/strict');1+import { Command, Option } from '../index.js';2+import { createTestCommand } from './testHelpers.js';3+import { test, describe } from 'node:test';4+import assert from 'node:assert/strict';5 6 describe('Option.implies()', () => {7 describe('check priorities', () => {8 test('when source undefined and implied undefined then implied is undefined', () => {212 unmodified linesmodified:tests/options.mandatory.test.js+4 added-4 removed
1-const commander = require('../');2-const { createTestCommand } = require('./testHelpers');3-const { test, describe } = require('node:test');4-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { createTestCommand } from './testHelpers.js';3+import { test, describe } from 'node:test';4+import assert from 'node:assert/strict';5 6 // Assuming mandatory options behave as normal options apart from the mandatory aspect, not retesting all behaviour.7 // Likewise, not redoing all tests on subcommand after testing on program.8 215 unmodified linesmodified:tests/options.optional.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // option with optional value, no default6 describe('option with optional value, no default', () => {7 test('when option not specified then value is undefined', () => {64 unmodified linesmodified:tests/options.opts.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Test the `.opts()` way of accessing option values.6 // Basic coverage of the main option types (leaving out negatable flags and options with optional values).7 67 unmodified linesmodified:tests/options.optsWithGlobals.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Testing optsWithGlobals and getOptionValueSourceWithGlobals with focus on globals.6 7 describe('Command.optsWithGlobals()', () => {109 unmodified linesmodified:tests/options.preset.test.js+3 added-3 removed
1-const { Command, Option } = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import { Command, Option } from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 describe('Option.preset()', () => {6 test('when boolean option with string preset used then value is preset', () => {7 const program = new Command();56 unmodified linesmodified:tests/options.registerClash.test.js+3 added-3 removed
1-const { Command, Option } = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import { Command, Option } from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 describe('registering clashing options', () => {6 test('when short option flag conflicts then throws', () => {7 assert.throws(59 unmodified linesmodified:tests/options.required.test.js+4 added-4 removed
1-const commander = require('../');2-const { createTestCommand } = require('./testHelpers');3-const { test, describe } = require('node:test');4-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { createTestCommand } from './testHelpers.js';3+import { test, describe } from 'node:test';4+import assert from 'node:assert/strict';5 6 // option with required value, no default7 describe('option with required option-argument, no default', () => {8 test('when option not specified then value is undefined', () => {62 unmodified linesmodified:tests/options.twice.test.js+3 added-3 removed
1-const { Command, Option } = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import { Command, Option } from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Test that when option specified twice, second use wins.6 // Seems pretty obvious for boolean options, but there was a bug before Commander v9.7 43 unmodified linesmodified:tests/options.values.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Test the ways values can be specified for options.6 // See also references on "Utility Conventions" in command.parseOptions.test.js7 81 unmodified linesmodified:tests/options.variadic.test.js+4 added-4 removed
1-const commander = require('../');2-const { createTestCommand } = require('./testHelpers');3-const { test, describe } = require('node:test');4-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { createTestCommand } from './testHelpers.js';3+import { test, describe } from 'node:test';4+import assert from 'node:assert/strict';5 6 describe('variadic options', () => {7 describe('variadic option with required option-argument', () => {8 test('when variadic with value missing then error', () => {175 unmodified linesmodified:tests/options.version.test.js+3 added-3 removed
1-const commander = require('../');2-const { test, describe } = require('node:test');3-const assert = require('node:assert/strict');1+import * as commander from '../index.js';2+import { test, describe } from 'node:test';3+import assert from 'node:assert/strict';4 5 // Test .version. Using exitOverride to check behaviour (instead of mocking process.exit).6 7 describe('Command.version()', () => {176 unmodified linesmodified:tests/testHelpers.js+2 added-4 removed
1-const { Command } = require('../');1+import { Command } from '../index.js';2 3 /**4 * Create a Command configured for using in tests.5 *2 unmodified lines8 *9 * @returns Command10 */11 12-function createTestCommand() {12+export function createTestCommand() {13 const cmd = new Command();14 cmd15 .exitOverride() // So we get exceptions instead of process.exit16 .configureOutput({1 unmodified line18 writeErr: () => {},19 });20 return cmd;21 }22-23-exports.createTestCommand = createTestCommand;modified:tests/useColor.test.js+3 added-3 removed
1-const { useColor } = require('../lib/command.js');2-const { test, describe, beforeEach, after } = require('node:test');3-const assert = require('node:assert/strict');1+import { useColor } from '../lib/command.js';2+import { test, describe, beforeEach, after } from 'node:test';3+import assert from 'node:assert/strict';4 5 describe('internal useColor environment variable support', () => {6 let holdNoColor = process.env.NO_COLOR;7 let holdForceColor = process.env.FORCE_COLOR;83 unmodified linesdeleted:typings/esm.d.mts-3 removed
1-// Just reexport the types from cjs2-// This is a bit indirect. There is not an index.js, but TypeScript will look for index.d.ts for types.3-export * from './index.js';modified:typings/index.d.ts+3 added-3 removed
956 unmodified lines957 name(): string;958 959 /**960 * Set the name of the command from script filename, such as process.argv[1],961- * or require.main.filename, or __filename.961+ * or import.meta.filename.962 *963 * (Used internally and public although not documented in README.)964 *965 * @example966 * ```ts967- * program.nameFromFilename(require.main.filename);967+ * program.nameFromFilename(import.meta.filename);968 * ```969 *970 * @returns `this` command for chaining971 */3 unmodified lines975 * Set the directory for searching for executable subcommands of this command.976 *977 * @example978 * ```ts979- * program.executableDir(__dirname);979+ * program.executableDir(import.meta.dirname);980 * // or981 * program.executableDir('subcommands');982 * ```983 *130 unmodified linesmodified:typings/index.test-d.ts+3 added-3 removed
1-import * as commander from './index';1+import * as commander from './index.js';2 import { expectType } from 'tsd';3 4 // We are not just checking return types here, we are also implicitly checking that the expected syntax is allowed.5 437 unmodified lines443 expectType<commander.Command>(program.optionsGroup('My Group'));444 expectType<string>(program.optionsGroup());445 446 // nameFromFilename447-expectType<commander.Command>(program.nameFromFilename(__filename));447+expectType<commander.Command>(program.nameFromFilename(import.meta.filename));448 449 // executableDir450-expectType<commander.Command>(program.executableDir(__dirname));450+expectType<commander.Command>(program.executableDir(import.meta.dirname));451 expectType<string | null>(program.executableDir());452 453 // outputHelp454 expectType<void>(program.outputHelp());333 unmodified linesmodified:.prettierrc.js+1 added-3 removed
1-const config = {1+export default {2 singleQuote: true,3 overrides: [4 {5 files: ['tsconfig*.json'],6 options: { parser: 'jsonc' },7 },8 ],9 };10-11-module.exports = config;modified:CHANGELOG.md+39 added
6 unmodified lines7 8 <!-- markdownlint-disable MD024 -->9 <!-- markdownlint-disable MD004 -->10 11+## [15.0.0] (2026-05-15)12+13+_date is placeholder, Node.js 20 EOL on 2026-04-30_14+15+Commander 15 is ESM only. This is expected to be seamless for ESM consumers, but some CommonJS consumers may hit issues with tooling requiring configuration for ESM-only dependencies. See Migration Tips below.16+17+The release of Commander 15 moves Commander 14 into maintenance. Commander 14 will get security updates for 12 months.18+For more info see [Release Policy](./docs/release-policy.md).19+20+### Added21+22+### Fixed23+24+### Changed25+26+- *Breaking:* migrated Commander implementation from CommonJS to ESM ([#2464])27+- *Breaking:* Commander 15 requires Node.js v20 or higher. To be more precise, `^20.19.0 || >=22.12.0` for `require(esm)`.28+- dev: switch tests from Jest to `node:test` test runner ([#2463])29+30+### Deleted31+32+- *Breaking:* removed deprecated export of `commander/esm.mjs` ([#2464])33+34+### Migration Tips35+36+Commander 15 is ESM only, but this does not mean you need to migrate to ESM to use it. Importing ESM from CommonJS is37+supported by Node.js, and Bun, and Deno. Hopefully it Just Works for you! However, you may be using a different runtime or38+some other part of your setup that may not yet natively support importing ESM from CommonJS, such as your testing framework39+or bundler.40+41+If you have problems using Commander 15 in your environment, one option is stay on Commander 14 for now. Commander 14 will42+get security updates until May 2027 and things will hopefully improve for your setup in the meantime.43+44+To allow `require(esm)` from CommonJS you may be able to make small changes to your current setup. Some45+examples for Jest are included in [examples/using-esm-from-commonjs](./examples/using-esm-from-commonjs).46+(Commander was using Jest, so we have a special interest.)47+48 ## [14.0.3] (2026-01-31)49 50 ### Added51 1438 unmodified lines1490 [#2410]: https://github.com/tj/commander.js/pull/24101491 [#2427]: https://github.com/tj/commander.js/pull/24271492 [#2428]: https://github.com/tj/commander.js/pull/24281493 [#2462]: https://github.com/tj/commander.js/pull/24621494+[#2463]: https://github.com/tj/commander.js/pull/24631495+[#2464]: https://github.com/tj/commander.js/pull/24641496 [#2465]: https://github.com/tj/commander.js/pull/24651497 1498 <!-- Referenced in 5.x -->1499 [#1]: https://github.com/tj/commander.js/issues/1135 unmodified linesmodified:eslint.config.js+5 added-5 removed
1-const globals = require('globals');2-const esLintjs = require('@eslint/js');3-const tseslint = require('typescript-eslint');4-const prettier = require('eslint-config-prettier');1+import globals from 'globals';2+import esLintjs from '@eslint/js';3+import tseslint from 'typescript-eslint';4+import prettier from 'eslint-config-prettier';5 6 // Only run tseslint on the files that we have included for TypeScript.7 const tsconfigTsFiles = ['**/*.{ts,mts}']; // match "include" in tsconfig.ts.json;8 const tsconfigJsFiles = ['*.{js,mjs}', 'lib/**/*.{js,mjs}']; // match "include" in tsconfig.js.json9 10 // Using tseslint.config adds some type safety and `extends` to simplify customising config array.11-module.exports = tseslint.config(11+export default tseslint.config(12 // Add recommended rules.13 esLintjs.configs.recommended,14 // tseslint with different setup for js/ts15 {52 unmodified linesdeleted:esm.mjs-16 removed
1-import commander from './index.js';2-3-// wrapper to provide named exports for ESM.4-export const {5- program,6- createCommand,7- createArgument,8- createOption,9- CommanderError,10- InvalidArgumentError,11- InvalidOptionArgumentError, // deprecated old name12- Command,13- Argument,14- Option,15- Help,16-} = commander;modified:index.js+14 added-17 removed
1-const { Argument } = require('./lib/argument.js');2-const { Command } = require('./lib/command.js');3-const { CommanderError, InvalidArgumentError } = require('./lib/error.js');4-const { Help } = require('./lib/help.js');5-const { Option } = require('./lib/option.js');1+import { Argument } from './lib/argument.js';2+import { Command } from './lib/command.js';3+import { CommanderError, InvalidArgumentError } from './lib/error.js';4+import { Help } from './lib/help.js';5+import { Option } from './lib/option.js';6 7-exports.program = new Command();7+export const program = new Command();8 9-exports.createCommand = (name) => new Command(name);10-exports.createOption = (flags, description) => new Option(flags, description);11-exports.createArgument = (name, description) => new Argument(name, description);9+export const createCommand = (name) => new Command(name);10+export const createOption = (flags, description) =>11+ new Option(flags, description);12+export const createArgument = (name, description) =>13+ new Argument(name, description);14 15 /**16 * Expose classes17 */18 17-exports.Command = Command;18-exports.Option = Option;19-exports.Argument = Argument;20-exports.Help = Help;21-22-exports.CommanderError = CommanderError;23-exports.InvalidArgumentError = InvalidArgumentError;24-exports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated19+export { Command, Option, Argument, Help };20+export { CommanderError, InvalidArgumentError };21+export { InvalidArgumentError as InvalidOptionArgumentError }; // Deprecateddeleted:jest.config.js-10 removed
1-const config = {2- testEnvironment: 'node',3- collectCoverage: true,4- transform: {5- '^.+\\.tsx?$': ['ts-jest', { tsconfig: 'tsconfig.ts.json' }],6- },7- testPathIgnorePatterns: ['/node_modules/'],8-};9-10-module.exports = config;modified:package.json+3 added-16 removed
32 unmodified lines33 },34 "files": [35 "index.js",36 "lib/*.js",37- "esm.mjs",37 "typings/index.d.ts",39- "typings/esm.d.mts",38 "package-support.json"39 ],42- "type": "commonjs",40+ "type": "module",41 "main": "./index.js",42 "exports": {43 ".": {46- "require": {47- "types": "./typings/index.d.ts",44+ "types": "./typings/index.d.ts",48- "default": "./index.js"49- },50- "import": {51- "types": "./typings/esm.d.mts",52- "default": "./esm.mjs"53- },45 "default": "./index.js"55- },56- "./esm.mjs": {57- "types": "./typings/esm.d.mts",58- "import": "./esm.mjs"46 }47 },48 "devDependencies": {49 "@eslint/js": "^9.4.0",7 unmodified lines57 "typescript-eslint": "^8.12.2"58 },59 "types": "typings/index.d.ts",60 "engines": {74- "node": ">=20"61+ "node": "^20.19.0 || >=22.12.0"62 },63 "support": true64 }modified:Readme.md+6 added-7 removed
74 unmodified lines75 76 Example file: [split.js](./examples/split.js)77 78 ```js79-const { program } = require('commander');79+import { program } from 'commander';80 81 program82 .option('--first')83 .option('-s, --separator <char>')18 unmodified lines102 103 Example file: [string-util.js](./examples/string-util.js)104 105 ```js106-const { Command } = require('commander');106+import { Command } from 'commander';107 const program = new Command();108 109 program110 .name('string-util')35 unmodified lines146 147 ## Declaring _program_ variable148 149 Commander exports a global object which is convenient for quick programs.150-This is used in the examples in this README for brevity.150+This is used in some examples in this README for brevity.151 152 ```js153-// CommonJS (.cjs)154-const { program } = require('commander');153+import { program } from 'commander';154 ```155 156 For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local `Command` object to use.157 395 unmodified lines553 Configuration options can be passed with the call to `.command()` and `.addCommand()`. Specifying `hidden: true` will554 remove the command from the generated help output. Specifying `isDefault: true` will run the subcommand if no other555 subcommand is specified. (Example file: [defaultCommand.js](./examples/defaultCommand.js).)556 558-You can add alternative names for a command with `.alias()`. (Example file: [alias.js](./examples/alias.js).)557+You can add alternative names for a command with `.alias()`. (Example file: [alias.cjs](./examples/alias.cjs).)558 559 `.command()` automatically copies the inherited settings from the parent command to the newly created subcommand. This is only done during creation; any later setting changes to the parent are not inherited.560 561 For safety, `.addCommand()` does not automatically copy the inherited settings from the parent command. There is a helper routine `.copyInheritedSettings()` for copying the settings when they are wanted.493 unmodified lines1055 1056 This factory function creates a new command. It is exported and may be used instead of using `new`, like:1057 1058 ```js1060-const { createCommand } = require('commander');1059+import { createCommand } from 'commander';1060 const program = createCommand();1061 ```1062 1063 `createCommand()` is also a method of the `Command` object, and creates a new command rather than a subcommand. This gets used internally109 unmodified lines