Пример
commander 9.5.0: Command
Проверенный пример — npm commander 9.5.0: Command. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: Command initializes CLI programs with…
sha256:1b8003366ebc357ffc0e473d2e7e64ee1d15c9d9830c9d11bb301ac5a1a10ba2
Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла.
Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди.
MIT-0
Свидетельства выполнения
Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.
- Основа свидетельства
- Подписанный контракт пройден
- Квитанции проверки
- 2
- Ключи подписи, собравшие его
- 1
Заявленная среда
linux 24 · ubuntu · glibc 2.39 x64 npm
Среды запусков проверки
| Окружение | Контракт | Этапы | Запуск |
|---|---|---|---|
| node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5… |
2026-08-23 |
| node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2… |
2026-09-07 |
Кейс
HOW- Цель
- verify commander.Command in pkg:npm/commander@9.5.0
- Пакеты
- Символы
-
- commander.Command
- Создан
- 2026-08-23T06:55:27Z
Контракт
- Command initializes CLI programs with configurable name, description, and version metadata
- Command.option and Command.requiredOption parse boolean flags and values with default fallbacks
- Command.command and Command.addCommand register subcommands with dedicated action handlers and argument parsing
- Command.action executes action callbacks receiving parsed positional arguments and options
- Command.hook executes preAction and postAction lifecycle hooks around command execution
- Command.exitOverride intercepts help and missing argument errors by throwing CommanderError
Файлы
- PROMPT.md
- csx.json
- index.js
- package-lock.json
- package.json
- spec.json
- test/contract.js
Исходный код
Clean-room public code sample — generation instructions
Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.
A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.
Goal: verify commander.Command in pkg:npm/commander@9.5.0
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/commander@9.5.0
Demonstrate these symbols/APIs:
- commander.Command
Rules:
- One focused purpose; the smallest project that proves the goal.
- Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
- Pin every dependency with a lockfile so resolution is reproducible.
- No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
- No personal names, emails, company names, or project identifiers of any kind.
- No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
- Keep it under 200 files and 256KB packed.
{"case":{"caseId":"case:sha256:1fd11796291272f317d48a6f2834084bb3d959653d9337793253bf51ee5b64e0","contract":["Command initializes CLI programs with configurable name, description, and version metadata","Command.option and Command.requiredOption parse boolean flags and values with default fallbacks","Command.command and Command.addCommand register subcommands with dedicated action handlers and argument parsing","Command.action executes action callbacks receiving parsed positional arguments and options","Command.hook executes preAction and postAction lifecycle hooks around command execution","Command.exitOverride intercepts help and missing argument errors by throwing CommanderError"],"goal":"verify commander.Command in pkg:npm/commander@9.5.0","kind":"HOW","packages":["pkg:npm/commander@9.5.0"],"schemaVersion":1,"symbols":["commander.Command"]},"contractCommand":["node","test/contract.js"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/commander@9.5.0"],"schemaVersion":1,"subject":"pkg:npm/commander@9.5.0","symbols":["commander.Command"],"verifierAdapter":"node-typescript@1"}
'use strict';
const { Command, CommanderError, InvalidArgumentError } = require('commander');
/**
* Creates a base Command instance with name, description, and version.
* @param {string} name
* @param {string} description
* @param {string} version
* @returns {Command}
*/
function createProgram(name, description, version) {
const program = new Command(name);
if (description) {
program.description(description);
}
if (version) {
program.version(version, '-V, --version', 'output the version number');
}
program.exitOverride();
return program;
}
/**
* Builds a Command demonstrating optional, required, and custom-parsed options.
* @returns {{ program: Command, getOpts: () => Record<string, any> }}
*/
function createOptionCommand() {
const program = new Command('serve').exitOverride();
let capturedOpts = null;
program
.requiredOption('-c, --config <path>', 'path to configuration file')
.option('-p, --port <number>', 'server port', (val) => {
const parsed = parseInt(val, 10);
if (isNaN(parsed) || parsed <= 0 || parsed > 65535) {
throw new InvalidArgumentError('Port must be a valid port number (1-65535).');
}
return parsed;
}, 3000)
.option('-d, --debug', 'enable debug logging', false)
.action((opts) => {
capturedOpts = opts;
});
return {
program,
getOpts: () => capturedOpts || program.opts()
};
}
/**
* Builds a Command with subcommands and positional arguments.
* @returns {{ program: Command, getResult: () => any }}
*/
function createSubcommandProgram() {
const program = new Command('git-cli').exitOverride();
let lastResult = null;
program
.command('clone <repository> [destination]')
.description('clone a repository into a directory')
.option('--depth <depth>', 'create a shallow clone', (v) => parseInt(v, 10))
.action((repository, destination, options) => {
lastResult = {
subcommand: 'clone',
repository,
destination: destination || null,
depth: options.depth || null
};
});
const commitCmd = new Command('commit')
.description('record changes to the repository')
.requiredOption('-m, --message <msg>', 'commit message')
.action((options) => {
lastResult = {
subcommand: 'commit',
message: options.message
};
});
program.addCommand(commitCmd);
return {
program,
getResult: () => lastResult
};
}
/**
* Builds a Command demonstrating preAction and postAction lifecycle hooks.
* @returns {{ program: Command, getTrace: () => string[] }}
*/
function createHookedProgram() {
const trace = [];
const program = new Command('pipeline').exitOverride();
program
.hook('preAction', (thisCommand, actionCommand) => {
trace.push(`preAction:${thisCommand.name()}->${actionCommand.name()}`);
})
.hook('postAction', (thisCommand, actionCommand) => {
trace.push(`postAction:${thisCommand.name()}->${actionCommand.name()}`);
});
program
.command('run <stage>')
.action((stage) => {
trace.push(`exec:${stage}`);
});
return {
program,
getTrace: () => trace
};
}
module.exports = {
Command,
CommanderError,
InvalidArgumentError,
createProgram,
createOptionCommand,
createSubcommandProgram,
createHookedProgram
};
{
"name": "sample-commander-command",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-commander-command",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"commander": "9.5.0"
}
},
"node_modules/commander": {
"version": "9.5.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-9.5.0.tgz",
"integrity": "sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==",
"license": "MIT",
"engines": {
"node": "^12.20.0 || >=14"
}
}
}
}
{
"name": "sample-commander-command",
"version": "1.0.0",
"private": true,
"description": "verify commander.Command in pkg:npm/commander@9.5.0",
"main": "index.js",
"scripts": {
"test": "node test/contract.js"
},
"dependencies": {
"commander": "9.5.0"
},
"license": "MIT-0"
}
{
"schemaVersion": 1,
"goal": "verify commander.Command in pkg:npm/commander@9.5.0",
"kind": "HOW",
"packages": [
"pkg:npm/commander@9.5.0"
],
"symbols": [
"commander.Command"
]
}
'use strict';
const assert = require('assert');
const {
Command,
CommanderError,
InvalidArgumentError,
createProgram,
createOptionCommand,
createSubcommandProgram,
createHookedProgram
} = require('../index.js');
function testProgramMetadata() {
const program = createProgram('sample-cli', 'A sample CLI tool', '1.2.3');
program.configureOutput({ writeOut: () => {}, writeErr: () => {} });
assert.strictEqual(program.name(), 'sample-cli');
assert.strictEqual(program.description(), 'A sample CLI tool');
assert.strictEqual(program.version(), '1.2.3');
// Verify --version throws CommanderError due to exitOverride
assert.throws(
() => {
program.parse(['node', 'sample-cli', '--version']);
},
(err) => {
assert.strictEqual(err.code, 'commander.version');
assert.strictEqual(err.exitCode, 0);
return true;
}
);
}
function testOptionParsingAndDefaults() {
// Test with full options provided
const { program: prog1, getOpts: getOpts1 } = createOptionCommand();
prog1.configureOutput({ writeOut: () => {}, writeErr: () => {} });
prog1.parse(['node', 'serve', '-c', 'config.json', '-p', '9000', '-d']);
assert.deepStrictEqual(getOpts1(), {
config: 'config.json',
port: 9000,
debug: true
});
// Test with defaults for optional flags
const { program: prog2, getOpts: getOpts2 } = createOptionCommand();
prog2.configureOutput({ writeOut: () => {}, writeErr: () => {} });
prog2.parse(['node', 'serve', '-c', 'app.json']);
assert.deepStrictEqual(getOpts2(), {
config: 'app.json',
port: 3000,
debug: false
});
}
function testSubcommandsAndPositionalArgs() {
// Test command() definition
const { program: prog1, getResult: getResult1 } = createSubcommandProgram();
prog1.configureOutput({ writeOut: () => {}, writeErr: () => {} });
prog1.parse(['node', 'git-cli', 'clone', 'https://example.com/repo.git', 'dest-dir', '--depth', '1']);
assert.deepStrictEqual(getResult1(), {
subcommand: 'clone',
repository: 'https://example.com/repo.git',
destination: 'dest-dir',
depth: 1
});
// Test addCommand() definition
const { program: prog2, getResult: getResult2 } = createSubcommandProgram();
prog2.configureOutput({ writeOut: () => {}, writeErr: () => {} });
prog2.parse(['node', 'git-cli', 'commit', '-m', 'Initial commit']);
assert.deepStrictEqual(getResult2(), {
subcommand: 'commit',
message: 'Initial commit'
});
}
function testActionExecutionAndParsing() {
const program = new Command('calc').exitOverride();
program.configureOutput({ writeOut: () => {}, writeErr: () => {} });
let executed = false;
let capturedArg = null;
let capturedOpts = null;
program
.argument('<num>', 'number to double')
.option('-s, --step <n>', 'step increment', (v) => parseInt(v, 10), 1)
.action((num, options) => {
executed = true;
capturedArg = num;
capturedOpts = options;
});
program.parse(['10', '--step', '5'], { from: 'user' });
assert.strictEqual(executed, true);
assert.strictEqual(capturedArg, '10');
assert.strictEqual(capturedOpts.step, 5);
}
function testLifecycleHooks() {
const { program, getTrace } = createHookedProgram();
program.configureOutput({ writeOut: () => {}, writeErr: () => {} });
program.parse(['node', 'pipeline', 'run', 'build']);
assert.deepStrictEqual(getTrace(), [
'preAction:pipeline->run',
'exec:build',
'postAction:pipeline->run'
]);
}
function testExitOverrideAndErrorHandling() {
// Missing mandatory option
const { program: missingOptProg } = createOptionCommand();
missingOptProg.configureOutput({ writeOut: () => {}, writeErr: () => {} });
assert.throws(
() => {
missingOptProg.parse(['node', 'serve']);
},
(err) => {
assert.strictEqual(err.code, 'commander.missingMandatoryOptionValue');
return true;
}
);
// Custom parser error (InvalidArgumentError)
const { program: invalidOptProg } = createOptionCommand();
invalidOptProg.configureOutput({ writeOut: () => {}, writeErr: () => {} });
assert.throws(
() => {
invalidOptProg.parse(['node', 'serve', '-c', 'cfg.json', '-p', 'invalid-port']);
},
(err) => {
assert.strictEqual(err.code, 'commander.invalidArgument');
return true;
}
);
// Unknown option error
const unknownOptProg = createProgram('tool').exitOverride();
unknownOptProg.configureOutput({ writeOut: () => {}, writeErr: () => {} });
assert.throws(
() => {
unknownOptProg.parse(['node', 'tool', '--unknown-flag']);
},
(err) => {
assert.strictEqual(err.code, 'commander.unknownOption');
return true;
}
);
}
function run() {
testProgramMetadata();
testOptionParsingAndDefaults();
testSubcommandsAndPositionalArgs();
testActionExecutionAndParsing();
testLifecycleHooks();
testExitOverrideAndErrorHandling();
console.log('Contract tests passed successfully.');
process.exit(0);
}
run();
Исходный сидер
аноним