Files
hyperframes/packages/cli/src/utils/command-failure-tracking.ts
T
miga-heygenandMiguel Ángel 1de8b5ae33 fix(cli): reject a swallowed --json when catalog's string flags have no value (#3992)
* fix(cli): reject a swallowed --json when catalog's string flags have no value

catalog --query --json (missing --query value) parsed as query="--json",
json=false, since citty's parser (node:util.parseArgs, strict: false)
unconditionally consumes the next token as a string arg's value with no
guard against it being another flag -- JSON-mode consumers silently got
human-readable stdout instead of a clear error.

Added an opt-in rejectSwallowedFlagValues() check (packages/cli/src/utils/
reject-unknown-flags.ts), called from catalog's own run() for its
query/type/tag string args. Kept it opt-in rather than wiring it into the
global assertKnownFlags pre-parse gate every command goes through: check.ts's
--frame-check is a string flag that's documented and tested to work bare or
immediately followed by another flag, handled by that command's own raw-args
preprocessing before citty parses it -- a blanket pre-parse check can't tell
that case apart from this bug, so review caught it as a real regression
before it shipped.

Co-Authored-By: Miguel Ángel <miguel.sierra@heygen.com>

* fix(cli): unify swallowed-flag-value handling into one raw-args gate

catalog --query --json (round 1's fix) turned out to be one instance of a
codebase-wide gap: any command with a type:"string"|"enum" flag followed by
--json (or any other declared flag) has its value swallowed by citty's parser
(node:util.parseArgs, strict: false unconditionally consumes the next token),
confirmed still reproducing on check --layout --json. Round 1's post-parse,
catalog-only check also duplicated check.ts's own existing --frame-check
raw-args mechanism instead of replacing it, and couldn't distinguish the
always-legitimate --query=--json (equals form) from the actual --query --json
swallow, since node:util.parseArgs parses both to the same object.

Replaced with a single raw-args scan (guardSwallowedFlagValues), wired into
the global wrapCommand gate next to assertKnownFlags so every command is
covered. Default: throw CliUsageError. Two narrow per-command opt-outs where a
command already has its own bespoke handling for this exact bug shape:
check's --frame-check (rewritten to --flag=, folding in and removing check.ts's
own normalizeFrameCheckRawArgs/swallowedOptionError) and upgrade's --project
(left untouched, since it already recovers the swallowed value itself). A
third, previously-undiscovered collision surfaced during testing: init.ts had
its own bespoke --example dash-value guard that the new global gate now
preempts; folded that in too and updated its one affected test's expectation.

Co-Authored-By: Miguel Ángel <miguel.sierra@heygen.com>

* fix(cli): stop the swallowed-flag usage error from leaking to stdout

Round 2's guardSwallowedFlagValues threw CliUsageError without
presented:true, the first non-presented CliUsageError construction in the
CLI -- executeCli's dead stdout-usage-dump branch (every other CliUsageError
goes through failUsage(), which always sets presented:true) fired for the
first time, leaking 1.4-5.7KB of ANSI usage text onto stdout on top of the
correct stderr message, breaking --json callers' clean-stdout contract on
exactly the class of error this ticket exists to fix.

