CodeSampleX

Ejemplo

commander 9.5.0: InvalidArgumentError

Muestra verificada para npm commander 9.5.0: InvalidArgumentError. El contrato se ejecutó en node 22 · linux alpine/x64 · docker y pasó.

sha256:a15960e24f991aae9f8c5fda1f36e634abb1c2199133f98ee6a8b5064e8475fa

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
2
Claves de firma que lo compilaron
1
Entorno declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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

Caso

HOW
Objetivo
verify commander.InvalidArgumentError in pkg:npm/commander@9.5.0
Paquetes
Símbolos
  • commander.InvalidArgumentError
Entorno
node 22.23.2
Creado
2026-08-23T07:00:03Z

Contrato

  1. InvalidArgumentError instantiates error objects with name 'InvalidArgumentError' and code 'commander.invalidArgument'
  2. InvalidOptionArgumentError is exported as an alias to InvalidArgumentError
  3. Throwing InvalidArgumentError inside custom option parser triggers CommanderError with code 'commander.invalidArgument'
  4. Throwing InvalidArgumentError inside custom positional argument parser triggers CommanderError with code 'commander.invalidArgument'
  5. Throwing generic Error inside custom option parser bypasses commander invalidArgument handling and rethrows standard Error

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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.InvalidArgumentError 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.InvalidArgumentError
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:1773d0333290d59ff1066b6a41fbd00ae31bd62e52bd5b31ab964fbd8310715f","constraints":{"executionContext":"node"},"contract":["InvalidArgumentError instantiates error objects with name 'InvalidArgumentError' and code 'commander.invalidArgument'","InvalidOptionArgumentError is exported as an alias to InvalidArgumentError","Throwing InvalidArgumentError inside custom option parser triggers CommanderError with code 'commander.invalidArgument'","Throwing InvalidArgumentError inside custom positional argument parser triggers CommanderError with code 'commander.invalidArgument'","Throwing generic Error inside custom option parser bypasses commander invalidArgument handling and rethrows standard Error"],"goal":"verify commander.InvalidArgumentError in pkg:npm/commander@9.5.0","kind":"HOW","packages":["pkg:npm/commander@9.5.0"],"schemaVersion":1,"symbols":["commander.InvalidArgumentError"]},"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@9.5.0"],"schemaVersion":1,"subject":"pkg:npm/commander@9.5.0","symbols":["commander.InvalidArgumentError"],"verifierAdapter":"node-typescript@1"}
index.js
'use strict';

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

/**
 * Creates a custom InvalidArgumentError.
 * @param {string} message
 * @returns {InvalidArgumentError}
 */
function createInvalidArgumentError(message) {
  return new InvalidArgumentError(message);
}

/**
 * Custom parser for integer option/argument that throws InvalidArgumentError on invalid values.
 * @param {string} value
 * @param {number} [min]
 * @param {number} [max]
 * @returns {number}
 */
function parseInteger(value, min = Number.MIN_SAFE_INTEGER, max = Number.MAX_SAFE_INTEGER) {
  const parsedValue = parseInt(value, 10);
  if (isNaN(parsedValue)) {
    throw new InvalidArgumentError(`'${value}' is not a valid integer.`);
  }
  if (parsedValue < min || parsedValue > max) {
    throw new InvalidArgumentError(`Value '${value}' must be between ${min} and ${max}.`);
  }
  return parsedValue;
}

/**
 * Custom parser for choice validation that throws InvalidArgumentError on invalid choices.
 * @param {string} value
 * @param {string[]} allowedChoices
 * @returns {string}
 */
function parseChoice(value, allowedChoices) {
  if (!allowedChoices.includes(value)) {
    throw new InvalidArgumentError(`Allowed values are ${allowedChoices.join(', ')}.`);
  }
  return value;
}

/**
 * Configures a Command instance with option parsers throwing InvalidArgumentError.
 * @returns {Command}
 */
function createOptionCommand() {
  const program = new Command()
    .exitOverride()
    .configureOutput({ writeErr: () => {}, writeOut: () => {} });

  program
    .option('-p, --port <number>', 'server port', (val) => parseInteger(val, 1, 65535))
    .addOption(
      new Option('-m, --mode <mode>', 'execution mode').argParser((val) =>
        parseChoice(val, ['development', 'production', 'test'])
      )
    );

  return program;
}

/**
 * Configures a Command instance with positional argument parsers throwing InvalidArgumentError.
 * @param {(...args: any[]) => void} actionHandler
 * @returns {Command}
 */
function createArgumentCommand(actionHandler) {
  const program = new Command()
    .exitOverride()
    .configureOutput({ writeErr: () => {}, writeOut: () => {} });

  program
    .argument('<count>', 'positive item count', (val) => parseInteger(val, 1))
    .addArgument(
      new Argument('<level>', 'log level').argParser((val) =>
        parseChoice(val, ['info', 'warn', 'error'])
      )
    )
    .action(actionHandler);

  return program;
}

/**
 * Configures a Command instance with option parser throwing a generic Error.
 * @returns {Command}
 */
function createGenericErrorOptionCommand() {
  const program = new Command()
    .exitOverride()
    .configureOutput({ writeErr: () => {}, writeOut: () => {} });

  program.option('-x, --extra <val>', 'extra value', (val) => {
    throw new Error(`Generic error for ${val}`);
  });

  return program;
}

