CodeSampleX

Пример

nopt 6.0.0: nopt

Проверенный пример — npm nopt 6.0.0: nopt. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: nopt exports main parser function along with…

sha256:ba0559055c1187bc41baa37c1398f62856bbae989c6ae53dc434584d74162e54

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Среды запусков проверки

Окружение Контракт Этапы Запуск
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-28

Кейс

HOW
Цель
verify pkg:npm/nopt@6.0.0
Пакеты
Символы
  • nopt
Окружение
node 22.23.2
Создан
2026-08-28T08:07:33Z

Контракт

  1. nopt exports main parser function along with clean and typeDefs properties
  2. nopt parses string, number, and boolean command-line options according to type definitions
  3. nopt supports boolean negation with no- prefix
  4. nopt accumulates multiple flag instances for array-typed options
  5. nopt expands shorthand flags and resolves prefix abbreviations
  6. nopt preserves positional arguments and options after double-dash in argv.remain
  7. parseOptions and parseCli helpers wrap nopt to structure options and positional arguments

Файлы

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

Use EXACTLY these public packages and versions:
  - pkg:npm/nopt@6.0.0
Demonstrate these symbols/APIs:
  - nopt

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:8d85fe0b450b4d77082c45fed04627ef119dff6b17361e9901cefd9f45af83a1","contract":["nopt exports main parser function along with clean and typeDefs properties","nopt parses string, number, and boolean command-line options according to type definitions","nopt supports boolean negation with no- prefix","nopt accumulates multiple flag instances for array-typed options","nopt expands shorthand flags and resolves prefix abbreviations","nopt preserves positional arguments and options after double-dash in argv.remain","parseOptions and parseCli helpers wrap nopt to structure options and positional arguments"],"goal":"verify pkg:npm/nopt@6.0.0","kind":"HOW","packages":["pkg:npm/nopt@6.0.0"],"schemaVersion":1,"symbols":["nopt"]},"contractCommand":["node","test/contract.mjs"],"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/nopt@6.0.0"],"schemaVersion":1,"subject":"pkg:npm/nopt@6.0.0","symbols":["nopt"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-nopt",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-nopt",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "nopt": "6.0.0"
      }
    },
    "node_modules/abbrev": {
      "version": "1.1.1",
      "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz",
      "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==",
      "license": "ISC"
    },
    "node_modules/nopt": {
      "version": "6.0.0",
      "resolved": "https://registry.npmjs.org/nopt/-/nopt-6.0.0.tgz",
      "integrity": "sha512-ZwLpbTgdhuZUnZzjd7nb1ZV+4DoiC6/sfiVKok72ym/4Tlf+DFdlHYmT2JPmcNNWV6Pi3SDf1kT+A4r9RTuT9g==",
      "license": "ISC",
      "dependencies": {
        "abbrev": "^1.0.0"
      },
      "bin": {
        "nopt": "bin/nopt.js"
      },
      "engines": {
        "node": "^12.13.0 || ^14.15.0 || >=16.0.0"
      }
    }
  }
}
package.json
{
  "name": "sample-nopt",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for nopt@6.0.0",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "nopt": "6.0.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/nopt@6.0.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/nopt@6.0.0"
  ],
  "symbols": [
    "nopt"
  ]
}
src/index.js
'use strict';

const nopt = require('nopt');

/**
 * Parses command line options with type definitions and shorthands.
 *
 * @param {object} types - Mapping of option names to type constructors or arrays.
 * @param {object} [shorthands={}] - Mapping of shorthand options to expansions.
 * @param {string[]} [args=process.argv] - Command line arguments.
 * @param {number} [slice=2] - Slice start index.
 * @returns {object} Parsed options object including argv metadata.
 */
function parseOptions(types, shorthands = {}, args = process.argv, slice = 2) {
  return nopt(types, shorthands, args, slice);
}

/**
 * Parses command line arguments and separates recognized flags from remaining positional arguments.
 *
 * @param {object} types - Option types map.
 * @param {object} [shorthands={}] - Shorthand aliases map.
 * @param {string[]} [args=[]] - Argument list.
 * @returns {{ options: object, remain: string[], cooked: string[], original: string[] }}
 */
function parseCli(types, shorthands = {}, args = []) {
  const parsed = nopt(types, shorthands, args, 0);
  const { argv, ...options } = parsed;
  return {
    options,
    remain: argv ? argv.remain : [],
    cooked: argv ? argv.cooked : [],
    original: argv ? argv.original : []
  };
}

