CodeSampleX

示例

nopt 9.0.0: parse command line options with types and shorthands

已验证示例 — npm nopt 9.0.0: parse command line options with types and shorthands. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过.

sha256:71efd188ba4473961fcda69d45e5687cc1eb29a4bc77c929f3f02e0ab504294e

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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
目标
parse command line options with types and shorthands
包
符号
  • nopt
环境
node 22.23.2
创建时间
2026-08-28T04:55:25Z

契约

  1. nopt parses typed options including String, Number, Boolean, Array, path, and Date from command line arguments
  2. nopt expands single and multi-flag shorthands into their canonical option equivalents
  3. nopt handles boolean negation with --no prefix and collects trailing arguments after -- in argv.remain
  4. nopt.clean coerces and validates option values according to type definitions
  5. nopt.typeDefs provides default type validators for standard JavaScript types

文件

  • 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: parse command line options with types and shorthands
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/nopt@9.0.0
Demonstrate these symbols/APIs:
  - nopt
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:e3fc368e273934a8aa109a68edbaf35b73a797938c67cc5823e156ab818f2d23","constraints":{"executionContext":"node"},"contract":["nopt parses typed options including String, Number, Boolean, Array, path, and Date from command line arguments","nopt expands single and multi-flag shorthands into their canonical option equivalents","nopt handles boolean negation with --no prefix and collects trailing arguments after -- in argv.remain","nopt.clean coerces and validates option values according to type definitions","nopt.typeDefs provides default type validators for standard JavaScript types"],"goal":"parse command line options with types and shorthands","kind":"HOW","packages":["pkg:npm/nopt@9.0.0"],"schemaVersion":1,"symbols":["nopt"]},"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/nopt@9.0.0"],"schemaVersion":1,"subject":"pkg:npm/nopt@9.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": "9.0.0"
      }
    },
    "node_modules/abbrev": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-4.0.0.tgz",
      "integrity": "sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA==",
      "license": "ISC",
      "engines": {
        "node": "^20.17.0 || >=22.9.0"
      }
    },
    "node_modules/nopt": {
      "version": "9.0.0",
      "resolved": "https://registry.npmjs.org/nopt/-/nopt-9.0.0.tgz",
      "integrity": "sha512-Zhq3a+yFKrYwSBluL4H9XP3m3y5uvQkB/09CwDruCiRmR/UJYnn9W4R48ry0uGC70aeTPKLynBtscP9efFFcPw==",
      "license": "ISC",
      "dependencies": {
        "abbrev": "^4.0.0"
      },
      "bin": {
        "nopt": "bin/nopt.js"
      },
      "engines": {
        "node": "^20.17.0 || >=22.9.0"
      }
    }
  }
}
package.json
{
  "name": "sample-nopt",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification sample for nopt",
  "main": "src/index.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "nopt": "9.0.0"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "parse command line options with types and shorthands",
  "kind": "HOW",
  "packages": [
    "pkg:npm/nopt@9.0.0"
  ],
  "symbols": [
    "nopt"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const nopt = require('nopt');

/**
 * Parses command line options using nopt with specified types and shorthands.
 * @param {Object} types - Known option types map
 * @param {Object} shorthands - Short flag aliases map
 * @param {string[]} args - Command line arguments
 * @param {number} slice - Index to start slicing args from (default 2)
 * @returns {Object} Parsed options object with argv metadata
 */
function parseOptions(types, shorthands, args, slice = 2) {
  return nopt(types, shorthands, args, slice);
}

/**
 * Cleans and type-checks an existing data object against type definitions.
 * @param {Object} data - Key-value map of option values to sanitize
 * @param {Object} types - Expected types map
 * @returns {Object} Sanitized data object
 */
function cleanOptions(data, types) {
  nopt.clean(data, types);
  return data;
}

module.exports = {
  nopt,
  parseOptions,
  cleanOptions
};
test/contract.js
const assert = require('node:assert');
const path = require('node:path');
const nopt = require('nopt');
const { parseOptions, cleanOptions } = require('../src/index.js');

// 1. Contract: nopt parses typed options (String, Number, Boolean, Array, path, Date) from CLI arguments
{
  const types = {
    name: String,
    port: Number,
    verbose: Boolean,
    tags: [String, Array],
    config: path,
    created: Date
  };
  const shorthands = {
    n: ['--name'],
    p: ['--port'],
    v: ['--verbose'],
    t: ['--tags'],
    c: ['--config']
  };

  const argv = [
    'node',
    'cli.js',
    '--name', 'sample-service',
    '-p', '8080',
    '-v',
    '--tags', 'web',
    '--tags', 'api',
    '--config', './config.json',
    '--created', '2026-08-28T00:00:00Z',
    'extraArg1',
    'extraArg2'
  ];

  const parsed = nopt(types, shorthands, argv, 2);

  assert.strictEqual(parsed.name, 'sample-service', 'String option parsed');
  assert.strictEqual(parsed.port, 8080, 'Number option parsed as number');
  assert.strictEqual(parsed.verbose, true, 'Boolean flag parsed as true');
  assert.deepStrictEqual(parsed.tags, ['web', 'api'], 'Array option collected into array');
  assert.strictEqual(parsed.config, path.resolve('./config.json'), 'path option resolved to absolute path');
  assert.ok(parsed.created instanceof Date, 'Date option parsed as Date object');
  assert.strictEqual(parsed.created.toISOString(), '2026-08-28T00:00:00.000Z', 'Date value preserved');
  assert.deepStrictEqual(parsed.argv.remain, ['extraArg1', 'extraArg2'], 'Positional arguments captured in remain');

  // Verify helper function
  const helperParsed = parseOptions(types, shorthands, argv, 2);
  assert.strictEqual(helperParsed.name, 'sample-service');
  assert.strictEqual(helperParsed.port, 8080);
}

// 2. Contract: nopt expands shorthand aliases and shorthand multi-args
{
  const types = {
    host: String,
    port: Number,
    quiet: Boolean
  };
  const shorthands = {
    h: ['--host'],
    p: ['--port'],
    q: ['--quiet'],
    local: ['--host', 'localhost', '--port', '3000']
  };

  const argv = ['node', 'cli.js', '-h', 'example.com', '-p', '9090', '-q'];
  const parsed = nopt(types, shorthands, argv, 2);
  assert.strictEqual(parsed.host, 'example.com', 'Shorthand -h expanded to --host');
  assert.strictEqual(parsed.port, 9090, 'Shorthand -p expanded to --port');
  assert.strictEqual(parsed.quiet, true, 'Shorthand -q expanded to --quiet');

  const multiArgv = ['node', 'cli.js', '--local'];
  const multiParsed = nopt(types, shorthands, multiArgv, 2);
  assert.strictEqual(multiParsed.host, 'localhost', 'Composite shorthand expanded host');
  assert.strictEqual(multiParsed.port, 3000, 'Composite shorthand expanded port');
}

// 3. Contract: nopt handles boolean negation with --no prefix and delimiter '--'
{
  const types = {
    debug: Boolean,
    color: Boolean,
    target: String
  };
  const shorthands = {};

  const argv = ['node', 'cli.js', '--no-debug', '--color', '--', '--target', 'raw-file'];
  const parsed = nopt(types, shorthands, argv, 2);

  assert.strictEqual(parsed.debug, false, '--no-debug set debug to false');
  assert.strictEqual(parsed.color, true, '--color set color to true');
  assert.strictEqual(parsed.target, undefined, 'Options after -- are not parsed as options');
  assert.deepStrictEqual(parsed.argv.remain, ['--target', 'raw-file'], 'Remaining arguments collected after --');
}

// 4. Contract: nopt.clean validates and coerces values in an options object
{
  const types = {
    id: Number,
    active: Boolean,
    title: String
  };

  const raw = {
    id: '42',
    active: 'true',
    title: 100
  };

  cleanOptions(raw, types);

  assert.strictEqual(raw.id, 42, 'clean coerced string number to number');
  assert.strictEqual(raw.active, true, 'clean coerced string boolean to boolean');
  assert.strictEqual(raw.title, '100', 'clean coerced number to string');
}

// 5. Contract: nopt exposes standard type definitions in typeDefs
{
  assert.ok(nopt.typeDefs.String, 'typeDefs has String');
  assert.ok(nopt.typeDefs.Boolean, 'typeDefs has Boolean');
  assert.ok(nopt.typeDefs.Number, 'typeDefs has Number');
  assert.ok(nopt.typeDefs.path, 'typeDefs has path');
  assert.ok(nopt.typeDefs.Array, 'typeDefs has Array');
  assert.ok(nopt.typeDefs.Date, 'typeDefs has Date');
  assert.ok(nopt.typeDefs.url, 'typeDefs has url');
  assert.ok(nopt.typeDefs.Stream, 'typeDefs has Stream');
}

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

原始种子者

匿名