@clidoc/yargs

中文文档
1.1.3发布于 2026/11/07MITTypeScriptES Module构建来源已验证近 30 天下载 2548

Generate CLI reference docs from Yargs command definitions via OpenCLI

原始使用文档
文档目录12 节
  1. Getting Started
  2. Why / compared to alternatives
  3. Related packages
  4. Add docgen to your CLI
  5. Optional: __opencli for machine discovery
  6. Limitations
  7. Asynchronous builders
  8. Advanced: passing an explicit command-modules array
  9. Adding examples and exit codes
  10. Contribution
  11. License
  12. Author

clidoc logo


npm package npm downloads coverage discord chat documentation


@clidoc/yargs

Generate CLI reference docs from Yargs command definitions.

  • 📄 Docs From Your Commands
  • 🔌 Ready-Made docgen Command
  • 🔁 Async Builder Support
  • 🛡️ Metadata Only, No Handlers Run
  • 🤖 Machine Discovery via __opencli

Stop hand-writing your CLI reference docs. Generate them from your Yargs command definitions so they never drift from --help.

@clidoc/yargs converts your commands into an OpenCLI document that you can validate, render to Markdown, and publish to Docusaurus or VitePress.

Read the Docs to Learn More.

Getting Started

npm install @clidoc/yargs @clidoc/core yargs

Why / compared to alternatives

  • Hand-written reference pages drift as flags change; this reads the definitions your CLI already runs.
  • --help only is terminal text for one command at a time. The OpenCLI document is structured and validated, and renders to a full Markdown reference, shell completions and MCP tool definitions.
  • It reads metadata only: no handlers run, so generating docs has no side effects. Yargs behavior that isn't metadata (custom validation, coercion, middleware) isn't documented; see Limitations.

Add docgen to your CLI

createDocgenCommand builds a ready-to-register docgen command module: -o/--output <file> (defaults to stdout) and --format <json|yaml|markdown> (default json). infoFromPackageJson derives the document's title, binary name, and version from your package.json.

import { readFileSync } from 'node:fs';
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
import { createDocgenCommand, fromYargs } from '@clidoc/yargs';
import { infoFromPackageJson } from '@clidoc/core';

const greet = {
  command: 'greet <name>',
  describe: 'Print a greeting',
  builder: (y) =>
    y
      .positional('name', { type: 'string', describe: 'Who to greet' })
      .option('loud', { type: 'boolean', describe: 'Shout the greeting' }),
  handler: (argv) => console.log(argv.loud ? `HELLO, ${argv.name}!` : `Hello, ${argv.name}.`),
};

const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
const info = infoFromPackageJson(pkg);

const parser = yargs(hideBin(process.argv)).command(greet);

let document;
parser.command(createDocgenCommand(() => document)).demandCommand();
// generate the document once every command, including docgen, is registered
document = fromYargs(parser, info);

parser.parse();

Run mycli docgen --output cli.json for JSON (the default), or mycli docgen --format markdown --output reference.md to render Markdown directly; omit --output to print to stdout. Install the validator with npm install -g @clidoc/cli and run clidoc validate cli.json. See the Yargs demo for a runnable example.

Optional: __opencli for machine discovery

For machine discovery, matching upstream OpenCLI's Go libraries, check argv for the hidden __opencli subcommand before Yargs parses arguments instead of calling .parse() directly: handleOpenCliRequest prints one JSON document to stdout (or writes it to a file with upstream's own -o/--out <file> flag), and exits 0, so command handlers never run.

import { handleOpenCliRequest } from '@clidoc/core';

if (!(await handleOpenCliRequest(hideBin(process.argv), () => document))) {
  parser.parse();
}

Consumers can then run mycli __opencli > mycli.opencli.json or mycli __opencli --out mycli.opencli.json for discovery.

