CodeSampleX

샘플

commander 9.5.0: Argument

검증된 샘플 — npm commander 9.5.0: Argument. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: Argument instantiates positional argument definitions…

sha256:f2616988b18045845b930ba2f65b93f9e0dc33735f9fc64c5808d1b275ac2dcc

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

컨트랙트

  1. Argument instantiates positional argument definitions with name, description, required, and variadic flags
  2. Argument.choices restricts allowed argument values and throws commander.invalidArgument when an invalid choice is provided
  3. Argument.default sets a fallback default value for optional positional arguments when omitted
  4. Argument.argParser transforms input values and validates syntax with custom parser functions or InvalidArgumentError
  5. Argument supports variadic positional arguments collecting multiple values into an array

파일

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

소스 아티팩트 내려받기 (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 commander.Argument 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.Argument

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:a5db60914e60bc112d4074db009a34f4d3cca6d7a514c8b53c17ac8c5a1c0cc6","contract":["Argument instantiates positional argument definitions with name, description, required, and variadic flags","Argument.choices restricts allowed argument values and throws commander.invalidArgument when an invalid choice is provided","Argument.default sets a fallback default value for optional positional arguments when omitted","Argument.argParser transforms input values and validates syntax with custom parser functions or InvalidArgumentError","Argument supports variadic positional arguments collecting multiple values into an array"],"goal":"verify commander.Argument in pkg:npm/commander@9.5.0","kind":"HOW","packages":["pkg:npm/commander@9.5.0"],"schemaVersion":1,"symbols":["commander.Argument"]},"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.Argument"],"verifierAdapter":"node-typescript@1"}
index.js
'use strict';

const { Argument, Command, InvalidArgumentError } = require('commander');

/**
 * Creates an Argument instance with the specified name and description.
 * @param {string} name - Argument name/flags (e.g., '<format>', '[port]').
 * @param {string} description - Argument description.
 * @returns {Argument}
 */
function createArgument(name, description) {
  return new Argument(name, description);
}

/**
 * Configures a command with a choices-restricted argument and optional default.
 * @param {string} argName
 * @param {string} description
 * @param {string[]} choices
 * @param {*} [defaultValue]
 * @returns {{ program: Command, getResult: () => * }}
 */
function createChoiceCommand(argName, description, choices, defaultValue) {
  const program = new Command().exitOverride();
  const arg = new Argument(argName, description).choices(choices);
  if (defaultValue !== undefined) {
    arg.default(defaultValue);
  }
  let result;
  program.addArgument(arg).action((val) => {
    result = val;
  });
  return {
    program,
    getResult: () => result
  };
}

/**
 * Configures a command with a custom parser argument.
 * @param {string} argName
 * @param {string} description
 * @param {Function} parserFn
 * @param {*} [defaultValue]
 * @returns {{ program: Command, getResult: () => * }}
 */
function createParsedArgCommand(argName, description, parserFn, defaultValue) {
  const program = new Command().exitOverride();
  const arg = new Argument(argName, description).argParser(parserFn);
  if (defaultValue !== undefined) {
    arg.default(defaultValue);
  }
  let result;
  program.addArgument(arg).action((val) => {
    result = val;
  });
  return {
    program,
    getResult: () => result
  };
}

/**
 * Configures a command with a variadic argument.
 * @param {string} argName
 * @param {string} description
 * @returns {{ program: Command, getResult: () => * }}
 */
function createVariadicCommand(argName, description) {
  const program = new Command().exitOverride();
  const arg = new Argument(argName, description);
  let result;
  program.addArgument(arg).action((val) => {
    result = val;
  });
  return {
    program,
    getResult: () => result
  };
}

module.exports = {
  Argument,
  Command,
  InvalidArgumentError,
  createArgument,
  createChoiceCommand,
  createParsedArgCommand,
  createVariadicCommand
};
package-lock.json
{
  "name": "sample-commander-argument",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-commander-argument",
      "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-argument",
  "version": "1.0.0",
  "private": true,
  "description": "verify commander.Argument in pkg:npm/commander@9.5.0",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "commander": "9.5.0"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify commander.Argument in pkg:npm/commander@9.5.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/commander@9.5.0"
  ],
  "symbols": [
    "commander.Argument"
  ]
}
test/contract.js
'use strict';

const assert = require('assert');
const {
  createArgument,
  createChoiceCommand,
  createParsedArgCommand,
  createVariadicCommand,
  InvalidArgumentError
} = require('../index.js');

function testArgumentProperties() {
  const reqArg = createArgument('<source>', 'source file path');
  assert.strictEqual(reqArg.name(), 'source');
  assert.strictEqual(reqArg.description, 'source file path');
  assert.strictEqual(reqArg.required, true);
  assert.strictEqual(reqArg.variadic, false);

  const optArg = createArgument('[destination]', 'destination path');
  assert.strictEqual(optArg.name(), 'destination');
  assert.strictEqual(optArg.required, false);
  assert.strictEqual(optArg.variadic, false);

  const varArg = createArgument('<files...>', 'target files');
  assert.strictEqual(varArg.name(), 'files');
  assert.strictEqual(varArg.required, true);
  assert.strictEqual(varArg.variadic, true);
}

function testChoicesAndValidation() {
  const allowed = ['json', 'yaml', 'text'];
  const { program, getResult } = createChoiceCommand('<format>', 'output format', allowed, 'json');

  // Valid choice
  program.parse(['node', 'app', 'yaml']);
  assert.strictEqual(getResult(), 'yaml');

  // Invalid choice throws commander.invalidArgument
  const invalidProgram = createChoiceCommand('<format>', 'output format', allowed).program;
  assert.throws(
    () => {
      invalidProgram.parse(['node', 'app', 'xml']);
    },
    (err) => {
      assert.strictEqual(err.code, 'commander.invalidArgument');
      assert.match(err.message, /Allowed choices are json, yaml, text/);
      return true;
    }
  );
}

function testDefaultValues() {
  const { program, getResult } = createChoiceCommand('[format]', 'output format', ['json', 'yaml', 'text'], 'json');
  program.parse(['node', 'app']);
  assert.strictEqual(getResult(), 'json');
}

function testCustomArgParser() {
  const parsePort = (val) => {
    const port = parseInt(val, 10);
    if (isNaN(port) || port < 1 || port > 65535) {
      throw new InvalidArgumentError('Port must be a number between 1 and 65535.');
    }
    return port;
  };

  const { program, getResult } = createParsedArgCommand('<port>', 'listening port', parsePort);
  program.parse(['node', 'app', '8080']);
  assert.strictEqual(getResult(), 8080);

  const { program: invalidProgram } = createParsedArgCommand('<port>', 'listening port', parsePort);
  assert.throws(
    () => {
      invalidProgram.parse(['node', 'app', 'invalid-port']);
    },
    (err) => {
      assert.strictEqual(err.code, 'commander.invalidArgument');
      assert.match(err.message, /Port must be a number between 1 and 65535/);
      return true;
    }
  );
}

function testVariadicArguments() {
  const { program, getResult } = createVariadicCommand('<items...>', 'list of items');
  program.parse(['node', 'app', 'item1', 'item2', 'item3']);
  assert.deepStrictEqual(getResult(), ['item1', 'item2', 'item3']);
}

function run() {
  testArgumentProperties();
  testChoicesAndValidation();
  testDefaultValues();
  testCustomArgParser();
  testVariadicArguments();
  console.log('Contract tests passed successfully.');
  process.exit(0);
}

run();

오리진 시더

익명