CodeSampleX

示例

commander 5.1.0

已验证示例 — npm commander 5.1.0. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: commander Command parses option flags with boolean toggles, custom coerce…

sha256:b451be13e71f1b675ac7966cc8224d01835f6385c8ab24e364d7c3f2af1b1b02

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
2
构建过它的签名密钥
2
声明的环境 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

验证运行环境

环境 契约 阶段 运行日期
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-19
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
包
环境
node 22.23.2
创建时间
2026-08-19T18:07:58Z

契约

  1. commander Command parses option flags with boolean toggles, custom coerce parsers, and default values into opts
  2. commander Command dispatches subcommands with required and optional positional arguments to action handlers
  3. commander exitOverride intercepts missing mandatory options and unknown options throwing CommanderError

文件

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • 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 pkg:npm/commander@5.1.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/commander@5.1.0
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:dfe7c0d684ed9046e95dd219388cb9f1226a4a8b6527a08660c56776fa916057","constraints":{"executionContext":"node"},"contract":["commander Command parses option flags with boolean toggles, custom coerce parsers, and default values into opts","commander Command dispatches subcommands with required and optional positional arguments to action handlers","commander exitOverride intercepts missing mandatory options and unknown options throwing CommanderError"],"goal":"verify pkg:npm/commander@5.1.0","kind":"HOW","packages":["pkg:npm/commander@5.1.0"],"schemaVersion":1},"contractCommand":["node","test/contract.js"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/commander@5.1.0"],"schemaVersion":1,"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "commander-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "commander-sample",
      "version": "1.0.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": "commander-sample",
  "version": "1.0.0",
  "dependencies": {
    "commander": "5.1.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/commander@5.1.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/commander@5.1.0"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const { Command } = require('commander');

/**
 * Creates and initializes a new Command instance.
 *
 * @param {string} [name] - The name of the command.
 * @param {string} [description] - Description of the command.
 * @returns {Command} A configured Command instance.
 */
function createCli(name, description) {
  const program = new Command();
  if (name) {
    program.name(name);
  }
  if (description) {
    program.description(description);
  }
  program.storeOptionsAsProperties(false);
  return program;
}

/**
 * Adds an option to a command instance.
 *
 * @param {Command} command - The command instance.
 * @param {string} flags - Option flag string (e.g. "-p, --port <number>").
 * @param {string} description - Description of the option.
 * @param {*} [defaultValue] - Default value for the option.
 * @param {Function} [coercionFn] - Custom value parser / coerce function.
 * @returns {Command} The command instance for chaining.
 */
function registerOption(command, flags, description, defaultValue, coercionFn) {
  if (coercionFn) {
    return command.option(flags, description, coercionFn, defaultValue);
  }
  return command.option(flags, description, defaultValue);
}

/**
 * Adds a mandatory option to a command instance.
 *
 * @param {Command} command - The command instance.
 * @param {string} flags - Required option flag string.
 * @param {string} description - Description of the required option.
 * @returns {Command} The command instance for chaining.
 */
function registerRequiredOption(command, flags, description) {
  return command.requiredOption(flags, description);
}

/**
 * Registers a subcommand with positional arguments and an action handler.
 *
 * @param {Command} parentCommand - The parent command instance.
 * @param {string} nameAndArgs - Subcommand name and argument pattern.
 * @param {string} description - Subcommand description.
 * @param {Function} actionHandler - Action handler callback receiving (args..., options, cmd).
 * @returns {Command} The newly created subcommand instance.
 */
function registerSubcommand(parentCommand, nameAndArgs, description, actionHandler) {
  const sub = parentCommand.command(nameAndArgs);
  sub.storeOptionsAsProperties(false);
  if (description) {
    sub.description(description);
  }
  if (actionHandler) {
    sub.action((...args) => {
      const cmd = args[args.length - 1];
      const positional = args.slice(0, -1);
      actionHandler(...positional, cmd.opts(), cmd);
    });
  }
  return sub;
}

/**
 * Parses argument array safely using exitOverride to prevent process termination.
 *
 * @param {Command} command - The command instance to parse with.
 * @param {string[]} argv - Array of arguments.
 * @param {object} [parseOptions] - Optional parse options, e.g. { from: 'user' }.
 * @returns {{ opts: object, args: string[] }} Parsed options and remaining args.
 */
function parseCliArgs(command, argv, parseOptions) {
  command.exitOverride();
  if (parseOptions) {
    command.parse(argv, parseOptions);
  } else {
    command.parse(argv);
  }
  return {
    opts: command.opts(),
    args: command.args,
  };
}

module.exports = {
  createCli,
  registerOption,
  registerRequiredOption,
  registerSubcommand,
  parseCliArgs,
};
test/contract.js
const assert = require('node:assert/strict');
const { CommanderError } = require('commander');
const {
  createCli,
  registerOption,
  registerRequiredOption,
  registerSubcommand,
  parseCliArgs,
} = require('../src/index.js');

// Contract 1: commander Command parses option flags with boolean toggles, custom coerce parsers, and default values into opts
{
  const cli = createCli('tester', 'Test CLI app');

  registerOption(cli, '-p, --port <number>', 'Port number to bind', 3000, (val) => parseInt(val, 10));
  registerOption(cli, '-v, --verbose', 'Enable verbose logging', false);
  registerOption(cli, '--no-color', 'Disable colored output');
  registerOption(cli, '-t, --tag <item>', 'Tags to append', [], (item, list) => [...list, item]);

  const result = parseCliArgs(cli, [
    'node',
    'cli.js',
    '-p',
    '8080',
    '--verbose',
    '--no-color',
    '-t',
    'alpha',
    '-t',
    'beta',
  ]);

  assert.strictEqual(result.opts.port, 8080, 'Port option should be coerced to integer 8080');
  assert.strictEqual(result.opts.verbose, true, 'Verbose flag should be boolean true');
  assert.strictEqual(result.opts.color, false, '--no-color should set color property to false');
  assert.deepStrictEqual(result.opts.tag, ['alpha', 'beta'], 'Tag option should accumulate values into array');

  // Test default values when options omitted
  const cliDefaults = createCli('tester-default');
  registerOption(cliDefaults, '-p, --port <number>', 'Port number', 5000, (val) => parseInt(val, 10));
  const defaultResult = parseCliArgs(cliDefaults, ['node', 'cli.js']);
  assert.strictEqual(defaultResult.opts.port, 5000, 'Port option should fallback to default 5000');
}

// Contract 2: commander Command dispatches subcommands with required and optional positional arguments to action handlers
{
  const cli = createCli('git-like');
  let dispatchedPayload = null;

  const cloneSubcommand = registerSubcommand(
    cli,
    'clone <repository> [targetDirectory]',
    'Clone repository into a directory',
    (repository, targetDirectory, options) => {
      dispatchedPayload = {
        repository,
        targetDirectory: targetDirectory || './default-target',
        depth: options.depth ? parseInt(options.depth, 10) : 1,
      };
    }
  );
  registerOption(cloneSubcommand, '--depth <n>', 'Depth of commits');

  parseCliArgs(cli, ['node', 'git-like.js', 'clone', 'localhost/repo.git', '--depth', '5']);

  assert.ok(dispatchedPayload !== null, 'Subcommand action handler should be called');
  assert.strictEqual(dispatchedPayload.repository, 'localhost/repo.git');
  assert.strictEqual(dispatchedPayload.targetDirectory, './default-target');
  assert.strictEqual(dispatchedPayload.depth, 5);
}

// Contract 3: commander exitOverride intercepts missing mandatory options and unknown options throwing CommanderError
{
  // Mandatory option missing
  const cliMandatory = createCli('mandatory-test');
  registerRequiredOption(cliMandatory, '-k, --key <value>', 'Mandatory API key');

  assert.throws(
    () => {
      parseCliArgs(cliMandatory, ['node', 'test.js']);
    },
    (err) => {
      assert.ok(err instanceof CommanderError, 'Error should be instance of CommanderError');
      assert.strictEqual(err.code, 'commander.missingMandatoryOptionValue');
      return true;
    }
  );

  // Unknown option supplied
  const cliStrict = createCli('strict-test');
  registerOption(cliStrict, '-f, --flag', 'Allowed flag');

  assert.throws(
    () => {
      parseCliArgs(cliStrict, ['node', 'test.js', '--unrecognized-option']);
    },
    (err) => {
      assert.ok(err instanceof CommanderError, 'Error should be instance of CommanderError');
      assert.strictEqual(err.code, 'commander.unknownOption');
      return true;
    }
  );
}

console.log('All pkg:npm/commander@5.1.0 contracts passed successfully.');

原始种子者

匿名