CodeSampleX

샘플

commander 5.1.0

검증된 샘플 — npm commander 5.1.0. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: Command configures program metadata and parses flags with default…

sha256:6537dc473bb9c6608abd8dddbc0d0ee2cbe18122d2b65b1fdd0f838a0499a561

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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-08

케이스

HOW
목표
verify pkg:npm/commander@5.1.0
패키지
생성일
2026-08-23T06:48:37Z

컨트랙트

  1. Command configures program metadata and parses flags with default and boolean values
  2. Command parses options with required values and custom type coercion functions
  3. Command supports negated boolean options with --no prefix
  4. Command registers subcommands with positional arguments and executes action handlers
  5. Command supports exitOverride to throw CommanderError on missing required options or invalid commands
  6. Command supports custom accumulator option functions for repeated flags

파일

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

소스 아티팩트 내려받기 (tar.gz)

소스

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@5.1.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/commander@5.1.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:232ce22a785f721ccbb2fc2355543c82af6482ca256e7d3b71a0159f331da5f1","contract":["Command configures program metadata and parses flags with default and boolean values","Command parses options with required values and custom type coercion functions","Command supports negated boolean options with --no prefix","Command registers subcommands with positional arguments and executes action handlers","Command supports exitOverride to throw CommanderError on missing required options or invalid commands","Command supports custom accumulator option functions for repeated flags"],"goal":"verify pkg:npm/commander@5.1.0","kind":"HOW","packages":["pkg:npm/commander@5.1.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@5.1.0"],"schemaVersion":1,"subject":"pkg:npm/commander@5.1.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": "5.1.0"
      }
    },
    "node_modules/commander": {
      "version": "5.1.0",
      "resolved": "https://registry.npmjs.org/commander/-/commander-5.1.0.tgz",
      "integrity": "sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg==",
      "license": "MIT",
      "engines": {
        "node": ">= 6"
      }
    }
  }
}
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": "5.1.0"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/commander@5.1.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/commander@5.1.0"
  ]
}
src/index.mjs
import { Command, CommanderError } from 'commander';

/**
 * Creates a configured base Command instance.
 *
 * @param {object} [options]
 * @param {string} [options.name]
 * @param {string} [options.version]
 * @param {string} [options.description]
 * @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);
  program.exitOverride();
  return program;
}

/**
 * Configures basic flags, options with defaults, and negation flags on a program.
 *
 * @param {Command} program
 * @returns {Command}
 */
export function configureStandardOptions(program) {
  return program
    .option('-v, --verbose', 'enable verbose logging')
    .option('-p, --port <number>', 'port number to bind', (val) => parseInt(val, 10), 8080)
    .option('-h, --host <hostname>', 'hostname to bind', 'localhost')
    .option('--no-cache', 'disable response caching');
}

/**
 * Registers subcommands with action handlers on a program.
 *
 * @param {Command} program
 * @param {object} [actions]
 * @param {function} [actions.onGreet]
 * @param {function} [actions.onAdd]
 * @returns {Command}
 */
export function registerSubcommands(program, actions = {}) {
  program
    .command('greet <name>')
    .description('generate a greeting message')
    .option('-g, --greeting <phrase>', 'custom greeting phrase', 'Hello')
    .action((name, cmdObj) => {
      if (actions.onGreet) {
        actions.onGreet({ name, greeting: cmdObj.greeting });
      }
    });

  program
    .command('add <a> <b>')
    .description('add two numbers together')
    .action((a, b) => {
      if (actions.onAdd) {
        actions.onAdd({
          a: parseFloat(a),
          b: parseFloat(b),
          sum: parseFloat(a) + parseFloat(b)
        });
      }
    });

  return program;
}

/**
 * Configures custom accumulator options (e.g. repeated options).
 *
 * @param {Command} program
 * @returns {Command}
 */
export function configureAccumulatorOptions(program) {
  const collect = (val, prev) => {
    prev.push(val);
    return prev;
  };

  return program.option('-i, --include <item>', 'items to include (repeatable)', collect, []);
}

export { Command, CommanderError };
test/contract.mjs
import assert from 'node:assert/strict';
import {
  createProgram,
  configureStandardOptions,
  registerSubcommands,
  configureAccumulatorOptions,
  Command,
  CommanderError
} from '../src/index.mjs';

// 1. Command configures program metadata and parses flags with default and boolean values
{
  const program = createProgram({
    name: 'sample-cli',
    version: '2.5.0',
    description: 'Sample CLI tool'
  });

  assert.equal(program.name(), 'sample-cli');
  assert.equal(program.version(), '2.5.0');
  assert.equal(program.description(), 'Sample CLI tool');

  configureStandardOptions(program);

  // Parse default options
  program.parse(['node', 'cli.js']);
  const defaultOpts = program.opts();
  assert.equal(defaultOpts.port, 8080);
  assert.equal(defaultOpts.host, 'localhost');
  assert.equal(defaultOpts.verbose, undefined);
  assert.equal(defaultOpts.cache, true);
}

// 2. Command parses options with required values and custom type coercion functions
{
  const program = createProgram();
  configureStandardOptions(program);

  program.parse(['node', 'cli.js', '-v', '-p', '9090', '-h', '127.0.0.1']);
  const opts = program.opts();
  assert.equal(opts.verbose, true);
  assert.equal(opts.port, 9090);
  assert.equal(typeof opts.port, 'number');
  assert.equal(opts.host, '127.0.0.1');
}

// 3. Command supports negated boolean options with --no prefix
{
  const program = createProgram();
  configureStandardOptions(program);

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

// 4. Command registers subcommands with positional arguments and executes action handlers
{
  let greetResult = null;
  let addResult = null;

  const program = createProgram();
  registerSubcommands(program, {
    onGreet: (res) => {
      greetResult = res;
    },
    onAdd: (res) => {
      addResult = res;
    }
  });

  program.parse(['node', 'cli.js', 'greet', 'Alice', '-g', 'Welcome']);
  assert.deepEqual(greetResult, { name: 'Alice', greeting: 'Welcome' });

  const program2 = createProgram();
  registerSubcommands(program2, {
    onGreet: (res) => {
      greetResult = res;
    },
    onAdd: (res) => {
      addResult = res;
    }
  });

  program2.parse(['node', 'cli.js', 'add', '15', '27']);
  assert.deepEqual(addResult, { a: 15, b: 27, sum: 42 });
}

// 5. Command supports exitOverride to throw CommanderError on missing required options or invalid commands
{
  const program = createProgram();
  program.requiredOption('-c, --config <file>', 'path to configuration file');

  assert.throws(
    () => {
      program.parse(['node', 'cli.js']);
    },
    (err) => {
      return err instanceof CommanderError && err.code === 'commander.missingMandatoryOptionValue';
    }
  );

  const subProgram = createProgram();
  subProgram.command('deploy');

  assert.throws(
    () => {
      subProgram.parse(['node', 'cli.js', 'unknown-command']);
    },
    (err) => {
      return err instanceof CommanderError && err.code === 'commander.unknownCommand';
    }
  );
}

// 6. Command supports custom accumulator option functions for repeated flags
{
  const program = createProgram();
  configureAccumulatorOptions(program);

  program.parse(['node', 'cli.js', '-i', 'apple', '-i', 'banana', '--include', 'cherry']);
  const opts = program.opts();
  assert.deepEqual(opts.include, ['apple', 'banana', 'cherry']);
}

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

오리진 시더

익명