Skip to content

Commit 73d3b4e

Browse files
committed
fix(cli): report command failures once
1 parent 619406a commit 73d3b4e

4 files changed

Lines changed: 68 additions & 123 deletions

File tree

‎packages/cli/src/cli.commands.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,10 @@ describe("CLI command registration", () => {
4747
expect(condition).toContain('command !== "events"');
4848
expect(condition).toContain('command !== "skills"');
4949
});
50+
51+
it("reports each command failure only at the executable boundary", () => {
52+
expect(cliSource).toContain("trackCommandFailures(load)");
53+
expect(cliSource).not.toContain("trackCommandFailures(load,");
54+
expect(cliSource.match(/reportCommandFailure\(command, error\)/g)).toHaveLength(1);
55+
});
5056
});

‎packages/cli/src/cli.ts‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -163,10 +163,7 @@ const commandLoaders = {
163163
};
164164

165165
const subCommands = Object.fromEntries(
166-
Object.entries(commandLoaders).map(([name, load]) => [
167-
name,
168-
trackCommandFailures(load, (error) => reportCommandFailure(command, error)),
169-
]),
166+
Object.entries(commandLoaders).map(([name, load]) => [name, trackCommandFailures(load)]),
170167
);
171168

172169
const main = defineCommand({

‎packages/cli/src/utils/command-failure-tracking.test.ts‎

Lines changed: 29 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -14,40 +14,32 @@ function defineRun(run: CommandDef["run"]): CommandDef {
1414
}
1515

1616
describe("trackCommandFailures", () => {
17-
it("reports the error and re-throws when run() rejects", async () => {
18-
const onFailure = vi.fn();
17+
it("re-throws when run() rejects so the executable boundary can report it", async () => {
1918
const boom = new Error("ffmpeg not found");
20-
const wrapped = trackCommandFailures(
21-
() => Promise.resolve(defineRun(() => Promise.reject(boom))),
22-
onFailure,
19+
const wrapped = trackCommandFailures(() =>
20+
Promise.resolve(defineRun(() => Promise.reject(boom))),
2321
);
2422

2523
const cmd = await wrapped();
2624
await expect((cmd.run as () => Promise<unknown>)()).rejects.toBe(boom);
27-
expect(onFailure).toHaveBeenCalledWith(boom);
2825
});
2926

30-
it("does not report when run() succeeds, and returns its value", async () => {
31-
const onFailure = vi.fn();
32-
const wrapped = trackCommandFailures(
33-
() => Promise.resolve(defineRun(() => Promise.resolve("ok" as unknown as void))),
34-
onFailure,
27+
it("returns the command value when run() succeeds", async () => {
28+
const wrapped = trackCommandFailures(() =>
29+
Promise.resolve(defineRun(() => Promise.resolve("ok" as unknown as void))),
3530
);
3631

3732
const cmd = await wrapped();
3833
await expect((cmd.run as () => Promise<unknown>)()).resolves.toBe("ok");
39-
expect(onFailure).not.toHaveBeenCalled();
4034
});
4135

4236
it("rejects an unknown flag on a leaf command", async () => {
43-
const wrapped = trackCommandFailures(
44-
() =>
45-
Promise.resolve({
46-
meta: { name: "leaf" },
47-
args: { out: { type: "string" } },
48-
run: () => Promise.resolve(),
49-
} as CommandDef),
50-
vi.fn(),
37+
const wrapped = trackCommandFailures(() =>
38+
Promise.resolve({
39+
meta: { name: "leaf" },
40+
args: { out: { type: "string" } },
41+
run: () => Promise.resolve(),
42+
} as CommandDef),
5143
);
5244
const cmd = await wrapped();
5345
await expect(
@@ -59,14 +51,12 @@ describe("trackCommandFailures", () => {
5951
// `figma component <ref> --name x`: --name belongs to the subcommand's
6052
// table; the group (subCommands + fallback-help run) must not reject it.
6153
const run = vi.fn(() => Promise.resolve());
62-
const wrapped = trackCommandFailures(
63-
() =>
64-
Promise.resolve({
65-
meta: { name: "figma" },
66-
subCommands: { component: () => Promise.resolve({ meta: { name: "component" } }) },
67-
run,
68-
} as unknown as CommandDef),
69-
vi.fn(),
54+
const wrapped = trackCommandFailures(() =>
55+
Promise.resolve({
56+
meta: { name: "figma" },
57+
subCommands: { component: () => Promise.resolve({ meta: { name: "component" } }) },
58+
run,
59+
} as unknown as CommandDef),
7060
);
7161
const cmd = await wrapped();
7262
await expect(
@@ -78,14 +68,12 @@ describe("trackCommandFailures", () => {
7868
});
7969

8070
it("still rejects an unknown flag when the group is NOT delegating", async () => {
81-
const wrapped = trackCommandFailures(
82-
() =>
83-
Promise.resolve({
84-
meta: { name: "figma" },
85-
subCommands: { component: () => Promise.resolve({ meta: { name: "component" } }) },
86-
run: () => Promise.resolve(),
87-
} as unknown as CommandDef),
88-
vi.fn(),
71+
const wrapped = trackCommandFailures(() =>
72+
Promise.resolve({
73+
meta: { name: "figma" },
74+
subCommands: { component: () => Promise.resolve({ meta: { name: "component" } }) },
75+
run: () => Promise.resolve(),
76+
} as unknown as CommandDef),
8977
);
9078
const cmd = await wrapped();
9179
await expect(
@@ -94,65 +82,44 @@ describe("trackCommandFailures", () => {
9482
});
9583

9684
it("passes through a command with no run() untouched", async () => {
97-
const onFailure = vi.fn();
9885
const parent: CommandDef = { meta: { name: "parent" } };
99-
const wrapped = trackCommandFailures(() => Promise.resolve(parent), onFailure);
86+
const wrapped = trackCommandFailures(() => Promise.resolve(parent));
10087

10188
const cmd = await wrapped();
10289
expect(cmd).toBe(parent);
103-
expect(onFailure).not.toHaveBeenCalled();
10490
});
10591

106-
it("awaits onFailure and re-throws the ORIGINAL error even if onFailure rejects", async () => {
107-
const boom = new Error("original failure");
108-
const wrapped = trackCommandFailures(
109-
() => Promise.resolve(defineRun(() => Promise.reject(boom))),
110-
() => Promise.reject(new Error("telemetry is down")),
111-
);
112-
113-
const cmd = await wrapped();
114-
await expect((cmd.run as () => Promise<unknown>)()).rejects.toBe(boom);
115-
});
116-
117-
it("REPORTS an unknown-flag rejection to onFailure (HF#2033: assertion inside the try)", async () => {
118-
// The flag assertion used to run before the try/catch, so an unknown-flag
119-
// throw skipped telemetry. It must now be reported like any other failure.
120-
const onFailure = vi.fn();
92+
it("re-throws an unknown-flag rejection to the executable boundary", async () => {
12193
const cmd = {
12294
meta: { name: "render" },
12395
args: { output: { type: "string", alias: "o" } },
12496
run: vi.fn(() => Promise.resolve()),
12597
} as unknown as CommandDef;
126-
const wrapped = trackCommandFailures(() => Promise.resolve(cmd), onFailure);
98+
const wrapped = trackCommandFailures(() => Promise.resolve(cmd));
12799

128100
const resolved = await wrapped();
129101
await expect(
130102
(resolved.run as (ctx: unknown) => Promise<unknown>)({ rawArgs: ["--nope", "x"] }),
131103
).rejects.toThrow(/unknown flag/i);
132-
expect(onFailure).toHaveBeenCalledTimes(1);
133104
expect(cmd.run).not.toHaveBeenCalled(); // body never ran — flag rejected first
134105
});
135106

136-
it("recursively wraps nested subcommands so their failures report too (HF#2033)", async () => {
137-
// cli.ts wraps only top-level loaders; a group's leaves (cloud/*, auth/*, …)
138-
// were never wrapped, silently dropping unknown-flag + failure telemetry.
139-
const onFailure = vi.fn();
107+
it("recursively wraps nested subcommands so their failures reach the boundary", async () => {
140108
const boom = new Error("nested boom");
141109
const group: CommandDef = {
142110
meta: { name: "cloud" },
143111
subCommands: {
144112
render: defineRun(() => Promise.reject(boom)),
145113
},
146114
};
147-
const wrapped = trackCommandFailures(() => Promise.resolve(group), onFailure);
115+
const wrapped = trackCommandFailures(() => Promise.resolve(group));
148116

149117
const resolvedGroup = await wrapped();
150118
const subLoader = (resolvedGroup.subCommands as Record<string, () => Promise<CommandDef>>)
151119
.render;
152120
if (!subLoader) throw new Error("expected a wrapped 'render' subcommand loader");
153121
const leaf = await subLoader();
154122
await expect((leaf.run as () => Promise<unknown>)()).rejects.toBe(boom);
155-
expect(onFailure).toHaveBeenCalledWith(boom);
156123
});
157124
});
158125

‎packages/cli/src/utils/command-failure-tracking.ts‎

Lines changed: 32 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -6,80 +6,55 @@ import { assertKnownFlags } from "./reject-unknown-flags.js";
66
type AnyCommandDef = CommandDef<any>;
77

88
/**
9-
* Wrap a lazy command loader so a thrown failure is reported via `onFailure`
10-
* before it propagates. citty's `runMain` catches command errors and exits 1
11-
* without re-throwing, so this is the only place to capture the reason. The
12-
* error is re-thrown unchanged, preserving citty's print + exit-1 behavior.
13-
*
14-
* `onFailure` is awaited so it can resolve the (lazily-loaded) telemetry module
15-
* before the error propagates — otherwise a command that throws before the
16-
* telemetry import settles would lose its event. A throw from `onFailure` is
17-
* swallowed so telemetry can never mask the real command failure.
18-
*
19-
* Commands that call `process.exit()` themselves bypass this (the process is
20-
* already gone) and must report their failure inline.
9+
* Wrap a lazy command loader so leaf commands and nested subcommands share the
10+
* unknown-flag guard. Errors propagate unchanged to the executable boundary,
11+
* which is the sole command-failure telemetry reporter.
2112
*/
2213
export function trackCommandFailures(
2314
load: () => Promise<AnyCommandDef>,
24-
onFailure: (err: unknown) => void | Promise<void>,
2515
): () => Promise<AnyCommandDef> {
26-
return () => load().then((cmd) => wrapCommand(cmd, onFailure));
16+
return () => load().then((cmd) => wrapCommand(cmd));
2717
}
2818

2919
/**
30-
* Wrap a resolved command's `run` (assert-flags + report-failure) AND
20+
* Wrap a resolved command's `run` (assert-flags) AND
3121
* recursively wrap every entry in its `subCommands`. Two HF#2033 fixes live
3222
* here:
33-
* 1. `assertKnownFlags` runs INSIDE the try, so an unknown-flag throw is
34-
* routed through `onFailure` (telemetry) like any other failure — it
35-
* used to throw before the try and lose the event entirely.
23+
* 1. `assertKnownFlags` runs in the wrapped command, so an unknown-flag
24+
* throw reaches the executable boundary like every other failure.
3625
* 2. Recursion covers nested command groups (`cloud/*`, `auth/*`, `figma/*`,
37-
* `lambda/*`, `capture/*`, `skills`). cli.ts only wraps the top-level
38-
* loaders, so before this a `hyperframes cloud render --badflag` silently
39-
* ignored the flag and reported nothing — citty dispatches to the leaf,
40-
* whose `run` was never wrapped.
26+
* `lambda/*`, `capture/*`, `skills`). Without it, a nested command's
27+
* unknown flags would bypass the leaf's guard.
4128
*/
42-
function wrapCommand(
43-
cmd: AnyCommandDef,
44-
onFailure: (err: unknown) => void | Promise<void>,
45-
): AnyCommandDef {
29+
function wrapCommand(cmd: AnyCommandDef): AnyCommandDef {
4630
const run = cmd.run;
4731
// Nothing to wrap (no run, no nested subcommands) — preserve identity.
4832
if (typeof run !== "function" && !cmd.subCommands) return cmd;
4933

5034
const wrapped: AnyCommandDef = { ...cmd };
5135
if (typeof run === "function") {
5236
wrapped.run = async (ctx: Parameters<typeof run>[0]) => {
53-
try {
54-
// Reject unknown flags before the command body: citty silently ignores
55-
// them otherwise, dropping the value (e.g. `render --out x` fell back to
56-
// the default output path). Inside the try so the rejection is reported.
57-
//
58-
// A command group (subCommands + fallback-help run) delegating to a
59-
// subcommand must NOT assert here: the flags belong to the subcommand's
60-
// table, not the group's, and would be falsely rejected (e.g.
61-
// `figma component <ref> --name x`). The wrapped subcommand loaders
62-
// below assert the leaf's own table, so typo protection is preserved.
63-
// Heuristic caveat: "first non-dash token names a subcommand" is sound
64-
// only while command groups declare no flags of their own — if a group
65-
// grows a flag whose value could match a subcommand name, replace this
66-
// with a real argv parse.
67-
const rawArgs = ctx?.rawArgs ?? [];
68-
const firstPositional = rawArgs.find((tok) => tok && !tok.startsWith("-"));
69-
const delegatesToSub =
70-
cmd.subCommands != null &&
71-
firstPositional != null &&
72-
Object.prototype.hasOwnProperty.call(cmd.subCommands, firstPositional);
73-
if (!delegatesToSub) assertKnownFlags(cmd, rawArgs);
74-
return await run(ctx);
75-
} catch (err) {
76-
try {
77-
await onFailure(err);
78-
} catch {
79-
// Telemetry must never mask the real command failure.
80-
}
81-
throw err;
82-
}
37+
// Reject unknown flags before the command body: citty silently ignores
38+
// them otherwise, dropping the value (e.g. `render --out x` fell back to
39+
// the default output path).
40+
//
41+
// A command group (subCommands + fallback-help run) delegating to a
42+
// subcommand must NOT assert here: the flags belong to the subcommand's
43+
// table, not the group's, and would be falsely rejected (e.g.
44+
// `figma component <ref> --name x`). The wrapped subcommand loaders
45+
// below assert the leaf's own table, so typo protection is preserved.
46+
// Heuristic caveat: "first non-dash token names a subcommand" is sound
47+
// only while command groups declare no flags of their own — if a group
48+
// grows a flag whose value could match a subcommand name, replace this
49+
// with a real argv parse.
50+
const rawArgs = ctx?.rawArgs ?? [];
51+
const firstPositional = rawArgs.find((tok) => tok && !tok.startsWith("-"));
52+
const delegatesToSub =
53+
cmd.subCommands != null &&
54+
firstPositional != null &&
55+
Object.prototype.hasOwnProperty.call(cmd.subCommands, firstPositional);
56+
if (!delegatesToSub) assertKnownFlags(cmd, rawArgs);
57+
return await run(ctx);
8358
};
8459
}
8560
if (cmd.subCommands) {
@@ -89,7 +64,7 @@ function wrapCommand(
8964
// (possibly async) loader. Normalize to a loader that resolves then wraps.
9065
wrappedSubs[name] = () =>
9166
Promise.resolve(typeof sub === "function" ? (sub as () => unknown)() : sub).then((c) =>
92-
wrapCommand(c as AnyCommandDef, onFailure),
67+
wrapCommand(c as AnyCommandDef),
9368
);
9469
}
9570
wrapped.subCommands = wrappedSubs;

0 commit comments

Comments
 (0)