From 9a618b798fcb6bb262d3709bc1de6edf2fff974b Mon Sep 17 00:00:00 2001 From: James Russo Date: Sat, 21 Nov 2026 13:31:44 +0000 Subject: [PATCH] fix(cli): read --json before the command name the same as after it (#8365) * fix(cli): read --json before the command name the same as after it `hyperframes --json ` turned on the JSON failure answer but never reached the command, so the command printed for people. The flag now moves behind the command's own arguments before anything reads them, so both spellings are one run: a command with a `json` flag answers in JSON, and a command without one refuses the flag as it already did after its name. A `--json` behind `--` is an argument and no longer turns the JSON failure answer on. Co-Authored-By: Claude Fable 5.2 * test(cli): follow --json to its one meaning in the entry-point cases Rows that put --json before the command name to see a command's lines for people now run without it, and the word-tier catalog case checks the ready-to-paste command. Co-Authored-By: Claude Fable 5.2 * fix(cli): drop init's handling for a JSON run that can no longer start init has no JSON output, and --json is now refused in both positions before init runs. The status holding, the JSON-run check and init's own answer text had no caller left. Its tests run without --json and assert the printed line. Co-Authored-By: Claude Fable 5.2 * test(cli): let the command table load preview where the studio packages are not built Co-Authored-By: Claude Fable 5.2 * fix(cli): read --json before `help ` the same as after it Co-Authored-By: Claude Fable 5.2 * test(cli): cover command words run with no subcommand in the --json table Co-Authored-By: Claude Fable 5.2 --------- Co-authored-by: Claude Fable 5.2 --- docs/packages/cli.mdx | 14 +- packages/cli/src/cli.dotEnv.test.ts | 2 +- packages/cli/src/cli.jsonFlag.test.ts | 281 ++++++++++++++++++ packages/cli/src/cli.lifecycle.test.ts | 25 +- packages/cli/src/cli.ts | 5 +- packages/cli/src/commands/catalog.test.ts | 1 + packages/cli/src/commands/init.output.test.ts | 26 +- packages/cli/src/commands/init.test.ts | 42 +-- packages/cli/src/commands/init.ts | 59 ++-- packages/cli/src/utils/jsonError.ts | 22 +- packages/cli/src/utils/projectShortcut.ts | 20 ++ 11 files changed, 378 insertions(+), 119 deletions(-) create mode 100644 packages/cli/src/cli.jsonFlag.test.ts diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdx index 959ff0d1fa..6da7df871d 100644 --- a/docs/packages/cli.mdx +++ b/docs/packages/cli.mdx @@ -55,8 +55,18 @@ text such as `\x1b` and `\x07`, and keep the value on its line, with a line brea shown as `\x0a`. [`capture`](#capture) does the same for its warnings and failure reason. `--json` output is not changed by this. -**`--json` for agents and scripts.** Most commands accept it, and the ones -that do not reject it with exit 2. The payload is wrapped with a `_meta` field +**`--json` for agents and scripts.** Most commands accept it, before or after +the command name: `hyperframes --json info` is the same run as +`hyperframes info --json`. The commands that have no JSON output refuse it in +either position, without running: they print a `json_unsupported` error as JSON +and exit 2. Those are `init`, `auth login`, `auth logout`, `auth refresh`, +`billing`, `browser`, `docs`, `events`, `feedback`, the `figma` subcommands, +`play`, `present`, `publish` and `templates`, and five command words run with no +subcommand: `auth`, `cloud`, `figma`, `media-use` and `skills` (so +`skills --json` installs nothing; `skills check` and `skills update` do accept +the flag). A `--json` after `--` is an +argument, not the flag, so it does not turn JSON output or the JSON form of a +failure on. The payload is wrapped with a `_meta` field so a script can spot an outdated CLI from any command's output, without a second call: diff --git a/packages/cli/src/cli.dotEnv.test.ts b/packages/cli/src/cli.dotEnv.test.ts index f4af3198ca..60e75ba14b 100644 --- a/packages/cli/src/cli.dotEnv.test.ts +++ b/packages/cli/src/cli.dotEnv.test.ts @@ -69,7 +69,7 @@ it.each( const definition = { default: { meta: { name: command }, - args: {}, + args: { json: { type: "boolean" } }, run: () => { observed = [ process.env.HYPERFRAMES_BROWSER_PATH, diff --git a/packages/cli/src/cli.jsonFlag.test.ts b/packages/cli/src/cli.jsonFlag.test.ts new file mode 100644 index 0000000000..306589fd03 --- /dev/null +++ b/packages/cli/src/cli.jsonFlag.test.ts @@ -0,0 +1,281 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { ArgsDef, CommandDef } from "citty"; +import { mockTelemetry } from "./cliDispatchTestUtils.js"; +import { jsonFlagBeforeSeparator, jsonFlagAfterCommand } from "./utils/projectShortcut.js"; + +type Loader = () => Promise; +type Tracking = typeof import("./utils/command-failure-tracking.js"); + +const originalArgv = [...process.argv]; +const originalExitCode = process.exitCode; +const MOCKED = [ + "citty", + "./utils/command-failure-tracking.js", + "./telemetry/index.js", + "./telemetry/events.js", + "./utils/workspaceBuildCheck.js", +]; +// The test job does not build the studio packages; `preview` only needs them once it runs. +const studioBuilt = () => + vi.doMock("./utils/workspaceBuildCheck.js", () => ({ + checkStudioWorkspaceBuild: () => [], + formatWorkspaceBuildProblems: () => "", + })); + +// Each load of the entry point adds its own listeners; drop the ones a row added. +function keepListeners(): () => void { + const watched = [ + ...["exit", "uncaughtException", "unhandledRejection"].map((event) => [process, event]), + [process.stdout, "error"], + [process.stderr, "error"], + ] as Array<[NodeJS.EventEmitter, string]>; + const before = watched.map(([emitter, event]) => emitter.listeners(event)); + return () => + watched.forEach(([emitter, event], i) => { + for (const added of emitter.listeners(event)) + if (!before[i]!.includes(added)) emitter.removeListener(event, added as () => void); + }); +} + +afterEach(async () => { + process.argv = [...originalArgv]; + process.exitCode = originalExitCode; + await vi.dynamicImportSettled(); + vi.restoreAllMocks(); + for (const path of MOCKED) vi.doUnmock(path); + vi.resetModules(); +}); + +// Every command that declares a `json` flag. A new command goes here or in WITHOUT_JSON. +const names = (list: string): string[] => list.trim().split(/,\s*/); +const WITH_JSON = names(` + add, audio, auth status, beats, benchmark, capture, catalog, catch-up, check, clean, + cloud delete, cloud get, cloud list, cloud render, cloudrun, compare, compositions, diff, + doctor, grade-compare, history begin, history end, history peek, history pin, + history restore, history show, history undo, info, inspect, keyframes, lambda, layout, lint, + measure curve, measure cuts, measure energy, measure events, measure extract, measure face, + measure frames, measure hands, measure ink, measure look, measure probe, measure sync, + media-treatment, media-use adopt, media-use analyze, media-use avatars, media-use candidates, + media-use doctor, media-use from, media-use generate, media-use params, media-use resolve, + media-use reuse, media-use stats, media-use voices, models, normalize-audio, open, preview, + remove-background, render, reverse start, share, skills check, skills update, snapshot, + telemetry, timeline apply, timeline delete, timeline duplicate, timeline ids, timeline move, + timeline set, timeline split, timeline trim, timeline undo, transcribe, tts, update, upgrade, + usage, validate +`); +const WITHOUT_JSON = names(` + auth login, auth logout, auth refresh, billing, browser, docs, events, feedback, figma asset, + figma component, figma tokens, init, play, present, publish, templates +`); + +// Command words that take subcommands, run on their own. REFUSED answer `json_unsupported`. +const REFUSED_PARENTS = names("auth, cloud, figma, media-use, skills"); +const OTHER_PARENTS = names("history, measure, reverse, timeline"); + +interface Leaf { + path: string[]; + json: boolean; + required: string[]; + parent?: true; +} + +const load = async (entry: unknown): Promise => + (typeof entry === "function" ? await (entry as Loader)() : await entry) as CommandDef; + +async function leaves(command: CommandDef, path: string[] = []): Promise { + const subs = command.subCommands as Record | undefined; + if (subs) { + const nested = Object.entries(subs).map(async ([name, entry]) => + leaves(await load(entry), [...path, name]), + ); + const own: Leaf[] = path.length ? [{ path, json: false, required: [], parent: true }] : []; + return [...own, ...(await Promise.all(nested)).flat()]; + } + const args = Object.entries((command.args ?? {}) as ArgsDef); + // Enough words for citty's own required-argument check to pass. + const required = args.flatMap(([name, arg]) => { + if (arg.default !== undefined) return []; + if (arg.type === "positional") return arg.required === false ? [] : ["x"]; + return arg.required ? [`--${name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}=x`] : []; + }); + return [{ path, json: "json" in (command.args ?? {}), required }]; +} + +/** The CLI's own command tree, read from the entry point without running a command. */ +async function commandTree(): Promise { + let root: CommandDef | undefined; + vi.doMock("citty", async (original) => ({ + ...(await original()), + runCommand: async (command: CommandDef) => void (root = command), + })); + mockTelemetry(); + studioBuilt(); + process.argv = ["node", "cli.ts", "info"]; + const restoreListeners = keepListeners(); + await import("./cli.js"); + await vi.dynamicImportSettled(); + restoreListeners(); + vi.doUnmock("citty"); + vi.resetModules(); + return leaves(root!); +} + +// A leaf's own work is replaced by one line; its flag checks stay real. +function stubLeafRuns(command: CommandDef): CommandDef { + const subs = command.subCommands as Record | undefined; + const run: CommandDef["run"] = ({ args }) => console.log(`ran json=${args.json}`); + if (!subs) return { ...command, run }; + const stubbed = Object.entries(subs).map(([name, entry]) => [ + name, + async () => stubLeafRuns(await load(entry)), + ]); + // citty also calls a parent's handler after its subcommand; the stand-in speaks only when run bare. + const bare: CommandDef["run"] = (context) => + context.rawArgs.some((arg) => arg in subs) ? undefined : run(context); + return { + ...command, + ...(command.run ? { run: bare } : {}), + subCommands: Object.fromEntries(stubbed), + }; +} + +async function run(args: string[]): Promise<{ stdout: string; exit: unknown }> { + let stdout = ""; + vi.doMock("./utils/command-failure-tracking.js", async (original) => { + const actual = await original(); + return { + ...actual, + trackCommandFailures: (loader: Loader) => + actual.trackCommandFailures(async () => stubLeafRuns(await loader())), + }; + }); + mockTelemetry(); + studioBuilt(); + const keep = (chunk: unknown): boolean => { + stdout += String(chunk); + return true; + }; + vi.spyOn(process.stdout, "write").mockImplementation(keep as typeof process.stdout.write); + vi.spyOn(console, "log").mockImplementation((line) => void keep(`${line}\n`)); + vi.spyOn(console, "error").mockImplementation(() => {}); + process.exitCode = undefined; + process.argv = ["node", "cli.ts", ...args]; + const restoreListeners = keepListeners(); + await import("./cli.js"); + await vi.dynamicImportSettled(); + restoreListeners(); + const exit = process.exitCode ?? 0; + vi.restoreAllMocks(); + vi.resetModules(); + return { stdout, exit }; +} + +describe("--json ahead of the command word", () => { + it.each([ + [ + ["--json", "info"], + ["info", "--json"], + ], + [ + ["--json", "--verbose", "info", "dir"], + ["--verbose", "info", "dir", "--json"], + ], + [ + ["--json", "lambda", "policies", "validate", "a.json"], + ["lambda", "policies", "validate", "a.json", "--json"], + ], + [ + ["--json", "--json", "info"], + ["info", "--json"], + ], + [ + ["--json", "info", "--json"], + ["info", "--json"], + ], + [ + ["--json=false", "info"], + ["info", "--json=false"], + ], + [ + ["--json", "add", "x", "--", "--y"], + ["add", "x", "--json", "--", "--y"], + ], + [ + ["info", "--", "--json"], + ["info", "--", "--json"], + ], + [ + ["--", "--json", "info"], + ["--", "--json", "info"], + ], + [["--json"], ["--json"]], + [ + ["info", "--json"], + ["info", "--json"], + ], + ])("%j is read as %j", (given, read) => { + expect(jsonFlagAfterCommand(given)).toEqual(read); + }); + + it.each([ + [["info", "--json"], true], + [["info", "--", "--json"], false], + [["info", "--json=false"], false], + ])("%j asks for JSON: %s", (argv, asks) => { + expect(jsonFlagBeforeSeparator(argv)).toBe(asks); + }); + + // fails without the fix: `--json help info` was answered as an unknown command named `help`. + it("prints a command's help the same in both positions", async () => { + const first = await run(["--json", "help", "info"]); + const after = await run(["help", "info", "--json"]); + expect(first).toEqual(after); + expect(first.exit).toBe(0); + expect(first.stdout).toContain("hyperframes info"); + expect(first.stdout).not.toContain("unknown_command"); + }); + + it("answers the same in both positions, for every command", async () => { + const tree = await commandTree(); + const named = (json: boolean) => + tree + .filter((leaf) => !leaf.parent && leaf.json === json) + .map((leaf) => leaf.path.join(" ")) + .sort(); + expect({ with: named(true), without: named(false) }).toEqual({ + with: WITH_JSON, + without: WITHOUT_JSON, + }); + + const parents = tree.filter((leaf) => leaf.parent).map((leaf) => leaf.path.join(" ")); + expect(parents.sort()).toEqual([...REFUSED_PARENTS, ...OTHER_PARENTS].sort()); + + const wrong: unknown[] = []; + for (const leaf of tree) { + const words = [...leaf.path, ...leaf.required]; + const first = await run(["--json", ...words]); + const after = await run([...words, "--json"]); + if (leaf.parent && !REFUSED_PARENTS.includes(leaf.path.join(" "))) { + if (JSON.stringify(first) !== JSON.stringify(after)) wrong.push({ words, first, after }); + continue; + } + const expected = leaf.json + ? { stdout: "ran json=true\n", exit: 0 } + : { + stdout: `${JSON.stringify({ + ok: false, + error: { + code: "json_unsupported", + message: `hyperframes ${leaf.path.join(" ")} has no JSON output.`, + hint: "Run it without --json.", + }, + })}\n`, + exit: 2, + }; + if (JSON.stringify([first, after]) !== JSON.stringify([expected, expected])) { + wrong.push({ command: words, first, after }); + } + } + expect(wrong).toEqual([]); + }, 600_000); +}); diff --git a/packages/cli/src/cli.lifecycle.test.ts b/packages/cli/src/cli.lifecycle.test.ts index b03a5e7147..b2678df00b 100644 --- a/packages/cli/src/cli.lifecycle.test.ts +++ b/packages/cli/src/cli.lifecycle.test.ts @@ -29,6 +29,8 @@ afterEach(async () => { vi.resetModules(); }); +const PLAIN = "(no --json)"; + describe("CLI lifecycle", () => { it("queues a command failure before exit, without waiting on a network flush", async () => { let resolveEvents!: (events: { @@ -534,18 +536,17 @@ describe("CLI lifecycle", () => { "Invalid --quality 'be\u0007st'.", 2, ], - // `docs` has no --json flag of its own; --json before the command name still reaches it. - ["an unknown docs topic", ["--json", "docs", "to\u0007pic"], "Unknown topic: to\u0007pic", 2], - // The rows below put --json first too: the command then prints its lines for people. + // The rows below run without --json: with it these commands refuse or answer in their own JSON. + ["an unknown docs topic", [PLAIN, "docs", "to\u0007pic"], "Unknown topic: to\u0007pic", 2], [ "an unknown telemetry subcommand", - ["--json", "telemetry", "fo\u0007o"], + [PLAIN, "telemetry", "fo\u0007o"], "Unknown subcommand: fo\u0007o", 2, ], [ "a telemetry preference that cannot be saved", - ["--json", "telemetry", "disable"], + [PLAIN, "telemetry", "disable"], "Reason: EACCES /ho\u0007me", 1, () => @@ -559,21 +560,21 @@ describe("CLI lifecycle", () => { ], [ "a catalog query with no searchable words", - ["--json", "catalog", "--query", "!!\u0007"], + [PLAIN, "catalog", "--query", "!!\u0007"], 'No searchable words in query "!!\u0007".', 1, () => mockCatalogRegistry(), ], [ "a catalog whose registry cannot be read", - ["--json", "catalog"], + ["catalog"], "The registry could not be read: no route to ho\u0007st", 1, () => mockCatalogRegistry("The registry could not be read: no route to ho\u0007st"), ], [ "speech that cannot be generated", - ["--json", "tts", "hello", "--voice", "af_\u0007x"], + [PLAIN, "tts", "hello", "--voice", "af_\u0007x"], "no model at /mo\u0007dels", 1, () => @@ -584,7 +585,7 @@ describe("CLI lifecycle", () => { })), ], ] as [string, string[], string, number, (() => void)?][])( - "answers a --json run for %s with the value as given", + "shows %s as text, and answers a --json run with the value as given", async (_name, argv, given, exit, mock) => { const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => undefined) as never); const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); @@ -602,19 +603,21 @@ describe("CLI lifecycle", () => { try { mockTelemetry(); mock?.(); - process.argv = ["node", "cli.ts", ...argv, ...(argv[0] === "--json" ? [] : ["--json"])]; + const plain = argv[0] === PLAIN; + process.argv = ["node", "cli.ts", ...(plain ? argv.slice(1) : [...argv, "--json"])]; await import("./cli.js"); const said = errorSpy.mock.calls.map((call) => call.map(String).join(" ")).join("\n") + written; expect(said).toContain(given.replace("\u0007", "\\x07")); expect(said).not.toContain("\u0007"); + expect(process.exitCode).toBe(exit); + if (plain) return; const body = JSON.parse(answered.trim().split("\n").at(-1) ?? "") as { ok: boolean; error: { message: string }; }; expect(body.ok).toBe(false); - expect(process.exitCode).toBe(exit); expect(body.error.message).toContain(given); expect(body.error.message).not.toContain("\\x07"); } finally { diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index e546a95c18..6b86e3a9f5 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -52,6 +52,7 @@ import { existsSync } from "node:fs"; // `hyperframes --version` near-instant (~10ms vs ~80ms). import { VERSION } from "./version.js"; +process.argv = [...process.argv.slice(0, 2), ...jsonFlagAfterCommand(process.argv.slice(2))]; let argv = process.argv.slice(2); if (argv[0] === "help") { process.argv = [...process.argv.slice(0, 2), ...argv.slice(1), "--help"]; @@ -112,7 +113,9 @@ import { } from "./utils/commandResult.js"; import { registerRunningCli } from "./utils/runningCli.js"; import { + jsonFlagBeforeSeparator, commandWordIndex, + jsonFlagAfterCommand, measureProbeShortcutArgv, openShortcutArgv, registryAliasArgv, @@ -246,7 +249,7 @@ const cliCommandArg = process.argv[2]; // (in the failure reporter) and `command` references `subCommands` (the `in` // check), so its type can't be inferred from its own initializer. const command: string = cliCommandArg && cliCommandArg in subCommands ? cliCommandArg : "unknown"; -const hasJsonFlag = process.argv.includes("--json"); +const hasJsonFlag = jsonFlagBeforeSeparator(argv); // Under --json a failure always answers on stdout with the shared envelope (see executeCli). const jsonOutput = hasJsonFlag ? watchOutput() : undefined; diff --git a/packages/cli/src/commands/catalog.test.ts b/packages/cli/src/commands/catalog.test.ts index 43ceb12548..a36da5c5dd 100644 --- a/packages/cli/src/commands/catalog.test.ts +++ b/packages/cli/src/commands/catalog.test.ts @@ -767,6 +767,7 @@ describe("catalog meaning search, on a terminal", () => { expect(output).toContain("None of these do it?"); expect(output).toContain("--tier words"); + expect(output).toContain('--search-miss "count up"'); }); // fails without the fix: the command was printed with the query rewritten, so pasting it reported other text. diff --git a/packages/cli/src/commands/init.output.test.ts b/packages/cli/src/commands/init.output.test.ts index bee4b8337b..8cbc911823 100644 --- a/packages/cli/src/commands/init.output.test.ts +++ b/packages/cli/src/commands/init.output.test.ts @@ -11,7 +11,6 @@ const SHOWN = "od\\x1b[2Jd\\x07"; const fake = vi.hoisted(() => ({ lines: [] as string[], attended: false, - json: false, confirmAnswer: false, templates: [] as Array>, fetchRemoteTemplate: vi.fn(), @@ -22,10 +21,6 @@ vi.mock("../utils/attendedTerminal.js", async (importOriginal) => ({ ...(await importOriginal()), isUnattended: () => !fake.attended, })); -vi.mock("../utils/jsonError.js", async (importOriginal) => ({ - ...(await importOriginal()), - isJsonRun: () => fake.json, -})); vi.mock("@clack/prompts", () => { const say = (message: string) => void fake.lines.push(message); return { @@ -89,7 +84,6 @@ function oddFile(name: string): string { beforeEach(() => { fake.lines.length = 0; fake.attended = false; - fake.json = false; fake.confirmAnswer = false; fake.templates = []; fake.fetchRemoteTemplate.mockReset().mockRejectedValue(new Error(`gone ${ODD}\nsecond line`)); @@ -138,6 +132,15 @@ describe("init output without prompts", () => { expectNoControlCharacters(); }); + // fails without the fix: a spinner drew the video's status in a run that asks nothing. + it("prints a video's status as lines, without a spinner", async () => { + const video = join(work, "clip.mov"); + copyFileSync(new URL("./__fixtures__/mpeg4.mp4", import.meta.url), video); + await run({ name: join(work, "f"), video, "skip-transcribe": true }); + expect(printed()).toContain("Transcoded to clip.mp4\n"); + expect(printed()).not.toContain("(spinner)"); + }); + // Windows refuses control characters in file and folder names. describe.skipIf(process.platform === "win32")("with odd names on disk", () => { // fails without the fix: the folder name is repeated as it was typed. @@ -187,17 +190,6 @@ describe("init output with prompts", () => { expectNoControlCharacters(); }); - // fails without the fix: a run that asked for JSON went to the questions, and a spinner drew the video's status on stdout. - it.each([undefined, "gone"])("asks and spins nothing in a JSON run: %s", async (example) => { - fake.json = true; - const video = join(work, "clip.mov"); - copyFileSync(new URL("./__fixtures__/mpeg4.mp4", import.meta.url), video); - await run({ name: join(work, "f"), video, example, "skip-transcribe": true }).catch(String); - expect(printed()).toContain("Transcoded to clip.mp4\n"); - expect(printed()).toContain(example ? 'Failed to scaffold example "gone"' : "Get started:"); - expect(printed()).not.toContain("(spinner)"); - }); - // fails without the fix: the example name and the reason are printed as they arrived. it("shows control characters in a failed example download as text", async () => { await expect(run({ name: join(work, "film"), example: `ex-${ODD}` })).rejects.toThrow(); diff --git a/packages/cli/src/commands/init.test.ts b/packages/cli/src/commands/init.test.ts index 3e6bca3e0d..e3199948b4 100644 --- a/packages/cli/src/commands/init.test.ts +++ b/packages/cli/src/commands/init.test.ts @@ -620,15 +620,13 @@ describe("hyperframes init flag rename", () => { ); // One row per init failure line that names something the caller typed. - // fails without the fix: the answer's message was the line as people see it, escapes included. - describe("with --json first, a failure answers with the value as given", () => { + describe("a failure line shows the value as text", () => { type Row = { name: string; args: string[]; before?: (dir: string) => void; after?: (dir: string) => void; shown?: string; - given?: string; exit: number; stderr?: string; stdout?: string; @@ -641,7 +639,6 @@ describe("hyperframes init flag rename", () => { name: "the renamed --template flag", args: ["proj", "--template", "bl\u0007a\nnk "], shown: "--example ", - given: "(given: --template bl\u0007a\nnk )", exit: 2, stderr: "The --template flag was renamed to --example. Example:\n npx hyperframes init proj --example \n", @@ -650,7 +647,6 @@ describe("hyperframes init flag rename", () => { name: "the renamed -V flag", args: ["proj", "-V", "cl\u0007i\np.mp4 "], shown: "--video ", - given: "(given: -V cl\u0007i\np.mp4 )", exit: 2, stderr: "The -V short flag no longer maps to --video. Use --video (or -v). Example:\n npx hyperframes init proj --video \n", @@ -659,7 +655,6 @@ describe("hyperframes init flag rename", () => { name: "a refused --resolution", args: ["proj", "--resolution", "b\u0007a\nd "], shown: 'Invalid --resolution: "b\\x07a\nd "', - given: 'Invalid --resolution: "b\u0007a\nd "', exit: 2, }, { @@ -670,7 +665,6 @@ describe("hyperframes init flag rename", () => { writeFileSync(join(dir, "fu\u0007l\nl ", "notes.txt"), ""); }, shown: "fu\\x07l\nl ", - given: "fu\u0007l\nl ", exit: 1, skip: posixOnly, }, @@ -678,14 +672,12 @@ describe("hyperframes init flag rename", () => { name: "a missing --video", args: ["proj", "--video", "cl\u0007i\np.mp4 "], shown: "Video file not found: cl\\x07i\np.mp4 ", - given: "Video file not found: cl\u0007i\np.mp4 ", exit: 1, }, { name: "a missing --audio", args: ["proj", "--audio", "so\u0007n\ng.mp3 "], shown: "Audio file not found: so\\x07n\ng.mp3 ", - given: "Audio file not found: so\u0007n\ng.mp3 ", exit: 1, }, { @@ -698,18 +690,9 @@ describe("hyperframes init flag rename", () => { }, after: (dir) => chmodSync(join(dir, "lo\u0007cked"), 0o755), shown: 'Failed to scaffold example "from-file": ', - given: "lo\u0007cked", exit: 1, skip: posixOnly || process.getuid?.() === 0, }, - { - name: "a folder that cannot be made, in the words of the error itself", - args: ["fi\nle /sub"], - before: (dir) => writeFileSync(join(dir, "fi\nle "), ""), - given: "fi\nle /sub'", - exit: 1, - skip: posixOnly, - }, { name: "a finished project, whose status line still comes first", args: ["done", "--audio", "a.wav", "--skip-transcribe"], @@ -720,7 +703,6 @@ describe("hyperframes init flag rename", () => { { name: "the renamed --template flag with values the shell would split", args: ["my film", "--template", "two words"], - given: "The --template flag was renamed to --example (given: --template two words)", exit: 2, stderr: 'The --template flag was renamed to --example. Example:\n npx hyperframes init "my film" --example "two words"\n', @@ -728,8 +710,6 @@ describe("hyperframes init flag rename", () => { { name: "the renamed -V flag with a value in two words", args: ["proj", "-V", "two words.mp4"], - given: - "The -V short flag no longer maps to --video; use --video or -v (given: -V two words.mp4)", exit: 2, stderr: 'The -V short flag no longer maps to --video. Use --video (or -v). Example:\n npx hyperframes init proj --video "two words.mp4"\n', @@ -740,25 +720,17 @@ describe("hyperframes init flag rename", () => { const dir = mkdtempSync(join(tmpdir(), "hf-init-test-")); row.before?.(dir); try { - const res = spawnSync( - "bun", - ["run", cliEntry, "--json", "init", ...row.args, "--non-interactive"], - { - cwd: dir, - encoding: "utf-8", - timeout: 30_000, - env: { ...process.env, HYPERFRAMES_SKIP_SKILLS: "1" }, - }, - ); + const res = spawnSync("bun", ["run", cliEntry, "init", ...row.args, "--non-interactive"], { + cwd: dir, + encoding: "utf-8", + timeout: 30_000, + env: { ...process.env, HYPERFRAMES_SKIP_SKILLS: "1" }, + }); expect(res.status).toBe(row.exit); if (row.stdout !== undefined) return expect(res.stdout.startsWith(row.stdout)).toBe(true); expect(res.stderr).toContain(row.shown ?? ""); expect(res.stderr).not.toContain("\u0007"); if (row.stderr !== undefined) expect(res.stderr).toBe(row.stderr); - const body = JSON.parse(res.stdout.trim()) as { ok: boolean; error: { message: string } }; - expect(body.ok).toBe(false); - expect(body.error.message).toContain(row.given ?? ""); - expect(body.error.message).not.toContain("\\x07"); } finally { row.after?.(dir); rmSync(dir, { recursive: true, force: true }); diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts index eb4e1246c9..43bd02bc67 100644 --- a/packages/cli/src/commands/init.ts +++ b/packages/cli/src/commands/init.ts @@ -4,7 +4,7 @@ // own task. // fallow-ignore-file complexity import { failCommand, finishCommand, failUsage } from "../utils/commandResult.js"; -import { isJsonRun, printFailureLine, releaseStatus, status } from "../utils/jsonError.js"; +import { printFailureLine } from "../utils/jsonError.js"; import { writeNewFileSync } from "../utils/writeNewFile.js"; import { runCommand } from "citty"; import { defineCommand } from "../utils/defineCommand.js"; @@ -508,7 +508,7 @@ async function handleVideoFile( if (interactive) { clack.log.warn(msg); } else { - status(c.warn(msg)); + console.log(c.warn(msg)); } } @@ -521,7 +521,7 @@ async function handleVideoFile( ), ); } else { - status( + console.log( c.warn(`Video codec "${terminalText(probed.videoCodec)}" is not supported by browsers.`), ); } @@ -555,7 +555,8 @@ async function handleVideoFile( if (shouldTranscode) { const mp4Name = freeTranscodeName(destDir, localVideoName); const mp4Path = resolve(destDir, mp4Name); - const spin = interactive ? clack.spinner() : { start: status, stop: status }; + const say = (text: string) => console.log(text); + const spin = interactive ? clack.spinner() : { start: say, stop: say }; spin.start("Transcoding to H.264 MP4..."); const ok = await transcodeToMp4(videoPath, mp4Path); if (ok) { @@ -573,8 +574,8 @@ async function handleVideoFile( clack.log.warn(c.dim("ffmpeg not installed — cannot transcode.")); clack.log.info(c.accent(`Install: ${getFFmpegInstallHint()}`)); } else { - status(c.warn("ffmpeg not installed — cannot transcode. Copying original.")); - status(c.dim("Install: ") + c.accent(getFFmpegInstallHint())); + console.log(c.warn("ffmpeg not installed — cannot transcode. Copying original.")); + console.log(c.dim("Install: ") + c.accent(getFFmpegInstallHint())); } copyIntoProjectUnlessAlreadyThere(videoPath, resolve(destDir, localVideoName)); } @@ -865,23 +866,19 @@ export default defineCommand({ async run({ args }) { if (args.template !== undefined) { const template = args.template; - printFailureLine( - () => - c.error( - `The --template flag was renamed to --example. Example:\n npx hyperframes init ${shellArg(args.name ?? "my-video") ?? ""} --example ${shellArg(template) ?? ""}`, - ), - `The --template flag was renamed to --example (given: --template ${template})`, + printFailureLine(() => + c.error( + `The --template flag was renamed to --example. Example:\n npx hyperframes init ${shellArg(args.name ?? "my-video") ?? ""} --example ${shellArg(template) ?? ""}`, + ), ); failUsage(); } if (args["video-legacy"] !== undefined) { const legacy = args["video-legacy"]; - printFailureLine( - () => - c.error( - `The -V short flag no longer maps to --video. Use --video (or -v). Example:\n npx hyperframes init ${shellArg(args.name ?? "my-video") ?? ""} --video ${shellArg(legacy) ?? ""}`, - ), - `The -V short flag no longer maps to --video; use --video or -v (given: -V ${legacy})`, + printFailureLine(() => + c.error( + `The -V short flag no longer maps to --video. Use --video (or -v). Example:\n npx hyperframes init ${shellArg(args.name ?? "my-video") ?? ""} --video ${shellArg(legacy) ?? ""}`, + ), ); failUsage(); } @@ -899,7 +896,7 @@ export default defineCommand({ modelFlag ?? DEFAULT_MODEL, languageFlag, ); - const interactive = !nonInteractive && !isUnattended() && !isJsonRun(); + const interactive = !nonInteractive && !isUnattended(); let resolutionPreset: CanvasResolution | undefined; if (args.resolution !== undefined) { @@ -973,7 +970,7 @@ export default defineCommand({ videoHasAudio = result.meta.hasAudio; videoDuration = result.meta.durationSeconds; videoSize = result.meta; - status( + console.log( `Video: ${result.meta.width}x${result.meta.height}, ${result.meta.durationSeconds.toFixed(1)}s`, ); } @@ -984,7 +981,7 @@ export default defineCommand({ copyIntoProjectUnlessAlreadyThere(audioPath, resolve(destDir, basename(audioPath))); const { getMediaDurationSeconds } = await import("../whisper/transcribe.js"); videoDuration = getMediaDurationSeconds(audioPath) ?? undefined; - status(`Audio: ${terminalText(basename(audioPath))}`); + console.log(`Audio: ${terminalText(basename(audioPath))}`); } // Transcribe @@ -993,16 +990,18 @@ export default defineCommand({ const { ensureWhisper, ensureModel } = await import("../whisper/manager.js"); await ensureWhisper(); await ensureModel(initialTranscriptionModel); - status("Transcribing..."); + console.log("Transcribing..."); const { transcribe: runTranscribe } = await import("../whisper/transcribe.js"); const result = await runTranscribe(sourceFilePath, destDir, { model: modelFlag, language: languageFlag, }); - status(`Transcribed: ${result.wordCount} words (${result.durationSeconds.toFixed(1)}s)`); + console.log( + `Transcribed: ${result.wordCount} words (${result.durationSeconds.toFixed(1)}s)`, + ); if (!videoDuration) videoDuration = result.durationSeconds; } catch (err) { - status( + console.log( `Transcription skipped: ${terminalLines(err instanceof Error ? err.message : String(err))}`, ); } @@ -1025,19 +1024,15 @@ export default defineCommand({ args.skill, ); } catch (err) { - printFailureLine( - (show) => - c.error( - `Failed to scaffold example "${show(templateId)}": ${show(err instanceof Error ? err.message : String(err))}`, - ), - undefined, - "Use --example blank for offline use.", + printFailureLine((show) => + c.error( + `Failed to scaffold example "${show(templateId)}": ${show(err instanceof Error ? err.message : String(err))}`, + ), ); console.error(c.dim("Use --example blank for offline use.")); failCommand(); } await finishScaffold(destDir, templateId, tailwind); - releaseStatus(); console.log(c.success(`Created ${c.accent(terminalText(name) + "/")}`)); for (const f of readdirSync(destDir).filter((f) => !f.startsWith("."))) { diff --git a/packages/cli/src/utils/jsonError.ts b/packages/cli/src/utils/jsonError.ts index 916e00f333..4a2123ced7 100644 --- a/packages/cli/src/utils/jsonError.ts +++ b/packages/cli/src/utils/jsonError.ts @@ -50,31 +50,14 @@ export function writeJsonFailure(body: CliErrorBody): void { */ let reported: { message: string; hint?: string; exact?: boolean } | undefined; let noticeDepth = 0; -let jsonRun = false; -const heldStatus: string[] = []; -export function printFailureLine( - line: (show: (text: string) => string) => string, - answer?: string, - hint?: string, -): void { +export function printFailureLine(line: (show: (text: string) => string) => string): void { console.error(line(terminalLines)); const given: string[] = []; const shape = tidy(line((text) => `\uE000${given.push(text) - 1}\uE001`)); const message = shape.replace(/\uE000(\d+)\uE001/g, (_, at) => given[Number(at)] ?? ""); const earlier = reported?.exact ? `${reported.message} ` : ""; - reported = { message: earlier + (answer ?? message), hint, exact: true }; -} - -export const isJsonRun = (): boolean => jsonRun; - -export function status(text: string): void { - if (jsonRun) heldStatus.push(text); - else console.log(text); -} - -export function releaseStatus(): void { - for (const text of heldStatus.splice(0)) console.log(text); + reported = { message: earlier + message, exact: true }; } /** The failure a command reported to the person (errorBox); the envelope's message when it has none. */ @@ -106,7 +89,6 @@ export function failureMessage(error: unknown): string { } export function watchOutput(): { wroteStdout: () => boolean; stderrText: () => string } { - jsonRun = true; let wrote = false; let stderr = ""; let inConsole = false; diff --git a/packages/cli/src/utils/projectShortcut.ts b/packages/cli/src/utils/projectShortcut.ts index 51e4091c03..40f5e5a817 100644 --- a/packages/cli/src/utils/projectShortcut.ts +++ b/packages/cli/src/utils/projectShortcut.ts @@ -8,6 +8,26 @@ export function commandWordIndex(argv: readonly string[]): number { return end >= 0 && index >= end ? -1 : index; } +export function jsonFlagAfterCommand(argv: readonly string[]): readonly string[] { + const at = commandWordIndex(argv); + const isJson = (arg: string): boolean => arg === "--json" || arg.startsWith("--json="); + if (at < 0 || !argv.slice(0, at).some(isJson)) return argv; + const end = argv.indexOf("--", at); + const own = argv.slice(at, end < 0 ? argv.length : end); + const moved = [...new Set(argv.slice(0, at).filter(isJson))].filter((arg) => !own.includes(arg)); + return [ + ...argv.slice(0, at).filter((arg) => !isJson(arg)), + ...own, + ...moved, + ...argv.slice(at + own.length), + ]; +} + +export function jsonFlagBeforeSeparator(argv: readonly string[]): boolean { + const end = argv.indexOf("--"); + return argv.slice(0, end < 0 ? argv.length : end).includes("--json"); +} + /** `hyperframes ` is `hyperframes open `; a known command wins over a folder of the same name. */ export function openShortcutArgv( argv: readonly string[],