module.exports = {
  nopt,
  parseOptions,
  parseCli
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const { nopt, parseOptions, parseCli } = require('../src/index.js');

async function runTests() {
  // 1. Export verification
  assert.equal(typeof nopt, 'function', 'nopt must be a function');
  assert.equal(typeof nopt.clean, 'function', 'nopt.clean must be a function');
  assert.equal(typeof nopt.typeDefs, 'object', 'nopt.typeDefs must be an object');
  assert.equal(typeof parseOptions, 'function', 'parseOptions helper must be a function');
  assert.equal(typeof parseCli, 'function', 'parseCli helper must be a function');

  // 2. Type parsing: String, Number, Boolean
  const basicTypes = {
    host: String,
    port: Number,
    debug: Boolean
  };
  const basicArgs = ['--host', 'localhost', '--port', '8080', '--debug'];
  const basicParsed = nopt(basicTypes, {}, basicArgs, 0);

  assert.equal(basicParsed.host, 'localhost', 'host should be parsed as string');
  assert.equal(basicParsed.port, 8080, 'port should be parsed as number');
  assert.equal(basicParsed.debug, true, 'debug should be parsed as boolean true');

  // 3. Boolean negation
  const negTypes = {
    minify: Boolean,
    sourceMap: Boolean
  };
  const negArgs = ['--no-minify', '--sourceMap'];
  const negParsed = nopt(negTypes, {}, negArgs, 0);

  assert.equal(negParsed.minify, false, '--no-minify should set flag to false');
  assert.equal(negParsed.sourceMap, true, '--sourceMap should set flag to true');

  // 4. Array accumulation
  const arrayTypes = {
    include: [String, Array],
    exclude: [String, Array]
  };
  const arrayArgs = ['--include', 'src/**', '--include', 'lib/**', '--exclude', 'dist/**'];
  const arrayParsed = nopt(arrayTypes, {}, arrayArgs, 0);

  assert.deepEqual(arrayParsed.include, ['src/**', 'lib/**'], 'array flags should accumulate multiple values');
  assert.deepEqual(arrayParsed.exclude, ['dist/**'], 'single array flag should produce single-element array');

  // 5. Shorthands and prefix abbreviation
  const shortTypes = {
    output: String,
    verbose: Boolean,
    concurrency: Number
  };
  const shorthands = {
    o: ['--output'],
    v: ['--verbose'],
    c: ['--concurrency']
  };
  const shortArgs = ['-o', 'dist/bundle.js', '-v', '-c', '4'];
  const shortParsed = nopt(shortTypes, shorthands, shortArgs, 0);

  assert.equal(shortParsed.output, 'dist/bundle.js', 'shorthand -o should expand to --output');
  assert.equal(shortParsed.verbose, true, 'shorthand -v should expand to --verbose');
  assert.equal(shortParsed.concurrency, 4, 'shorthand -c should expand to --concurrency');

  // Prefix abbreviation resolution
  const abbrevArgs = ['--verb', '--concur', '8'];
  const abbrevParsed = nopt(shortTypes, shorthands, abbrevArgs, 0);
  assert.equal(abbrevParsed.verbose, true, '--verb should resolve to --verbose');
  assert.equal(abbrevParsed.concurrency, 8, '--concur should resolve to --concurrency');

  // 6. Positional arguments and double-dash delimiter
  const posTypes = {
    target: String
  };
  const posArgs = ['--target', 'es2020', 'file1.js', 'file2.js', '--', '--not-a-flag', 'extra.js'];
  const posParsed = nopt(posTypes, {}, posArgs, 0);

  assert.equal(posParsed.target, 'es2020');
  assert.deepEqual(
    posParsed.argv.remain,
    ['file1.js', 'file2.js', '--not-a-flag', 'extra.js'],
    'positional and delimiter arguments should be preserved in argv.remain'
  );

  // 7. Helper parseCli
  const cliResult = parseCli(
    { name: String, count: Number },
    { n: ['--name'] },
    ['-n', 'worker', 'job1', 'job2']
  );
  assert.deepEqual(cliResult.options, { name: 'worker' });
  assert.deepEqual(cliResult.remain, ['job1', 'job2']);
  assert.ok(Array.isArray(cliResult.cooked));
  assert.ok(Array.isArray(cliResult.original));

  console.log('All nopt contract tests passed successfully.');
}

runTests().catch((err) => {
  console.error('Contract test failure:', err);
  process.exit(1);
});

Исходный сидер

аноним