CodeSampleX

Sample

commander 9.5.0

Verified sample for npm commander 9.5.0. The contract ran on node 22 · linux alpine/x64 · docker and passed: Command configures program metadata including…

sha256:a0855c0580558d6310c9341463f5bdb3a6bdb7f95900a70a5966202003096c2b

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
2
Signing keys that built it
1
Declared environment linux 24 · ubuntu · glibc 2.39 x64 npm

Verification-run environments

Environment Contract Stages Run
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

Case

HOW
Goal
verify pkg:npm/commander@9.5.0
Packages
Created
2026-08-23T06:50:52Z

Contract

  1. Command configures program metadata including name, version, description, and summary
  2. Option supports choices validation, default fallback values, and mutual conflict detection
  3. Argument parses positional parameters with custom argument parsing functions and default values
  4. Command registers subcommands and executes lifecycle hooks including preAction and postAction
  5. Command supports negated boolean options with --no prefix and custom accumulator reducer options
  6. Command exitOverride throws CommanderError on missing mandatory options, unknown commands, or invalid arguments

Files

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • test/contract.mjs

Download the source artifact (tar.gz)

Source

PROMPT.md
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 pkg:npm/commander@9.5.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/commander@9.5.0

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.
csx.json
{"case":{"caseId":"case:sha256:376b2ccdec9ec0554976e8d8a028e1af305e26492abf316ee2e0e8eca4a80548","contract":["Command configures program metadata including name, version, description, and summary","Option supports choices validation, default fallback values, and mutual conflict detection","Argument parses positional parameters with custom argument parsing functions and default values","Command registers subcommands and executes lifecycle hooks including preAction and postAction","Command supports negated boolean options with --no prefix and custom accumulator reducer options","Command exitOverride throws CommanderError on missing mandatory options, unknown commands, or invalid arguments"],"goal":"verify pkg:npm/commander@9.5.0","kind":"HOW","packages":["pkg:npm/commander@9.5.0"],"schemaVersion":1},"contractCommand":["node","test/contract.mjs"],"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","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-commander",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-commander",
      "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"
      }
    }
  }
}
package.json
{
  "name": "sample-commander",
  "version": "1.0.0",
  "description": "Clean-room verification sample for commander",
  "type": "module",
  "main": "src/index.mjs",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "commander": "9.5.0"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/commander@9.5.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/commander@9.5.0"
  ]
}
src/index.mjs
import { Command, Option, Argument, CommanderError, InvalidArgumentError } from 'commander';

/**
 * Creates a configured base Command instance with exitOverride enabled.
 *
 * @param {object} [options]
 * @param {string} [options.name]
 * @param {string} [options.version]
 * @param {string} [options.description]
 * @param {string} [options.summary]
 * @returns {Command}
 */
export function createProgram(options = {}) {
  const program = new Command();
  if (options.name) program.name(options.name);
  if (options.version) program.version(options.version);
  if (options.description) program.description(options.description);
  if (options.summary) program.summary(options.summary);
  program.exitOverride();
  program.configureOutput({
    writeOut: () => {},
    writeErr: () => {}
  });
  return program;
}

/**
 * Configures options with choices, conflicts, and defaults.
 *
 * @param {Command} program
 * @returns {Command}
 */
export function configureAdvancedOptions(program) {
  return program
    .addOption(new Option('-e, --env <environment>', 'target deployment environment').choices(['development', 'staging', 'production']).default('development'))
    .addOption(new Option('-q, --quiet', 'suppress standard output').conflicts('verbose'))
    .addOption(new Option('-v, --verbose', 'enable verbose logging'))
    .addOption(new Option('--no-cache', 'disable response caching'))
    .addOption(new Option('-t, --tag <tag>', 'tag names (repeatable)').argParser((val, prev) => prev.concat([val])).default([]));
}

/**
 * Configures typed arguments with a custom parser.
 *
 * @param {Command} program
 * @param {function} actionHandler
 * @returns {Command}
 */
export function configureTypedArguments(program, actionHandler) {
  const parsePort = (value) => {
    const port = parseInt(value, 10);
    if (isNaN(port) || port < 1 || port > 65535) {
      throw new InvalidArgumentError('Port must be a valid integer between 1 and 65535.');
    }
    return port;
  };

  return program
    .addArgument(new Argument('<port>', 'server listening port').argParser(parsePort))
    .addArgument(new Argument('[host]', 'bind hostname').default('127.0.0.1'))
    .action(actionHandler);
}

/**
 * Registers subcommands with preAction and postAction lifecycle hooks.
 *
 * @param {Command} program
 * @param {object} [callbacks]
 * @param {function} [callbacks.onPreAction]
 * @param {function} [callbacks.onPostAction]
 * @param {function} [callbacks.onBuild]
 * @returns {Command}
 */
export function registerLifecycleCommands(program, callbacks = {}) {
  if (callbacks.onPreAction) {
    program.hook('preAction', callbacks.onPreAction);
  }
  if (callbacks.onPostAction) {
    program.hook('postAction', callbacks.onPostAction);
  }

  program
    .command('build <target>')
    .description('compile project artifacts')
    .option('-m, --minify', 'minify compiled code')
    .action((target, options) => {
      if (callbacks.onBuild) {
        callbacks.onBuild({ target, minify: Boolean(options.minify) });
      }
    });

  return program;
}

