diff --git a/packages/cli/src/commands/lambda.ts b/packages/cli/src/commands/lambda.ts index 0f069ce326..8290c251a1 100644 --- a/packages/cli/src/commands/lambda.ts +++ b/packages/cli/src/commands/lambda.ts @@ -16,6 +16,7 @@ import { parseOutputResolutionFlag } from "../utils/parseOutputResolution.js"; import type { Example } from "./_examples.js"; import type { VideoArch } from "./lambda/videoImage.js"; import { c } from "../ui/colors.js"; +import { terminalText } from "@hyperframes/core"; import { deliveryFlagArgs, parseDeliveryFlags } from "../utils/deliveryFlags.js"; import { defaultCloudFps } from "../utils/compositionFps.js"; import { isMissingPackageError, missingPackageMessage } from "../utils/missingPackage.js"; @@ -293,7 +294,7 @@ export default defineCommand({ case "sites": { if (args.target !== "create") { console.error( - `[lambda sites] unknown verb "${String(args.target)}". Only "create" is supported.`, + `[lambda sites] unknown verb "${terminalText(String(args.target))}". Only "create" is supported.`, ); failUsage(); } @@ -454,7 +455,7 @@ export default defineCommand({ return; } default: - console.error(`${c.error("Unknown subcommand:")} ${subcommand}\n${HELP}`); + console.error(`${c.error("Unknown subcommand:")} ${terminalText(subcommand)}\n${HELP}`); failUsage(); } }, diff --git a/packages/cli/src/commands/lambda/deploy.test.ts b/packages/cli/src/commands/lambda/deploy.test.ts index e6d789a513..baddc13524 100644 --- a/packages/cli/src/commands/lambda/deploy.test.ts +++ b/packages/cli/src/commands/lambda/deploy.test.ts @@ -31,6 +31,10 @@ const { pushVideoImage } = await import("./videoImage.js"); let dir: string | undefined; let quiet: { mockRestore(): void }; +const ESC = String.fromCharCode(27); +const ODD = `od${ESC}[2Jd\x07`; +const SHOWN = "od\\x1b[2Jd\\x07"; + beforeEach(() => { vi.mocked(samDeploy).mockClear(); vi.mocked(warmFunction).mockReset(); @@ -119,6 +123,27 @@ describe("runDeploy", () => { expect(written).toHaveLength(1); }); + // fails without the fix: the stack outputs and the warm-up failure are printed as they arrived. + it("shows control characters in the stack outputs and a warm-up failure as text", async () => { + checkout(); + vi.mocked(fetchStackOutputs).mockReset(); + vi.mocked(fetchStackOutputs).mockReturnValueOnce({ + bucketName: `b-${ODD}`, + functionName: `f-${ODD}`, + stateMachineArn: `s-${ODD}`, + videoFunctionName: `v-${ODD}`, + }); + vi.mocked(warmFunction).mockImplementation(() => { + throw new Error(`Task ${ODD}\ntimed out`); + }); + await runDeploy({ skipBuild: true, stackName: `hf${ODD}`, region: "eu-west-1" }); + const printed = vi.mocked(console.log).mock.calls.flat().join("\n"); + expect(printed).toContain(`sam deploy (stack=hf${SHOWN} region=eu-west-1)`); + for (const shown of ["b-", "f-", "s-", "v-"]) expect(printed).toContain(`${shown}${SHOWN}`); + expect(printed).toContain(`the deploy is fine: Task ${SHOWN}\ntimed out`); + expect(printed).not.toContain(ESC); + }); + it("does not warm with warm: false", async () => { checkout(); await runDeploy({ skipBuild: true, stackName: "hf", warm: false }); diff --git a/packages/cli/src/commands/lambda/deploy.ts b/packages/cli/src/commands/lambda/deploy.ts index 297ff86ad6..375bd72662 100644 --- a/packages/cli/src/commands/lambda/deploy.ts +++ b/packages/cli/src/commands/lambda/deploy.ts @@ -12,6 +12,7 @@ import { spawnSync } from "node:child_process"; import { existsSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; import { c } from "../../ui/colors.js"; +import { terminalLines, terminalText } from "@hyperframes/core"; import { stagePrebuiltHandler } from "./prebuiltHandler.js"; import { fetchStackOutputs, locateSamTemplate, samDeploy } from "./sam.js"; import { repoRoot } from "./repoRoot.js"; @@ -66,7 +67,9 @@ export async function runDeploy(args: Partial = {}): Promise { }) : undefined; - console.log(c.dim(`→ sam deploy (stack=${resolved.stackName} region=${resolved.region})`)); + console.log( + c.dim(terminalText(`→ sam deploy (stack=${resolved.stackName} region=${resolved.region})`)), + ); samDeploy({ samDir, stackName: resolved.stackName, @@ -108,13 +111,13 @@ export async function runDeploy(args: Partial = {}): Promise { console.log(); console.log(c.success("Stack deployed.")); - console.log(` ${c.dim("Bucket:")} ${outputs.bucketName}`); - console.log(` ${c.dim("State machine:")} ${outputs.stateMachineArn}`); - console.log(` ${c.dim("Function:")} ${outputs.functionName}`); + console.log(` ${c.dim("Bucket:")} ${terminalText(outputs.bucketName)}`); + console.log(` ${c.dim("State machine:")} ${terminalText(outputs.stateMachineArn)}`); + console.log(` ${c.dim("Function:")} ${terminalText(outputs.functionName)}`); if (outputs.videoFunctionName) { - console.log(` ${c.dim("Video function:")} ${outputs.videoFunctionName} (arm64)`); + console.log(` ${c.dim("Video function:")} ${terminalText(outputs.videoFunctionName)} (arm64)`); } - console.log(` ${c.dim("State file:")} ${resolve(statePath)}`); + console.log(` ${c.dim("State file:")} ${terminalText(resolve(statePath))}`); console.log(); console.log(c.dim(`Render with: hyperframes lambda render `)); } @@ -141,7 +144,9 @@ function warmVideoFunction(functionName: string | undefined, args: DeployArgs): try { warmFunction({ functionName, region: args.region, awsProfile: args.awsProfile }); } catch (error) { - console.log(c.warn(`Warm-up skipped, the deploy is fine: ${(error as Error).message}`)); + console.log( + c.warn(terminalLines(`Warm-up skipped, the deploy is fine: ${(error as Error).message}`)), + ); } } diff --git a/packages/cli/src/commands/lambda/destroy.test.ts b/packages/cli/src/commands/lambda/destroy.test.ts index cebc40a6ea..dc2fcc6089 100644 --- a/packages/cli/src/commands/lambda/destroy.test.ts +++ b/packages/cli/src/commands/lambda/destroy.test.ts @@ -20,6 +20,10 @@ let cwd: string; let previousCwd: string; let quiet: { mockRestore(): void }; +const ESC = String.fromCharCode(27); +const ODD = `od${ESC}[2Jd\x07`; +const SHOWN = "od\\x1b[2Jd\\x07"; + beforeEach(() => { cwd = mkdtempSync(join(tmpdir(), "hf-lambda-destroy-")); previousCwd = process.cwd(); @@ -67,4 +71,21 @@ describe("runDestroy", () => { expect.objectContaining({ repositoryName: "demo-video" }), ); }); + + // fails without the fix: the stack name, in the progress lines, is printed as it is stored. + it.skipIf(process.platform === "win32")( + "shows control characters in the stack and repository names as text", + async () => { + const stackName = `De${ODD}mo`; + writeStackOutputs({ ...stack, stackName, videoRepository: "repo" }, cwd); + + await runDestroy({ stackName }); + + const printed = vi.mocked(console.log).mock.calls.flat().join("\n"); + expect(printed).toContain(`sam delete (stack=De${SHOWN}mo region=us-east-1)`); + expect(printed).toContain(`Deleting ECR repository de${SHOWN.toLowerCase()}mo-video`); + expect(printed).not.toContain(ESC); + expect(samDelete).toHaveBeenCalledWith(expect.objectContaining({ stackName })); + }, + ); }); diff --git a/packages/cli/src/commands/lambda/destroy.ts b/packages/cli/src/commands/lambda/destroy.ts index f2d893e28f..821655a647 100644 --- a/packages/cli/src/commands/lambda/destroy.ts +++ b/packages/cli/src/commands/lambda/destroy.ts @@ -13,6 +13,7 @@ import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { c } from "../../ui/colors.js"; +import { terminalText } from "@hyperframes/core"; import { deleteStackOutputs, requireStack } from "./state.js"; import { deleteEcrRepository, samDelete } from "./sam.js"; import { repoRoot } from "./repoRoot.js"; @@ -25,7 +26,9 @@ export interface DestroyArgs { export async function runDestroy(args: DestroyArgs): Promise { const stack = requireStack(args.stackName); - console.log(c.dim(`→ sam delete (stack=${stack.stackName} region=${stack.region})`)); + console.log( + c.dim(terminalText(`→ sam delete (stack=${stack.stackName} region=${stack.region})`)), + ); const root = repoRoot(); const awsProfile = args.awsProfile ?? process.env.AWS_PROFILE; // Mirror deploy.ts's AWS_PROFILE env fallback — `AWS_PROFILE=prod @@ -41,7 +44,7 @@ export async function runDestroy(args: DestroyArgs): Promise { } if (stack.videoRepository) { const repositoryName = videoRepositoryName(stack.stackName); - console.log(c.dim(`→ Deleting ECR repository ${repositoryName}`)); + console.log(c.dim(terminalText(`→ Deleting ECR repository ${repositoryName}`))); deleteEcrRepository({ repositoryName, region: stack.region, awsProfile }); } deleteStackOutputs(args.stackName); @@ -49,7 +52,7 @@ export async function runDestroy(args: DestroyArgs): Promise { console.log(c.success("Stack torn down.")); console.log( c.dim( - `Note: the render bucket "${stack.bucketName}" was deployed with Retain — empty + delete it via the AWS console or CLI if you want to fully reclaim storage.`, + `Note: the render bucket "${terminalText(stack.bucketName)}" was deployed with Retain — empty + delete it via the AWS console or CLI if you want to fully reclaim storage.`, ), ); } diff --git a/packages/cli/src/commands/lambda/output.test.ts b/packages/cli/src/commands/lambda/output.test.ts new file mode 100644 index 0000000000..1517f52e4d --- /dev/null +++ b/packages/cli/src/commands/lambda/output.test.ts @@ -0,0 +1,274 @@ +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { consumeCommandResult } from "../../utils/commandResult.js"; +import { writeStackOutputs } from "./state.js"; + +const ESC = String.fromCharCode(27); +const ODD = `od${ESC}[2Jd\x07`; +const SHOWN = "od\\x1b[2Jd\\x07"; + +const sdk = vi.hoisted(() => ({ + getRenderProgress: vi.fn(), + renderToLambda: vi.fn(), + deploySite: vi.fn(), + assertStackReadsSites: vi.fn(async () => {}), + parseStateMachineArn: () => ({ account: "123456789012" }), + siteHandleFromId: (bucketName: string, siteId: string) => ({ + siteId, + projectS3Uri: `s3://${bucketName}/sites/${siteId}`, + bytes: 0, + uploaded: false, + uploadedAt: "", + }), +})); +vi.mock("@hyperframes/aws-lambda/sdk", () => sdk); + +const { default: lambdaCommand } = await import("../lambda.js"); + +const STACK = "demo"; +const lines: string[] = []; +let cwd: string; +let previousCwd: string; + +const printed = (): string => lines.join("\n").replace(new RegExp(`${ESC}\\[[0-9;]*m`, "g"), ""); + +function expectNoControlCharacters(): void { + expect(printed()).not.toContain(ESC); + expect(printed()).not.toContain("\x07"); +} + +function run(args: Record): Promise { + return Promise.resolve( + lambdaCommand.run?.({ + args: { "stack-name": STACK, ...args }, + rawArgs: [], + cmd: lambdaCommand, + } as never), + ); +} + +function progress(over: Record): Record { + return { + status: "SUCCEEDED", + overallProgress: 1, + framesRendered: 30, + totalFrames: 30, + lambdasInvoked: 2, + costs: { displayCost: "$0.01", breakdown: { lambdaUsd: 0.01, stepFunctionsUsd: 0 } }, + outputFile: null, + errors: [], + warnings: [], + fatalErrorEncountered: false, + ...over, + }; +} + +beforeEach(() => { + lines.length = 0; + cwd = mkdtempSync(join(tmpdir(), "hf-lambda-output-")); + previousCwd = process.cwd(); + process.chdir(cwd); + writeStackOutputs({ + stackName: STACK, + region: "us-east-1", + bucketName: "demo-bucket", + stateMachineArn: "arn:aws:states:us-east-1:123456789012:stateMachine:hf", + functionName: "hf-render", + lambdaMemoryMb: 10240, + deployedAt: "2026-01-01T00:00:00Z", + }); + for (const method of ["log", "error", "warn"] as const) + vi.spyOn(console, method).mockImplementation((...args: unknown[]) => { + lines.push(args.join(" ")); + }); + for (const fake of [sdk.getRenderProgress, sdk.renderToLambda, sdk.deploySite]) fake.mockReset(); +}); + +afterEach(() => { + consumeCommandResult(); + vi.restoreAllMocks(); + process.chdir(previousCwd); + rmSync(cwd, { recursive: true, force: true }); +}); + +describe("lambda output for people", () => { + // fails without the fix: the status, warning, output address and failure rows are printed as they arrived. + it("progress shows control characters in a reply as text", async () => { + sdk.getRenderProgress.mockResolvedValue( + progress({ + status: `FAIL${ODD}`, + warnings: [`slow ${ODD}`], + outputFile: { s3Uri: `s3://demo-bucket/${ODD}.mp4`, bytes: 1 }, + errors: [{ state: `Render${ODD}`, error: `Err${ODD}`, cause: `why ${ODD}\nmore` }], + fatalErrorEncountered: true, + }), + ); + await run({ subcommand: "progress", target: "render-1" }); + expect(printed()).toContain(`slow ${SHOWN}`); + expect(printed()).toContain(`FAIL${SHOWN}`); + expect(printed()).toContain(`s3://demo-bucket/${SHOWN}.mp4`); + expect(printed()).toContain(`Render${SHOWN}: Err${SHOWN} — why ${SHOWN}\nmore`); + expectNoControlCharacters(); + expect(consumeCommandResult()?.exitCode).toBe(1); + }); + + // fails without the fix: the notice, the started render's rows and the finished output are printed as they arrived. + it("render --wait shows control characters in a notice and in the replies as text", async () => { + sdk.renderToLambda.mockImplementation(async (options: { onNotice?: (m: string) => void }) => { + options.onNotice?.(`left out ${ODD}`); + return { + renderId: `id-${ODD}`, + executionArn: `arn-${ODD}`, + outputS3Uri: `s3://out/${ODD}`, + projectS3Uri: `s3://site/${ODD}`, + }; + }); + sdk.getRenderProgress.mockResolvedValue( + progress({ warnings: [`slow ${ODD}`], outputFile: { s3Uri: `s3://done/${ODD}`, bytes: 9 } }), + ); + await run({ + subcommand: "render", + target: join(cwd, "project"), + width: "1920", + height: "1080", + fps: "30", + wait: true, + }); + for (const shown of [ + "left out ", + "id-", + "arn-", + "s3://out/", + "s3://site/", + "slow ", + "s3://done/", + ]) + expect(printed()).toContain(`${shown}${SHOWN}`); + expectNoControlCharacters(); + }); + + // fails without the fix: the ending status and the failure rows are printed as they arrived. + it("render --wait shows control characters in a failed render's rows as text", async () => { + sdk.renderToLambda.mockResolvedValue({ + renderId: "id", + executionArn: "arn", + outputS3Uri: "s3://out", + projectS3Uri: "s3://site", + }); + sdk.getRenderProgress.mockResolvedValue( + progress({ + status: `ABORT${ODD}`, + errors: [{ state: `Chunk${ODD}`, error: `Err${ODD}`, cause: `why ${ODD}` }], + }), + ); + await run({ + subcommand: "render", + target: join(cwd, "project"), + width: "1920", + height: "1080", + fps: "30", + wait: true, + }); + expect(printed()).toContain(`[ABORT${SHOWN}]`); + expect(printed()).toContain(`Render ended with status ABORT${SHOWN}.`); + expect(printed()).toContain(`Chunk${SHOWN}: Err${SHOWN} — why ${SHOWN}`); + expectNoControlCharacters(); + expect(consumeCommandResult()?.exitCode).toBe(1); + }); + + // fails without the fix: the poll hint repeats the render id as it arrived. + it("render shows control characters in the poll hint as text", async () => { + sdk.renderToLambda.mockResolvedValue({ + renderId: `id-${ODD}`, + executionArn: "arn", + outputS3Uri: "s3://out", + projectS3Uri: "s3://site", + }); + await run({ + subcommand: "render", + target: join(cwd, "project"), + width: "1920", + height: "1080", + fps: "30", + }); + expect(printed()).toContain(`hyperframes lambda progress id-${SHOWN}`); + expectNoControlCharacters(); + }); + + // fails without the fix: the notice, the site rows and the render hint are printed as they arrived. + it("sites create shows control characters in a notice, the reply and the hint as text", async () => { + sdk.deploySite.mockImplementation(async (options: { onNotice?: (m: string) => void }) => { + options.onNotice?.(`left out ${ODD}`); + return { + siteId: `site-${ODD}`, + projectS3Uri: `s3://site/${ODD}`, + bytes: 3, + uploaded: true, + uploadedAt: `then ${ODD}`, + }; + }); + await run({ subcommand: "sites", target: "create", extra: `proj${ODD}` }); + for (const shown of ["left out ", "site-", "s3://site/", "then ", "lambda render proj"]) + expect(printed()).toContain(`${shown}${SHOWN}`); + expect(printed()).toContain(`--site-id=site-${SHOWN} --stack-name=${STACK}`); + expectNoControlCharacters(); + }); + + // fails without the fix: the notice, the site id and each row's key, address or reason are printed as they arrived. + it("render-batch shows control characters in a notice and in each row as text", async () => { + const batch = join(cwd, "batch.jsonl"); + writeFileSync( + batch, + [`key-a-${ODD}`, `key-b-${ODD}`].map((outputKey) => JSON.stringify({ outputKey })).join("\n"), + ); + sdk.deploySite.mockImplementation(async (options: { onNotice?: (m: string) => void }) => { + options.onNotice?.(`left out ${ODD}`); + return { siteId: `site-${ODD}`, projectS3Uri: "s3://site", bytes: 3, uploaded: true }; + }); + sdk.renderToLambda.mockImplementation(async (options: { outputKey: string }) => { + if (options.outputKey.startsWith("key-b")) throw new Error(`refused ${ODD}\nsecond line`); + return { executionArn: `arn-${ODD}` }; + }); + await run({ + subcommand: "render-batch", + target: join(cwd, "project"), + batch, + width: "1920", + height: "1080", + fps: "30", + "max-concurrent": "1", + }); + for (const shown of ["left out ", "batch: site-", "key-a-", "key-b-", "arn-"]) + expect(printed()).toContain(`${shown}${SHOWN}`); + expect(printed()).toContain(`refused ${SHOWN}\nsecond line`); + expectNoControlCharacters(); + expect(consumeCommandResult()?.exitCode).toBe(1); + }); + + // fails without the fix: the subcommand is repeated as it was typed. + it("shows control characters in an unknown subcommand as text", async () => { + await expect(run({ subcommand: `ren${ODD}der` })).rejects.toThrow(); + expect(printed()).toContain(`Unknown subcommand: ren${SHOWN}der`); + expectNoControlCharacters(); + }); + + // fails without the fix: the verb is repeated as it was typed. + it("shows control characters in an unknown sites verb as text", async () => { + await expect(run({ subcommand: "sites", target: `cre${ODD}ate` })).rejects.toThrow(); + expect(printed()).toContain(`unknown verb "cre${SHOWN}ate"`); + expectNoControlCharacters(); + }); + + // fails without the fix: the stack name is repeated as it was typed, in the path and in the hint. + it("shows control characters in a missing stack's name as text", async () => { + await expect( + run({ subcommand: "progress", target: "render-1", "stack-name": `st${ODD}ack` }), + ).rejects.toThrow(); + expect(printed()).toContain(`no stack state for "st${SHOWN}ack"`); + expect(printed()).toContain(`--stack-name=st${SHOWN}ack`); + expect(printed()).toContain(`Known stacks here: ${STACK}.`); + expectNoControlCharacters(); + }); +}); diff --git a/packages/cli/src/commands/lambda/policies.test.ts b/packages/cli/src/commands/lambda/policies.test.ts index 8566efe259..7c9b980be6 100644 --- a/packages/cli/src/commands/lambda/policies.test.ts +++ b/packages/cli/src/commands/lambda/policies.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -6,8 +6,10 @@ import { allRequiredActions, buildPolicyDocument, buildRoleTrustPolicy, + runPolicies, validatePolicy, } from "./policies.js"; +import { consumeCommandResult } from "../../utils/commandResult.js"; let workdir: string; @@ -238,3 +240,42 @@ function writePolicy(doc: { Version: string; Statement: unknown }): string { writeFileSync(path, JSON.stringify(doc)); return path; } + +describe("policies — validate output for people", () => { + const ODD = "\u009b2J\u0007"; + const SHOWN = "\\x9b2J\\x07"; + + afterEach(() => { + consumeCommandResult(); + vi.restoreAllMocks(); + }); + + // fails without the fix: the path is printed as it was typed. + it("shows control characters in a missing policy path as text", async () => { + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + await runPolicies({ + verb: "validate", + inputPath: join(workdir, `po${ODD}licy.json`), + json: false, + }); + const printed = error.mock.calls.flat().join("\n"); + expect(printed).toContain(`po${SHOWN}licy.json`); + expect(printed).not.toContain(ODD); + expect(consumeCommandResult().exitCode).toBe(1); + }); + + // fails without the fix: the pattern from the policy file is printed as it was written. + it("shows control characters in a warned action pattern as text", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + vi.spyOn(console, "log").mockImplementation(() => {}); + const path = join(workdir, "policy.json"); + writeFileSync( + path, + JSON.stringify({ Statement: [{ Effect: "Allow", Action: ["s3:Get\u009b2J*Object"] }] }), + ); + await runPolicies({ verb: "validate", inputPath: path, json: false }); + const printed = warn.mock.calls.flat().join("\n"); + expect(printed).toContain("s3:Get\\x9b2J*Object"); + expect(printed).not.toContain("\u009b"); + }); +}); diff --git a/packages/cli/src/commands/lambda/policies.ts b/packages/cli/src/commands/lambda/policies.ts index b6599ddd11..6e9996a283 100644 --- a/packages/cli/src/commands/lambda/policies.ts +++ b/packages/cli/src/commands/lambda/policies.ts @@ -22,6 +22,7 @@ import { CliUsageError, failUsage, setCommandExitCode } from "../../utils/comman */ import { readJsonFileText } from "../../utils/jsonFlag.js"; +import { terminalLines } from "@hyperframes/core"; import { c } from "../../ui/colors.js"; import { failureMessage, jsonFailure } from "../../utils/jsonError.js"; @@ -279,7 +280,7 @@ export async function runPolicies(args: PoliciesArgs): Promise { setCommandExitCode(1); return; } - console.error(c.error(`Failed to validate ${args.inputPath}: ${msg}`)); + console.error(c.error(terminalLines(`Failed to validate ${args.inputPath}: ${msg}`))); setCommandExitCode(1); return; } @@ -289,7 +290,7 @@ export async function runPolicies(args: PoliciesArgs): Promise { return; } for (const warning of result.warnings) { - console.warn(c.dim(`Warning: ${warning}`)); + console.warn(c.dim(`Warning: ${terminalLines(warning)}`)); } if (result.missing.length === 0) { console.log(c.success(`Policy covers all ${result.required.length} required actions.`)); diff --git a/packages/cli/src/commands/lambda/prebuiltHandler.test.ts b/packages/cli/src/commands/lambda/prebuiltHandler.test.ts index 7063b76b9d..1ae7f4f761 100644 --- a/packages/cli/src/commands/lambda/prebuiltHandler.test.ts +++ b/packages/cli/src/commands/lambda/prebuiltHandler.test.ts @@ -3,7 +3,12 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { noHandlerMessage, type StageDeps, stagePrebuiltHandler } from "./prebuiltHandler.js"; +import { + defaultDeps, + noHandlerMessage, + type StageDeps, + stagePrebuiltHandler, +} from "./prebuiltHandler.js"; const ownedByAnotherAccount = vi.hoisted(() => new Set()); vi.mock("node:fs", async (importOriginal) => { @@ -22,6 +27,10 @@ const SHA = createHash("sha256").update(ZIP).digest("hex"); const URL = "https://github.com/heygen-com/hyperframes/releases/download/v9.8.7/x.zip"; const dirs: string[] = []; +const ESC = String.fromCharCode(27); +const ODD = `od${ESC}[2Jd\x07`; +const SHOWN = "od\\x1b[2Jd\\x07"; + function setup(body: Buffer = ZIP) { const root = mkdtempSync(join(tmpdir(), "hf-prebuilt-")); dirs.push(root); @@ -172,4 +181,15 @@ describe("stagePrebuiltHandler with nothing to deploy", () => { expect(noHandlerMessage(true)).toMatch(/has no prebuilt handler for its version/); expect(downloads).toEqual([]); }); + + // fails without the fix: a progress line is printed as it was handed over. + it("prints a progress line's control characters as text", () => { + const said = vi.spyOn(console, "log").mockImplementation(() => {}); + try { + defaultDeps.log(`→ Pushing to ${ODD}`); + expect(said.mock.calls).toEqual([[`→ Pushing to ${SHOWN}`]]); + } finally { + said.mockRestore(); + } + }); }); diff --git a/packages/cli/src/commands/lambda/prebuiltHandler.ts b/packages/cli/src/commands/lambda/prebuiltHandler.ts index a1ff49ba8a..65c1a1f247 100644 --- a/packages/cli/src/commands/lambda/prebuiltHandler.ts +++ b/packages/cli/src/commands/lambda/prebuiltHandler.ts @@ -12,6 +12,7 @@ import { } from "node:fs"; import { dirname, join } from "node:path"; import { downloadFile } from "../../utils/download.js"; +import { terminalLines } from "@hyperframes/core"; import { isMissingPackageError } from "../../utils/missingPackage.js"; import { VERSION } from "../../version.js"; import { @@ -39,7 +40,7 @@ export const defaultDeps: StageDeps = { loadAdapter: () => import("@hyperframes/aws-lambda/sdk"), download: downloadFile, cacheDir: HANDLER_CACHE_DIR, - log: (line) => console.log(line), + log: (line) => console.log(terminalLines(line)), }; /** The one message for "no checkout and no pinned handler": everything the user needs to fix it. */ diff --git a/packages/cli/src/commands/lambda/progress.ts b/packages/cli/src/commands/lambda/progress.ts index 915c50222e..7e8cc10fd7 100644 --- a/packages/cli/src/commands/lambda/progress.ts +++ b/packages/cli/src/commands/lambda/progress.ts @@ -7,6 +7,7 @@ import { setCommandExitCode } from "../../utils/commandResult.js"; */ import { c } from "../../ui/colors.js"; +import { terminalLines, terminalText } from "@hyperframes/core"; import { videoArchitecture, requireStack } from "./state.js"; export interface ProgressArgs { @@ -40,10 +41,10 @@ export async function runProgress(args: ProgressArgs): Promise { console.log(JSON.stringify(progress, null, 2)); return; } - for (const warning of progress.warnings) console.warn(c.warn(warning)); + for (const warning of progress.warnings) console.warn(c.warn(terminalLines(warning))); const pct = Math.round(progress.overallProgress * 100); - console.log(`${c.dim("Status:")} ${statusColor(progress.status)}`); + console.log(`${c.dim("Status:")} ${statusColor(terminalText(progress.status))}`); console.log(`${c.dim("Progress:")} ${pct}%`); console.log( `${c.dim("Frames:")} ${progress.framesRendered}${progress.totalFrames === null ? "" : ` / ${progress.totalFrames}`}`, @@ -53,13 +54,15 @@ export async function runProgress(args: ProgressArgs): Promise { `${c.dim("Cost:")} ${progress.costs.displayCost} (Lambda $${progress.costs.breakdown.lambdaUsd.toFixed(4)} + SFN $${progress.costs.breakdown.stepFunctionsUsd.toFixed(4)})`, ); if (progress.outputFile) { - console.log(`${c.dim("Output:")} ${progress.outputFile.s3Uri}`); + console.log(`${c.dim("Output:")} ${terminalText(progress.outputFile.s3Uri)}`); } if (progress.errors.length > 0) { console.log(); console.log(c.error("Errors:")); for (const err of progress.errors) { - console.log(` ${c.dim(err.state)}: ${err.error} — ${err.cause}`); + console.log( + ` ${c.dim(terminalText(err.state))}: ${terminalLines(err.error)} — ${terminalLines(err.cause)}`, + ); } } if (progress.fatalErrorEncountered) { diff --git a/packages/cli/src/commands/lambda/render-batch.ts b/packages/cli/src/commands/lambda/render-batch.ts index 77637f7641..8e303d9838 100644 --- a/packages/cli/src/commands/lambda/render-batch.ts +++ b/packages/cli/src/commands/lambda/render-batch.ts @@ -31,6 +31,7 @@ import type { } from "@hyperframes/aws-lambda/sdk"; import type { CanvasResolution, DistributedFps } from "@hyperframes/core"; import { c } from "../../ui/colors.js"; +import { terminalLines, terminalText } from "@hyperframes/core"; import { errorBox } from "../../ui/format.js"; import { loadProjectVariableSchema, @@ -246,14 +247,14 @@ export async function runRenderBatch(args: RenderBatchArgs): Promise { expectedBucketOwner: parseStateMachineArn(stack.stateMachineArn).account, region: stack.region, includeOutsideFiles: args.includeOutsideFiles, - onNotice: (message) => console.error(c.dim(message)), + onNotice: (message) => console.error(c.dim(terminalLines(message))), }); if (!args.json) { console.log( c.success( siteHandle.uploaded - ? `Site uploaded once for the batch: ${siteHandle.siteId}` - : `Site already up to date (skipped upload): ${siteHandle.siteId}`, + ? `Site uploaded once for the batch: ${terminalText(siteHandle.siteId)}` + : `Site already up to date (skipped upload): ${terminalText(siteHandle.siteId)}`, ), ); console.log(); @@ -338,9 +339,11 @@ export async function runRenderBatch(args: RenderBatchArgs): Promise { : c.error("✗"); const detail = row.status === "failed-to-start" - ? c.error(row.error ?? "unknown error") - : (row.executionArn ?? c.dim("(no execution)")); - console.log(` ${tag} line ${row.inputLine} ${c.dim(row.outputKey)} ${detail}`); + ? c.error(terminalLines(row.error ?? "unknown error")) + : row.executionArn + ? terminalText(row.executionArn) + : c.dim("(no execution)"); + console.log(` ${tag} line ${row.inputLine} ${c.dim(terminalText(row.outputKey))} ${detail}`); } if (failed > 0) setCommandExitCode(1); } diff --git a/packages/cli/src/commands/lambda/render.ts b/packages/cli/src/commands/lambda/render.ts index 59b126ec2b..ffc65e8174 100644 --- a/packages/cli/src/commands/lambda/render.ts +++ b/packages/cli/src/commands/lambda/render.ts @@ -13,6 +13,7 @@ import type { } from "@hyperframes/aws-lambda/sdk"; import type { CanvasResolution, DistributedFps } from "@hyperframes/core"; import { c } from "../../ui/colors.js"; +import { terminalLines, terminalText } from "@hyperframes/core"; import type { DeliveryFlagValues } from "../../utils/deliveryFlags.js"; import { reportVariableIssues, @@ -121,7 +122,7 @@ export async function runRender(args: RenderArgs): Promise { // doesn't quietly become a no-op. console.warn( c.warn( - `--strict-variables: no ${indexPath} on disk — schema validation skipped. ` + + `--strict-variables: no ${terminalText(indexPath)} on disk — schema validation skipped. ` + "Variables flow through unchecked. To enable strict checking, run from a project dir that contains the composition.", ), ); @@ -148,7 +149,7 @@ export async function runRender(args: RenderArgs): Promise { executionName: args.executionName, outputKey: args.outputKey, includeOutsideFiles: args.includeOutsideFiles, - onNotice: (message) => console.error(c.dim(message)), + onNotice: (message) => console.error(c.dim(terminalLines(message))), }); if (args.json) { @@ -166,17 +167,17 @@ export async function runRender(args: RenderArgs): Promise { } console.log(c.success("Render started.")); - console.log(` ${c.dim("Render ID:")} ${handle.renderId}`); - console.log(` ${c.dim("Execution ARN:")} ${handle.executionArn}`); - console.log(` ${c.dim("Output S3 URI:")} ${handle.outputS3Uri}`); - console.log(` ${c.dim("Project S3:")} ${handle.projectS3Uri}`); - console.log(` ${c.dim("Stack state:")} ${stateFilePath(args.stackName)}`); + console.log(` ${c.dim("Render ID:")} ${terminalText(handle.renderId)}`); + console.log(` ${c.dim("Execution ARN:")} ${terminalText(handle.executionArn)}`); + console.log(` ${c.dim("Output S3 URI:")} ${terminalText(handle.outputS3Uri)}`); + console.log(` ${c.dim("Project S3:")} ${terminalText(handle.projectS3Uri)}`); + console.log(` ${c.dim("Stack state:")} ${terminalText(stateFilePath(args.stackName))}`); console.log(); if (args.wait) { await waitForCompletion(handle.executionArn, stack, args.waitIntervalMs, args.json); return; } - console.log(c.dim(`Poll with: hyperframes lambda progress ${handle.renderId}`)); + console.log(c.dim(`Poll with: hyperframes lambda progress ${terminalText(handle.renderId)}`)); } async function waitForCompletion( @@ -197,7 +198,7 @@ async function waitForCompletion( videoArchitecture: videoArchitecture(stack), }); for (const warning of progress.warnings) { - if (!warned.has(warning)) console.warn(c.warn(warning)); + if (!warned.has(warning)) console.warn(c.warn(terminalLines(warning))); warned.add(warning); } if (!json && progress.framesRendered !== lastRendered) { @@ -205,7 +206,7 @@ async function waitForCompletion( const total = progress.totalFrames ?? "?"; const pct = Math.round(progress.overallProgress * 100); console.log( - ` ${c.dim(`[${progress.status}]`)} ${pct}% • ${progress.framesRendered}/${total} frames • ${progress.costs.displayCost}`, + ` ${c.dim(`[${terminalText(progress.status)}]`)} ${pct}% • ${progress.framesRendered}/${total} frames • ${progress.costs.displayCost}`, ); } if (progress.status !== "RUNNING") { @@ -214,14 +215,16 @@ async function waitForCompletion( } else if (progress.status === "SUCCEEDED" && progress.outputFile) { console.log(); console.log(c.success("Render complete.")); - console.log(` ${c.dim("Output:")} ${progress.outputFile.s3Uri}`); + console.log(` ${c.dim("Output:")} ${terminalText(progress.outputFile.s3Uri)}`); console.log(` ${c.dim("Size:")} ${progress.outputFile.bytes ?? "?"} bytes`); console.log(` ${c.dim("Total cost:")} ${progress.costs.displayCost}`); } else { console.log(); - console.log(c.error(`Render ended with status ${progress.status}.`)); + console.log(c.error(`Render ended with status ${terminalText(progress.status)}.`)); for (const err of progress.errors) { - console.log(` ${c.dim(err.state)}: ${err.error} — ${err.cause}`); + console.log( + ` ${c.dim(terminalText(err.state))}: ${terminalLines(err.error)} — ${terminalLines(err.cause)}`, + ); } setCommandExitCode(1); } diff --git a/packages/cli/src/commands/lambda/sites.ts b/packages/cli/src/commands/lambda/sites.ts index d4042f8a0a..dcc5b42936 100644 --- a/packages/cli/src/commands/lambda/sites.ts +++ b/packages/cli/src/commands/lambda/sites.ts @@ -7,6 +7,7 @@ import { resolve as resolvePath } from "node:path"; import { c } from "../../ui/colors.js"; +import { terminalLines, terminalText } from "@hyperframes/core"; import { DEFAULT_STACK_NAME, requireStack } from "./state.js"; // `@hyperframes/aws-lambda` is a workspace devDependency in `packages/cli` @@ -40,7 +41,7 @@ export async function runSitesCreate(args: SitesCreateArgs): Promise { region: stack.region, siteId: args.siteId, includeOutsideFiles: args.includeOutsideFiles, - onNotice: (message) => console.error(c.dim(message)), + onNotice: (message) => console.error(c.dim(terminalLines(message))), }); if (args.json) { @@ -51,15 +52,17 @@ export async function runSitesCreate(args: SitesCreateArgs): Promise { console.log( c.success(handle.uploaded ? "Site uploaded." : "Site already up to date (skipped upload)."), ); - console.log(` ${c.dim("Site ID:")} ${handle.siteId}`); - console.log(` ${c.dim("S3 URI:")} ${handle.projectS3Uri}`); + console.log(` ${c.dim("Site ID:")} ${terminalText(handle.siteId)}`); + console.log(` ${c.dim("S3 URI:")} ${terminalText(handle.projectS3Uri)}`); console.log(` ${c.dim("Bytes:")} ${handle.bytes}`); - console.log(` ${c.dim("Uploaded at:")} ${handle.uploadedAt}`); + console.log(` ${c.dim("Uploaded at:")} ${terminalText(handle.uploadedAt)}`); console.log(); console.log( c.dim( - `Render with: hyperframes lambda render ${args.projectDir} --site-id=${handle.siteId}` + - (args.stackName === DEFAULT_STACK_NAME ? "" : ` --stack-name=${args.stackName}`), + terminalText( + `Render with: hyperframes lambda render ${args.projectDir} --site-id=${handle.siteId}` + + (args.stackName === DEFAULT_STACK_NAME ? "" : ` --stack-name=${args.stackName}`), + ), ), ); } diff --git a/packages/cli/src/commands/lambda/state.test.ts b/packages/cli/src/commands/lambda/state.test.ts index 6b27104bcc..f58d210b42 100644 --- a/packages/cli/src/commands/lambda/state.test.ts +++ b/packages/cli/src/commands/lambda/state.test.ts @@ -14,6 +14,10 @@ import { let workdir: string; +const ESC = String.fromCharCode(27); +const ODD = `od${ESC}[2Jd\x07`; +const SHOWN = "od\\x1b[2Jd\\x07"; + beforeEach(() => { workdir = mkdtempSync(join(tmpdir(), "hf-lambda-cli-state-")); }); @@ -148,4 +152,23 @@ describe("lambda state file", () => { rmSync(elsewhere, { recursive: true, force: true }); } }); + + // fails without the fix: the stack name read from the file is printed as it is stored. + it("requireStack shows control characters in the stack name a file records as text", () => { + plant("test", { ...sample, stackName: `ot${ODD}her` }); + const said = refusal("test"); + expect(said).toContain(`names stack "ot${SHOWN}her", not "test"`); + expect(said).not.toContain(ESC); + }); + + // fails without the fix: the file's path is printed as it is on disk. + it.skipIf(process.platform === "win32")( + "requireStack shows control characters in an unusable file's path as text", + () => { + plant(`te${ODD}st`, "not an object"); + const said = refusal(`te${ODD}st`); + expect(said).toContain(`te${SHOWN}st.json is not a JSON object`); + expect(said).not.toContain(ESC); + }, + ); }); diff --git a/packages/cli/src/commands/lambda/state.ts b/packages/cli/src/commands/lambda/state.ts index 3b68b282a8..c837c5ed11 100644 --- a/packages/cli/src/commands/lambda/state.ts +++ b/packages/cli/src/commands/lambda/state.ts @@ -1,4 +1,5 @@ import { failCommand } from "../../utils/commandResult.js"; +import { terminalText } from "@hyperframes/core"; /** * Persists `hyperframes lambda` stack outputs (bucket, state-machine ARN, * region) so `render` / `progress` / `destroy` don't need to re-derive @@ -154,20 +155,24 @@ export function requireStack(stackName: string, cwd: string = process.cwd()): St const path = stateFilePath(stackName, cwd); const deploy = `Run \`hyperframes lambda deploy${stackName === DEFAULT_STACK_NAME ? "" : ` --stack-name=${stackName}`}\``; if (typeof stack === "string") { - console.error(`[hyperframes lambda] ${path} ${stack}. ${deploy} to rewrite it.`); + console.error(terminalText(`[hyperframes lambda] ${path} ${stack}. ${deploy} to rewrite it.`)); failCommand(); } if (!stack) { const known = listStackNames(cwd); const hint = known.length ? ` Known stacks here: ${known.join(", ")}.` : ""; console.error( - `[hyperframes lambda] no stack state for "${stackName}" at ${path}. ${deploy} first.${hint}`, + terminalText( + `[hyperframes lambda] no stack state for "${stackName}" at ${path}. ${deploy} first.${hint}`, + ), ); failCommand(); } if (!sameFileOnCaseInsensitiveDisk(String(stack.stackName), stackName)) { console.error( - `[hyperframes lambda] ${path} names stack "${stack.stackName}", not "${stackName}". ${deploy} to rewrite it.`, + terminalText( + `[hyperframes lambda] ${path} names stack "${stack.stackName}", not "${stackName}". ${deploy} to rewrite it.`, + ), ); failCommand(); }