Split into two functions instead of one, since the two throw sites have
genuinely different reach: throwSwallowedFlagError (used by
guardSwallowedFlagValues, thrown before any command's own run() executes)
prints the message itself and sets presented:true, matching every other
print-then-failUsage() usage-error site in this codebase. swallowedFlagUsageError
(used by check.ts's parseFrameCheck) is a plain, side-effect-free CliUsageError
factory, because that throw is always caught by check.ts's own run() try/catch,
which already prints and presents every error uniformly -- using the printing
variant there instead produced a real, verified regression (a doubled stderr
line in non-JSON mode, an extra stderr line even in --json mode), caught by
adversarial review before it shipped.

Co-Authored-By: Miguel Ángel <miguel.sierra@heygen.com>

* test(cli): assert literal stdout bytes stay empty for the swallowed-flag error

The prior test for this only asserted the internal presented:true flag, with
a comment noting the actual 0-byte-stdout behavior was checked by hand
against the built CLI. Added an automated spawn-based test (same pattern as
init.test.ts's runInit) that runs the real CLI and asserts stdout is
literally empty, not just that the presented mechanism is engaged.

Co-Authored-By: Miguel Ángel <miguel.sierra@heygen.com>

* refactor(cli): split the swallow guard into small helpers to clear the audit gate

Moves the leaf flag checks out of the wrapCommand run arrow, drops ignored args
from the owner map, and pulls the per-token decision out of the guard loop.
Trims two comments to keep check.ts under its comment share. No behaviour change.

* fix(cli): swallow guard hints a value and lets --no- negations through

* fix(cli): swallow guard looks past --no- negations that citty drops

---------

Co-authored-by: Miguel Ángel <miguel.sierra@heygen.com>
2026-10-09 21:55:42 +00:00

111 lines
4.8 KiB
TypeScript

import { parseArgs } from "citty";
import type { ArgsDef, CommandContext, CommandDef } from "citty";
import { resolveExtraPositionals } from "./reject-extra-positionals.js";
import { assertKnownFlags, guardSwallowedFlagValues } from "./reject-unknown-flags.js";
// citty types subcommands as `CommandDef<any>` (SubCommandsDef); mirror that so
// each command's specific args type is accepted without per-command generics.
type AnyCommandDef = CommandDef<any>;
/**
* Wrap a lazy command loader so leaf commands and nested subcommands share the
* unknown-flag guard. Errors propagate unchanged to the executable boundary,
* which reports them.
*/
export function trackCommandFailures(
load: () => Promise<AnyCommandDef>,
): () => Promise<AnyCommandDef> {
return () => load().then((cmd) => wrapCommand(cmd, commandName(cmd)));
}
function commandName(cmd: AnyCommandDef): string {
const name = (cmd.meta as { name?: unknown } | undefined)?.name;
return typeof name === "string" ? name : "";
}
/**
* Wrap a resolved command's `run` (assert flags and positional count) AND
* recursively wrap every entry in its `subCommands`. Two HF#2033 fixes live
* here:
* 1. `assertKnownFlags` runs in the wrapped command, so an unknown-flag
* throw reaches the executable boundary like every other failure.
* 2. Recursion covers nested command groups (`cloud/*`, `auth/*`, `figma/*`,
* `lambda/*`, `capture/*`, `skills`). Without it, a nested command's
* unknown flags would bypass the leaf's guard.
*/
function wrapCommand(cmd: AnyCommandDef, path: string): AnyCommandDef {
const run = cmd.run;
// Nothing to wrap (no run, no nested subcommands) — preserve identity.
if (typeof run !== "function" && !cmd.subCommands) return cmd;
const wrapped: AnyCommandDef = { ...cmd };
if (typeof run === "function") {
wrapped.run = async (ctx: Parameters<typeof run>[0]) => {
// Reject unknown flags before the command body: citty silently ignores
// them otherwise, dropping the value (e.g. `render --out x` fell back to
// the default output path).
//
// A command group (subCommands + fallback-help run) delegating to a
// subcommand must NOT assert here: the flags belong to the subcommand's
// table, not the group's, and would be falsely rejected (e.g.
// `figma component <ref> --name x`). The wrapped subcommand loaders
// below assert the leaf's own table, so typo protection is preserved.
// Heuristic caveat: "first non-dash token names a subcommand" is sound
// only while command groups declare no flags of their own — if a group
// grows a flag whose value could match a subcommand name, replace this
// with a real argv parse.
const rawArgs = ctx?.rawArgs ?? [];
const firstPositional = rawArgs.find((tok) => tok && !tok.startsWith("-"));
const delegatesToSub =
cmd.subCommands != null &&
firstPositional != null &&
Object.prototype.hasOwnProperty.call(cmd.subCommands, firstPositional);
if (!delegatesToSub) guardLeafFlags(cmd, path, ctx, rawArgs);
// Groups read `args._[0]` to pick fallback help, so only leaves get the count check.
if (!cmd.subCommands) resolveExtraPositionals(cmd, path, ctx?.args);
return await run(ctx);
};
}
if (cmd.subCommands) {
const wrappedSubs: Record<string, () => Promise<AnyCommandDef>> = {};
for (const [name, sub] of Object.entries(cmd.subCommands)) {
// citty subCommands are Resolvable<CommandDef>: a def, a promise, or a
// (possibly async) loader. Normalize to a loader that resolves then wraps.
wrappedSubs[name] = () =>
Promise.resolve(typeof sub === "function" ? (sub as () => unknown)() : sub).then((c) =>
wrapCommand(c as AnyCommandDef, `${path} ${name}`),
);
}
wrapped.subCommands = wrappedSubs;
}
return wrapped;
}
// citty built ctx.args before this ran; re-parse when the swallow guard rewrites rawArgs.
function guardLeafFlags(
cmd: AnyCommandDef,
path: string,
ctx: CommandContext<any>,
rawArgs: string[],
): void {
assertKnownFlags(cmd, rawArgs);
const guarded = guardSwallowedFlagValues(cmd, path, rawArgs);
if (!guarded.rewritten) return;
ctx.rawArgs = guarded.rawArgs;
ctx.args = parseArgs(guarded.rawArgs, (cmd.args ?? {}) as ArgsDef);
}
/**
* Report a command failure to telemetry, loading the telemetry module on demand
* (keeps it off the CLI cold-start path) and awaiting it so the event is
* enqueued before the caller re-throws / exits. Best-effort — never throws.
*/
export async function reportCommandFailure(command: string, err: unknown): Promise<void> {
try {
const { trackCommandFailure } = await import("../telemetry/events.js");
trackCommandFailure(command, err);
} catch {
// ignore: a telemetry failure must not affect the command's exit path
}
}