module.exports = {
  InvalidArgumentError,
  InvalidOptionArgumentError,
  createInvalidArgumentError,
  parseInteger,
  parseChoice,
  createOptionCommand,
  createArgumentCommand,
  createGenericErrorOptionCommand
};
package-lock.json
{
  "name": "sample-commander-invalid-argument-error",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-commander-invalid-argument-error",
      "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-invalid-argument-error",
  "version": "1.0.0",
  "private": true,
  "description": "verify commander.InvalidArgumentError 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.InvalidArgumentError in pkg:npm/commander@9.5.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/commander@9.5.0"
  ],
  "symbols": [
    "commander.InvalidArgumentError"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.js
'use strict';

const assert = require('assert');
const {
  InvalidArgumentError,
  InvalidOptionArgumentError,
  createInvalidArgumentError,
  parseInteger,
  parseChoice,
  createOptionCommand,
  createArgumentCommand,
  createGenericErrorOptionCommand
} = require('../index.js');

function testInvalidArgumentErrorClass() {
  const message = 'Custom invalid argument message';
  const error = createInvalidArgumentError(message);

  assert.ok(error instanceof Error, 'InvalidArgumentError must inherit from Error');
  assert.ok(error instanceof InvalidArgumentError, 'error must be instance of InvalidArgumentError');
  assert.strictEqual(error.name, 'InvalidArgumentError', 'error.name must be InvalidArgumentError');
  assert.strictEqual(error.message, message, 'error.message must match input message');
  assert.strictEqual(error.code, 'commander.invalidArgument', 'error.code must be commander.invalidArgument');
  assert.strictEqual(InvalidOptionArgumentError, InvalidArgumentError, 'InvalidOptionArgumentError is an alias to InvalidArgumentError');
}

function testCustomOptionParsing() {
  const program = createOptionCommand();

  // Test valid options
  program.parse(['node', 'app', '-p', '8080', '-m', 'production']);
  assert.strictEqual(program.opts().port, 8080, 'port option should be parsed as integer');
  assert.strictEqual(program.opts().mode, 'production', 'mode option should be parsed string');

  // Test invalid integer option throws CommanderError with commander.invalidArgument
  const invalidPortProgram = createOptionCommand();
  assert.throws(
    () => {
      invalidPortProgram.parse(['node', 'app', '-p', 'not-a-number']);
    },
    (err) => {
      assert.strictEqual(err.code, 'commander.invalidArgument');
      assert.strictEqual(err.exitCode, 1);
      assert.match(err.message, /not a valid integer/);
      return true;
    }
  );

  // Test out-of-range option throws CommanderError with commander.invalidArgument
  const outOfRangeProgram = createOptionCommand();
  assert.throws(
    () => {
      outOfRangeProgram.parse(['node', 'app', '-p', '70000']);
    },
    (err) => {
      assert.strictEqual(err.code, 'commander.invalidArgument');
      assert.strictEqual(err.exitCode, 1);
      assert.match(err.message, /must be between 1 and 65535/);
      return true;
    }
  );

  // Test invalid choice option throws CommanderError with commander.invalidArgument
  const invalidModeProgram = createOptionCommand();
  assert.throws(
    () => {
      invalidModeProgram.parse(['node', 'app', '-m', 'invalid-mode']);
    },
    (err) => {
      assert.strictEqual(err.code, 'commander.invalidArgument');
      assert.strictEqual(err.exitCode, 1);
      assert.match(err.message, /Allowed values are development, production, test/);
      return true;
    }
  );
}

function testCustomArgumentParsing() {
  let receivedCount = null;
  let receivedLevel = null;
  const program = createArgumentCommand((count, level) => {
    receivedCount = count;
    receivedLevel = level;
  });

  // Test valid positional arguments
  program.parse(['node', 'app', '5', 'warn']);
  assert.strictEqual(receivedCount, 5, 'count argument should be parsed as 5');
  assert.strictEqual(receivedLevel, 'warn', 'level argument should be parsed as warn');

  // Test non-integer positional argument throws CommanderError with commander.invalidArgument
  const invalidArgProgram = createArgumentCommand(() => {});
  assert.throws(
    () => {
      invalidArgProgram.parse(['node', 'app', 'not-a-number', 'warn']);
    },
    (err) => {
      assert.strictEqual(err.code, 'commander.invalidArgument');
      assert.strictEqual(err.exitCode, 1);
      assert.match(err.message, /not a valid integer/);
      return true;
    }
  );

  // Test out-of-range positional argument throws CommanderError with commander.invalidArgument
  const outOfRangeArgProgram = createArgumentCommand(() => {});
  assert.throws(
    () => {
      outOfRangeArgProgram.parse(['node', 'app', '0', 'warn']);
    },
    (err) => {
      assert.strictEqual(err.code, 'commander.invalidArgument');
      assert.strictEqual(err.exitCode, 1);
      assert.match(err.message, /must be between 1 and/);
      return true;
    }
  );

  // Test invalid choice argument throws CommanderError with commander.invalidArgument
  const invalidChoiceArgProgram = createArgumentCommand(() => {});
  assert.throws(
    () => {
      invalidChoiceArgProgram.parse(['node', 'app', '10', 'verbose']);
    },
    (err) => {
      assert.strictEqual(err.code, 'commander.invalidArgument');
      assert.strictEqual(err.exitCode, 1);
      assert.match(err.message, /Allowed values are info, warn, error/);
      return true;
    }
  );
}

function testGenericErrorBypassesInvalidArgumentHandling() {
  const program = createGenericErrorOptionCommand();

  assert.throws(
    () => {
      program.parse(['node', 'app', '-x', 'test-value']);
    },
    (err) => {
      assert.strictEqual(err.name, 'Error');
      assert.strictEqual(err.code, undefined);
      assert.strictEqual(err.message, 'Generic error for test-value');
      return true;
    }
  );
}

function runAll() {
  testInvalidArgumentErrorClass();
  testCustomOptionParsing();
  testCustomArgumentParsing();
  testGenericErrorBypassesInvalidArgumentHandling();
  console.log('Contract tests passed successfully.');
}

runAll();

Seeder de origen

anónimo