GitHub
Skip to content

Argument parsers

Use readerly with node:util parseArgs or cac. readerFlags takes the shared reader flags and hands the rest of argv to your parser.

readerly is not a CLI framework. It reads the shared reader flags, such as --format and --no-input, and leaves your commands, options and help text to the parser you already use.

Each command takes its own arguments, the ones after its name, and uses them twice:

  1. createOut({ tool, command, argv }) scans argv for the shared flags and builds the profile from them.
  2. readerFlags(argv).rest returns the same argv without those flags. Your parser reads that.

readerFlags never throws. It stops at -- and leaves -- and everything after it in rest. It knows the long flags only, plus -y. -v stays in rest, so it can keep meaning --version.

Your parser never sees --format, --json, --full, --max-chars, --color, --no-color, --no-input, --non-interactive, --yes, -y, --verbose, --quiet or --input. Don't declare options with those names.

A bad value, such as --format nope, is not your parser's problem either. createOut keeps it and out.end() prints the failure and returns 2:

✖ --format nope is not a format. Use one of: text, agent, json, jsonl.
╰▶ fix: Pass --format with one of: text, agent, json, jsonl.
text

parseArgs ships with Node, so this example needs nothing beyond readerly:

import { parseArgs } from "node:util";
import { createOut, failure, FailureError, readerFlags } from "readerly";

export async function check(argv: string[]): Promise<number> {
  const out = createOut<{ files: number }>({ tool: "acme", command: "check", argv });
  let parsed;
  try {
    parsed = parseArgs({
      args: readerFlags(argv).rest,
      options: { fix: { type: "boolean", default: false } },
      allowPositionals: true,
    });
  } catch (error) {
    return out.fail(new FailureError(failure("usage", (error as Error).message)));
  }
  const paths = parsed.positionals.length > 0 ? parsed.positionals : ["."];
  out.warn({ code: "ACME010", message: "Alias shadows a workspace package", file: "vite.config.ts" });
  out.set({ files: paths.length });
  if (!parsed.values.fix) out.next("acme check --fix", "applies 1 safe fix");
  return out.end();
}

const [command, ...args] = process.argv.slice(2);
if (command === "check") process.exitCode = await check(args);
acme.ts

process.exitCode = await check(args) sets the exit code and lets Node finish writing stdout. out.end() returns 0 for ok, 1 for failed and 2 for action_required.

In a pipe, acme check src prints:

⚠ 1 warning

warn  ACME010  vite.config.ts  Alias shadows a workspace package

next: acme check --fix   (applies 1 safe fix)
text

parseArgs is strict by default and throws on an unknown option. Wrapped in failure("usage", …), the error leaves through out.fail in the reader's format and exits 2. acme check src --frobnicate prints on stderr:

✖ Unknown option '--frobnicate'. To specify a positional argument starting with a '-', place it at the end of the command after '--', as in '-- "--frobnicate"
text

With --json, the same failure is a document on stdout:

{
  "schema": "acme.check/v1",
  "status": "failed",
  "error": {
    "message": "Unknown option '--frobnicate'. To specify a positional argument starting with a '-', place it at the end of the command after '--', as in '-- \"--frobnicate\""
  }
}
json

Warning

out.fail(error) takes something thrown. Pass new FailureError(failure(…)), not the Failure object itself: a plain object becomes a runtime failure with the message [object Object] and exit 1.

cac matches the command for you, so the command's own arguments come from argv without the command's name. This example ran with cac 7.1.1:

import { cac } from "cac";
import { createOut, failure, FailureError, readerFlags } from "readerly";

async function check(argv: string[], paths: string[], options: { fix: boolean }) {
  const out = createOut({ tool: "acme", command: "check", argv });
  out.info(`checked ${paths.join(", ") || "."}${options.fix ? " with fixes" : ""}`);
  return out.end();
}

const argv = process.argv.slice(2);
const cli = cac("acme");
cli
  .command("check [...paths]", "Check files")
  .option("--fix", "Apply the safe fixes")
  // createOut gets the command's own arguments: argv without the word `check`.
  .action((paths: string[], options: { fix: boolean }) =>
    check(argv.toSpliced(argv.indexOf("check"), 1), paths, options),
  );
cli.parse(["node", "acme", ...readerFlags(argv).rest], { run: false });
try {
  process.exitCode = await cli.runMatchedCommand();
} catch (error) {
  const out = createOut({ tool: "acme", command: cli.matchedCommandName, argv });
  process.exitCode = out.fail(new FailureError(failure("usage", (error as Error).message)));
}
acme.ts

cli.parse drops the first two items of the array it gets, as it does with process.argv, hence "node", "acme". { run: false } keeps the action from running inside parse, so runMatchedCommand() can return its exit code.

Reader flags work before or after the command name. acme --format jsonl check src prints:

{"type":"version","schema":"acme.check/v1","tool":"acme"}
{"type":"diagnostic","severity":"info","message":"checked src"}
{"type":"result","status":"ok","message":"1 info","data":{}}
text

cac throws on an unknown option from runMatchedCommand(), before the action runs. The catch turns it into a usage failure. acme check --frobnicate prints on stderr and exits 2:

✖ Unknown option `--frobnicate`
text

readerly builds the commands in hidden: footers, in the next: line of a skipped prompt and in the rerun of an action_required failure from tool, command and rest, without the reader flags. Pass the command's own arguments, not the whole process.argv. For acme check src with argv: ["src"], a skipped --fix prompt prints next: acme check src --fix. With argv: ["check", "src"], it prints next: acme check check src --fix.

Next: testing your CLI for every reader.