export { Command, Option, Argument, CommanderError, InvalidArgumentError };
test/contract.mjs
import assert from 'node:assert/strict';
import {
  createProgram,
  configureAdvancedOptions,
  configureTypedArguments,
  registerLifecycleCommands,
  Command,
  Option,
  Argument,
  CommanderError,
  InvalidArgumentError
} from '../src/index.mjs';

// 1. Command configures program metadata including name, version, description, and summary
{
  const program = createProgram({
    name: 'sample-tool',
    version: '9.5.0',
    description: 'Sample CLI tool for verifying commander',
    summary: 'CLI verification tool'
  });

  assert.equal(program.name(), 'sample-tool');
  assert.equal(program.version(), '9.5.0');
  assert.equal(program.description(), 'Sample CLI tool for verifying commander');
  assert.equal(program.summary(), 'CLI verification tool');
}

// 2. Option supports choices validation, default fallback values, and mutual conflict detection
{
  const program = createProgram();
  configureAdvancedOptions(program);

  // Default values
  program.parse(['node', 'cli.js']);
  assert.equal(program.opts().env, 'development');

  // Valid choices
  const stagingProgram = createProgram();
  configureAdvancedOptions(stagingProgram);
  stagingProgram.parse(['node', 'cli.js', '-e', 'staging']);
  assert.equal(stagingProgram.opts().env, 'staging');

  // Invalid choice throws CommanderError
  const invalidProgram = createProgram();
  configureAdvancedOptions(invalidProgram);
  assert.throws(
    () => invalidProgram.parse(['node', 'cli.js', '-e', 'invalid-env']),
    (err) => err instanceof CommanderError && err.code === 'commander.invalidArgument'
  );

  // Conflicting options throw CommanderError
  const conflictProgram = createProgram();
  configureAdvancedOptions(conflictProgram);
  assert.throws(
    () => conflictProgram.parse(['node', 'cli.js', '-q', '-v']),
    (err) => err instanceof CommanderError && err.code === 'commander.conflictingOption'
  );
}

// 3. Argument parses positional parameters with custom argument parsing functions and default values
{
  let parsedResult = null;
  const program = createProgram();
  configureTypedArguments(program, (port, host) => {
    parsedResult = { port, host };
  });

  program.parse(['node', 'cli.js', '3000']);
  assert.deepEqual(parsedResult, { port: 3000, host: '127.0.0.1' });

  // Custom argument parsing error throws InvalidArgumentError wrapped in CommanderError
  const invalidArgProgram = createProgram();
  configureTypedArguments(invalidArgProgram, () => {});
  assert.throws(
    () => invalidArgProgram.parse(['node', 'cli.js', 'invalid-port']),
    (err) => err instanceof CommanderError && err.code === 'commander.invalidArgument'
  );
}

// 4. Command registers subcommands and executes lifecycle hooks including preAction and postAction
{
  const executionOrder = [];
  let buildResult = null;

  const program = createProgram();
  registerLifecycleCommands(program, {
    onPreAction: (thisCommand, actionCommand) => {
      executionOrder.push(`pre:${actionCommand.name()}`);
    },
    onPostAction: (thisCommand, actionCommand) => {
      executionOrder.push(`post:${actionCommand.name()}`);
    },
    onBuild: (data) => {
      executionOrder.push(`action:build:${data.target}`);
      buildResult = data;
    }
  });

  program.parse(['node', 'cli.js', 'build', 'bundle.js', '--minify']);
  assert.deepEqual(executionOrder, ['pre:build', 'action:build:bundle.js', 'post:build']);
  assert.deepEqual(buildResult, { target: 'bundle.js', minify: true });
}

// 5. Command supports negated boolean options with --no prefix and custom accumulator reducer options
{
  const program = createProgram();
  configureAdvancedOptions(program);

  program.parse(['node', 'cli.js', '--no-cache', '-t', 'alpha', '-t', 'beta']);
  const opts = program.opts();
  assert.equal(opts.cache, false);
  assert.deepEqual(opts.tag, ['alpha', 'beta']);
}

// 6. Command exitOverride throws CommanderError on missing mandatory options, unknown commands, or invalid arguments
{
  const requiredOptProgram = createProgram();
  requiredOptProgram.requiredOption('-c, --config <file>', 'path to config');
  assert.throws(
    () => requiredOptProgram.parse(['node', 'cli.js']),
    (err) => err instanceof CommanderError && err.code === 'commander.missingMandatoryOptionValue'
  );

  const unknownCmdProgram = createProgram();
  unknownCmdProgram.command('start');
  assert.throws(
    () => unknownCmdProgram.parse(['node', 'cli.js', 'nonexistent-command']),
    (err) => err instanceof CommanderError && err.code === 'commander.unknownCommand'
  );
}

console.log('Contract tests passed successfully.');

Origin Seeder

anonymous