Limitations

  • .check() and .middleware() callbacks are never invoked.
  • Builder callbacks run to collect metadata, so use trusted modules. fromYargs rejects asynchronous builders; use fromYargsAsync for those.
  • Custom parsing, coercion, validation, and middleware behavior.
  • Unsupported builder methods report their name and suggest .option() or extending fromYargs.
  • A required array option (demandOption: true) emits variadic: true, required: true.
  • An array-typed option's default can't be expressed either — OpenCLI flag defaults are a single string, number, or boolean — so fromYargs throws a diagnostic naming the option instead of emitting an invalid document. Apply the default in your handler instead (e.g. argv.rules ?? ['basic']).

Asynchronous builders

fromYargs runs builders synchronously. If a builder is async, for example one that lazily imports its subcommands as yargs-file-commands does, use fromYargsAsync. It takes the same arguments, awaits each builder, and includes the options and subcommands registered after an await. createDocgenCommand accepts an async getDocument, so the document is built only when docgen runs and normal startup stays lazy:

import { createDocgenCommand, fromYargsAsync } from '@clidoc/yargs';
import { fileCommands } from 'yargs-file-commands';

const commands = await fileCommands({ commandDirs });
const docgen = createDocgenCommand(() => fromYargsAsync([...commands, docgen], info));

await yargs(hideBin(process.argv)).command(commands).command(docgen).parseAsync();

Pass the command modules rather than the parser here: Yargs doesn't expose its registered commands while a handler is running.

Advanced: passing an explicit command-modules array

fromYargs accepts an array of command modules in place of a live instance, for callers who want to build a document from modules that were never registered on a parser, run the conversion at a different time, or skip package.json entirely:

import { fromYargs } from '@clidoc/yargs';

const document = fromYargs([greet], { title: 'My CLI', binary: 'mycli', version: '1.0.0' });

fromYargs converts Yargs command metadata into an OpenCLI 1.0.0-alpha.14 document, from either a live instance or an explicit array of the same modules that register your commands, plus the CLI title, executable name, and version. fromYargs reads metadata only; it does not parse arguments or run handlers.

Adding examples and exit codes

fromYargs only knows what Yargs' command metadata exposes, so examples, exitCodes, and metadata like info.license never appear in the generated document. Add them with @clidoc/core's mergeDocument, replacing the plain fromYargs(parser, info) call above with:

import { mergeDocument } from '@clidoc/core';

document = mergeDocument(fromYargs(parser, info), {
  info: { license: { name: 'MIT', spdxId: 'MIT' } },
  commands: {
    'mycli greet': {
      examples: [{ title: 'Basic', content: 'mycli greet Ada' }],
      exitCodes: [{ code: 1, status: 'BAD_USER_INPUT_ERROR', summary: 'Missing name' }],
    },
  },
});

Use the full generated command key (mycli greet) to add metadata to the existing command.

See the @clidoc/core README for the merge rules.

Contribution

See Contributing Guide.

License

MIT

Author

Ben Houston, Sponsored by Land of Assets.

版本与发布记录

@clidoc/yargs 共发布 6 个版本,首次发布于 2026/09/22;过去 12 个月发布了 6 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.1.3latest2026/11/073 天前
1.1.22026/11/036 天前
1.1.12026/10/051 个月前
1.1.02026/09/291 个月前
0.1.12026/09/251 个月前
0.1.02026/09/221 个月前

关于 @clidoc/yargs 的常见问题

@clidoc/yargs 是什么?

Generate CLI reference docs from Yargs command definitions via OpenCLI

如何安装 @clidoc/yargs?

在项目目录运行 npm install @clidoc/yargs,或使用 pnpm add / yarn add / bun add。

@clidoc/yargs 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@clidoc/yargs 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@clidoc/yargs 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@clidoc/yargs 可以商用吗?

@clidoc/yargs 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@clidoc/yargs 的下载量有多少?

根据 npm 官方下载统计,@clidoc/yargs 在 2026/10/10 – 2026/11/08 这 30 天内被下载 2,548 次,日均约 85 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@clidoc/yargs 还在维护吗?

最新版本 1.1.3 发布于 2026/11/07(3 天前);至今共发布 6 个版本,其中过去 12 个月发布了 6 个;首次发布于 2026/09/22。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。