feat(cli): add hyperframes cloud render/list/get/delete commands (#1110)

* feat(cli): vendor initial hyperframes cloud client codegen

Generated by experiment-framework/scripts/generate_hyperframes_cli_client.py
(see heygen-com/experiment-framework#37896). Sets up the baseline for the
sync workflow to diff against on future spec changes.

The follow-up PR adds the orchestration layer (zip + upload + poll +
download) and the user-facing 'hyperframes cloud render/list/get/delete'
commands on top of this generated client.

The fallow ignore pattern is necessary because the generated request()
method is intentionally a single switch that handles all 5 endpoints
in one place; refactoring it here would just be re-introduced on the
next codegen run.

* chore(cli): regenerate cloud client with mimeType parameter on multipart uploads

Adds optional mimeType arg to uploadAsset (and any future multipart
endpoints). Without it, FormData sends application/octet-stream which
is correct for the documented media surface (png/jpeg/mp4/etc.) but
ambiguous for the private-beta zip uploads the cloud render flow uses.
Callers that pass `mimeType: "application/zip"` tag the multipart
part with the right Content-Type so downstream proxies, WAFs, and any
future server-side change that keys off the part MIME (instead of the
current magic-byte detection) all see the intended type.

Addresses review feedback on heygen-com/experiment-framework#37896.
Generated by scripts/generate_hyperframes_cli_client.py with the
matching update to the multipart emit path.

* feat(cli): add hyperframes cloud render/list/get/delete commands

Hand-rolled orchestration layer on top of the auto-generated cloud
client (vendored in the previous PR):

- cloud render <dir>: zip via createPublishArchive → upload to
  /v3/assets → submit /v3/hyperframes/renders → poll
  /v3/hyperframes/renders/{id} every 10s (max 60min) → stream the
  signed video_url to disk.
- cloud render --no-wait: submit and exit with the render_id.
- cloud render --asset-id / --url: skip zip+upload and use a
  pre-uploaded asset or public HTTPS zip.
- cloud render --variables / --variables-file: same UX as the local
  render command; variables are validated against
  data-composition-variables only when there's a local project.
- cloud list / cloud get / cloud delete: thin wrappers around the
  matching client methods, with cursor-pagination support on list.

Auth comes from the existing cli/src/auth/ chain via cloud/auth.ts —
no new credential store, no new env var. The cloud client receives a
getAuthHeaders() callback that re-resolves credentials on every
request, so OAuth refreshes mid-poll are picked up automatically.

Also extracts a parent-scoped path lookup in help.ts so 'cloud render
--help' surfaces the right examples instead of falling through to the
top-level 'render' command's examples.

* fix(cli): address 15 code-review findings on cloud commands

Correctness fixes
- delete: require --no-confirm when stdin isn't a TTY OR --json is
  passed; previously both silently auto-bypassed the irreversible-
  delete prompt. Explicit decline now exits 2 (distinct from API/system
  errors which still exit 1).
- render: mutex check now counts the positional dir alongside
  --asset-id / --url; `cloud render ./foo --asset-id X` now errors
  instead of silently dropping the dir.
- render: docstring updated — only --no-wait short-circuits the poll
  loop; --callback-url is independent (webhook fires either way).
- render: removed dead try/catch around resolveProject (it calls
  process.exit, never throws). resolveVariablesAndValidateIfLocal also
  takes the resolved project source instead of re-parsing args.
- render: createPublishArchive errors now surface via errorBox instead
  of bubbling a raw stack trace past citty.
- help: loadExamples now only catches ERR_MODULE_NOT_FOUND; real load
  errors (syntax error, broken import) propagate so a broken
  cloud/render.ts no longer silently shows the local render command's
  examples. Also skips the parent-scoped lookup when parentName is the
  root command ("hyperframes").
- list: fetchAll gained a 50-page safety cap + duplicate-cursor
  detection so a buggy backend serving the same next_token on a loop
  can't OOM the CLI.
- download: drain await now listens for error / close / abort so a
  failing write stream (ENOSPC, AbortSignal) rejects promptly instead
  of hanging forever. Partial files are unlinked on any error so the
  caller never observes a truncated MP4. content-length is verified
  against the actual byte count.
- poll: default sleep is abort-aware so Ctrl+C feels immediate instead
  of waiting out the full interval.
- pollWithProgress: ANSI carriage-return redraws now gated on
  process.stdout.isTTY — non-TTY runs (CI, file redirects) emit one
  line per status transition instead of polluting the log with
  literal escape codes.

Cloud client: 401-retry-with-refresh
- createCloudClient now wraps the generated client with a Proxy that
  catches HyperframesApiError(status=401), force-refreshes the OAuth
  token via forceRefreshCredentials, and retries the call exactly
  once. Mirrors AuthClient's onUnauthenticatedRefresh so server-side
  revocations and clock-skew rejections recover automatically.
- auth.ts gained forceRefreshCredentials() and now updates expires_at
  on the refreshed credential it returns (fixed stale-expiry race).

Shared helpers
- cloud/errors.ts: reportApiError(stage, err, opts) is the single
  error-funnel. ERROR_CODE_HINTS now applies to every subverb — fixes
  hyperframes_render_not_found being unreachable from get/delete and
  cuts ~70 LOC of duplicated try/catch/instanceof from render/list/
  get/delete.
- cloud/parsing.ts: parseIntFlag / parseNumericFlag / parseEnumFlag
  strict-mode parsers reject trailing garbage that Number.parseInt
  silently accepts.
- cloud/ansi.ts: stripAnsi / visibleLength / padEndVisible — covers
  ESC + 24-bit truecolor (c.accent palette) instead of the previous
  regex which undercounted overhead and missed truecolor.

JSON-output consistency + _meta envelope
- Every cloud subverb's --json output now goes through withMeta(...)
  so it carries the standard _meta envelope documented in cli.mdx.
- Single-render outputs use {render: detail} across get, delete,
  render-no-wait, render-failed, and render-success. list uses
  {renders: [...], has_more, next_token?}. delete adds deleted: true.

Tests
- 25 new tests across ansi.test.ts, parsing.test.ts, plus truncation
  + abort-cleanup tests for download.test.ts.
- 589 / 589 total CLI tests pass.

* fix(cli): address Vai's review on cloud commands

- render: pass mimeType: "application/zip" to uploadAsset so the
  multipart Content-Type is correct (was application/octet-stream).
  Server currently magic-byte-detects from file bytes so this is
  belt-and-suspenders today, but any downstream proxy / WAF / future
  server change that keys off the part MIME now sees the intended
  type instead of relying on detection.
- render: poll error path now surfaces "Resume with: hyperframes
  cloud get <renderId>" via reportApiError's new `suggestion`
  option, matching the PollTimeoutError handler. The server-side
  render keeps running through a transient 5xx; the user just
  needs the right command to pick it back up.
- list: fetchAll now errorBox-exits on the malformed
  {has_more: true, next_token: null} shape instead of silently
  returning a truncated list (matching the duplicate-cursor guard).
- download: closeFile now listens for 'error' on the write stream
  in addition to the end() callback, so a late ENOSPC during flush
  doesn't leak an unhandled error onto the stream and resolves the
  finally promptly.
- errors: reportApiError accepts an optional `suggestion` that's
  used as the errorBox third line when no code-specific hint
  matches — gives callers a place to surface always-actionable
  recovery context.
- docs(cli): document --idempotency-key as the safe-retry mechanism
  for the upload step. The 401-retry Proxy replays POST requests
  on a stale token; without an idempotency key, the upload may
  land twice. A UUID per logical render is the recommended pattern.
This commit is contained in:
James Russo
2026-05-28 14:10:05 -04:00
committed by GitHub
parent e9f45b7c33
commit ce5e872e51
20 changed files with 2148 additions and 6 deletions
+87
View File
@@ -0,0 +1,87 @@
/**
* `hyperframes cloud delete <render_id>` — soft-delete a cloud render.
*
* Subsequent GET calls return 404. The signed video URL stops working
* shortly after. There's no undo from the CLI side.
*/
import { defineCommand } from "citty";
import { createCloudClient } from "../../cloud/index.js";
import { reportApiError } from "../../cloud/errors.js";
import { withMeta } from "../../utils/updateCheck.js";
import { c } from "../../ui/colors.js";
import { errorBox } from "../../ui/format.js";
export default defineCommand({
meta: { name: "delete", description: "Soft-delete a cloud render" },
args: {
id: {
type: "positional",
required: true,
description: "Render ID to delete",
},
json: {
type: "boolean",
description: "Emit machine-readable JSON",
default: false,
},
"no-confirm": {
type: "boolean",
description: "Skip the interactive confirmation prompt (required for scripts and --json)",
default: false,
},
},
// fallow-ignore-next-line complexity
async run({ args }) {
if (!args["no-confirm"]) {
// Don't auto-bypass the prompt just because stdin isn't a TTY
// or `--json` was passed — both used to silently skip the
// safety check. Force the caller to opt in via `--no-confirm`
// so cron jobs, CI shells, and JSON consumers can't soft-delete
// by accident.
if (args.json || !process.stdin.isTTY) {
errorBox(
"Confirmation required",
"delete cannot prompt for confirmation here — stdin isn't a TTY or --json was passed.",
"Re-run with --no-confirm to acknowledge the irreversible delete.",
);
process.exit(1);
}
const ok = await confirmDelete(args.id);
if (!ok) {
// Distinct exit code so wrapper scripts can tell an explicit
// decline apart from an API/system error.
console.log(c.dim("Aborted."));
process.exit(2);
}
}
const client = await createCloudClient();
try {
const response = await client.deleteRender({ render_id: args.id });
if (args.json) {
console.log(
JSON.stringify(
withMeta({ render: { render_id: response.render_id }, deleted: true }),
null,
2,
),
);
return;
}
console.log(`${c.success("✓")} Deleted ${c.accent(response.render_id)}`);
} catch (err) {
reportApiError("Could not delete render", err, {
notFound: `No render found with id "${args.id}".`,
});
}
},
});
async function confirmDelete(id: string): Promise<boolean> {
const clack = await import("@clack/prompts");
const answer = await clack.confirm({
message: `Delete render ${id}? This is irreversible.`,
initialValue: false,
});
return answer === true;
}
+86
View File
@@ -0,0 +1,86 @@
/**
* `hyperframes cloud get <render_id>` — fetch detail for a single render.
*
* Includes the signed `video_url` and `thumbnail_url` when status is
* `completed`. The signed URLs are short-lived; don't paste them into
* docs / chat — fetch them on demand.
*/
import { defineCommand } from "citty";
import { createCloudClient } from "../../cloud/index.js";
import { reportApiError } from "../../cloud/errors.js";
import { colorStatus } from "../../cloud/statusColor.js";
import { withMeta } from "../../utils/updateCheck.js";
import type { HyperframesRenderDetail } from "../../cloud/index.js";
import { c } from "../../ui/colors.js";
export default defineCommand({
meta: { name: "get", description: "Fetch detail for one cloud render" },
args: {
id: {
type: "positional",
required: true,
description: "Render ID (returned by `cloud render` / `cloud list`)",
},
json: {
type: "boolean",
description: "Emit machine-readable JSON",
default: false,
},
},
async run({ args }) {
const client = await createCloudClient();
try {
const detail = await client.getRender({ render_id: args.id });
if (args.json) {
console.log(JSON.stringify(withMeta({ render: detail }), null, 2));
return;
}
printHuman(detail);
} catch (err) {
reportApiError("Could not fetch render", err, {
notFound: `No render found with id "${args.id}".`,
});
}
},
});
// fallow-ignore-next-line complexity
function printHuman(detail: HyperframesRenderDetail): void {
const rows: [string, string | undefined][] = [
["Render ID:", c.accent(detail.render_id)],
["Status: ", colorStatus(detail.status)],
["Format: ", detail.format],
["Quality: ", detail.quality ?? undefined],
["Fps: ", detail.fps?.toString()],
["Resolution:", detail.resolution ?? undefined],
["Composition:", detail.composition ?? undefined],
["Title: ", detail.title ?? undefined],
["Callback ID:", detail.callback_id ?? undefined],
[
"Duration: ",
detail.duration !== undefined && detail.duration !== null
? `${detail.duration.toFixed(2)}s`
: undefined,
],
[
"Created: ",
detail.created_at !== undefined && detail.created_at !== null
? new Date(detail.created_at * 1000).toISOString()
: undefined,
],
[
"Completed:",
detail.completed_at !== undefined && detail.completed_at !== null
? new Date(detail.completed_at * 1000).toISOString()
: undefined,
],
["Video URL:", detail.video_url ?? undefined],
["Thumbnail:", detail.thumbnail_url ?? undefined],
["Failure: ", detail.failure_message ?? undefined],
];
for (const [label, value] of rows) {
if (value === undefined) continue;
console.log(`${c.bold(label)} ${value}`);
}
}
+144
View File
@@ -0,0 +1,144 @@
/**
* `hyperframes cloud list` — page through GET /v3/hyperframes/renders.
*
* Cursor pagination: `--limit` caps a single page (max 100 per the
* spec), `--all` walks `next_token` until exhausted. Default page size
* mirrors the API default (10).
*/
import { defineCommand } from "citty";
import { createCloudClient } from "../../cloud/index.js";
import { padEndVisible } from "../../cloud/ansi.js";
import { reportApiError } from "../../cloud/errors.js";
import { parseIntFlag } from "../../cloud/parsing.js";
import { colorStatus } from "../../cloud/statusColor.js";
import { withMeta } from "../../utils/updateCheck.js";
import type { HyperframesRenderDetail } from "../../cloud/index.js";
import { c } from "../../ui/colors.js";
import { errorBox } from "../../ui/format.js";
// Safety cap on --all to defend against a buggy backend serving the
// same next_token in a loop. 50 pages at the maximum page size of 100
// covers 5,000 renders — well past anyone's expected list size.
const MAX_ALL_PAGES = 50;
export default defineCommand({
meta: { name: "list", description: "List recent cloud renders" },
args: {
limit: {
type: "string",
description: "Items per page (1-100; default 10)",
},
token: {
type: "string",
description: "Resume from a previous next_token cursor",
},
all: {
type: "boolean",
description: "Fetch every page (follows next_token until exhausted)",
default: false,
},
json: {
type: "boolean",
description: "Emit machine-readable JSON",
default: false,
},
},
// fallow-ignore-next-line complexity
async run({ args }) {
const limit = parseIntFlag(args.limit, { flag: "--limit", min: 1, max: 100 });
const client = await createCloudClient();
try {
if (args.all) {
const renders = await fetchAll(client, limit);
emit(renders, args.json, null, false);
} else {
const page = await client.listRenders({ limit, token: args.token });
emit(page.data ?? [], args.json, page.next_token ?? null, Boolean(page.has_more));
}
} catch (err) {
reportApiError("Could not list cloud renders", err);
}
},
});
// fallow-ignore-next-line complexity
async function fetchAll(
client: Awaited<ReturnType<typeof createCloudClient>>,
pageSize: number | undefined,
): Promise<HyperframesRenderDetail[]> {
const out: HyperframesRenderDetail[] = [];
const seenCursors = new Set<string>();
let token: string | undefined;
for (let page = 0; page < MAX_ALL_PAGES; page++) {
const result = await client.listRenders({ limit: pageSize, token });
out.push(...(result.data ?? []));
if (!result.has_more) return out;
// Defensive: server said `has_more: true` but didn't hand us a
// cursor to use. Better to surface the malformed shape than
// return a silently-truncated list.
if (!result.next_token) {
errorBox(
"Pagination cursor missing",
"Server returned has_more: true with no next_token — incomplete response.",
"Retry the command, or report this if it persists.",
);
process.exit(1);
}
if (seenCursors.has(result.next_token)) {
errorBox(
"Pagination loop detected",
`Server returned the same next_token (${result.next_token}) twice.`,
"Retry the command, or report this if it persists.",
);
process.exit(1);
}
seenCursors.add(result.next_token);
token = result.next_token;
}
errorBox(
"Pagination cap reached",
`Stopped after ${MAX_ALL_PAGES} pages to avoid an unbounded loop.`,
`Re-run with a higher --limit, or paginate manually with --token.`,
);
process.exit(1);
}
// fallow-ignore-next-line complexity
function emit(
renders: HyperframesRenderDetail[],
asJson: boolean,
nextToken: string | null,
hasMore: boolean,
): void {
if (asJson) {
const payload: Record<string, unknown> = { renders, has_more: hasMore };
if (nextToken !== null) payload["next_token"] = nextToken;
console.log(JSON.stringify(withMeta(payload), null, 2));
return;
}
if (renders.length === 0) {
console.log(c.dim("No renders found."));
return;
}
const idWidth = Math.max(8, ...renders.map((r) => r.render_id.length));
const statusWidth = Math.max(6, ...renders.map((r) => r.status.length));
for (const r of renders) {
const id = c.accent(r.render_id);
const status = colorStatus(r.status);
const created =
r.created_at !== undefined && r.created_at !== null
? new Date(r.created_at * 1000).toISOString()
: "—";
const title = r.title ? ` ${c.dim(r.title)}` : "";
console.log(
`${padEndVisible(id, idWidth)} ${padEndVisible(status, statusWidth)} ${c.dim(created)}${title}`,
);
}
if (nextToken) {
console.log("");
console.log(c.dim(`More results — pass --token ${nextToken} to continue.`));
}
}
+587
View File
@@ -0,0 +1,587 @@
/**
* `hyperframes cloud render` — orchestrate a cloud-rendered HyperFrames
* composition end-to-end:
*
* 1. Resolve the project (or reuse a pre-uploaded `--asset-id` /
* `--url`).
* 2. Zip the project (reuses `createPublishArchive` so the
* file-ignore set matches the existing `publish` command exactly).
* 3. Upload the zip via `POST /v3/assets` (multipart) — the server
* branches on the detected `application/zip` MIME.
* 4. Submit the render via `POST /v3/hyperframes/renders` with a
* `project: {type:"asset_id", asset_id}` shape.
* 5. If `--no-wait`: print the `render_id` and exit immediately.
* Otherwise poll `GET /v3/hyperframes/renders/{id}` every
* `--poll-interval` (default 10s, max 60min). `--callback-url`
* can be combined with either mode: the webhook always fires when
* the server-side render terminates, independent of whether the
* CLI is still polling.
* 6. On `completed`: stream the signed `video_url` to disk.
* 7. On `failed`: print `failure_message` and exit 1.
*
* Auth comes from the existing `cli/src/auth/` chain via `cloud/auth.ts`.
* The cloud HTTP client (`cloud/_gen/client.ts`) is generated from
* `experiment-framework/openapi/external-api.json`; never hand-edit it.
*/
import { defineCommand } from "citty";
import { c } from "../../ui/colors.js";
import { errorBox, formatBytes, formatDuration } from "../../ui/format.js";
import { resolveProject } from "../../utils/project.js";
import { createPublishArchive } from "../../utils/publishProject.js";
import {
reportVariableIssues,
resolveVariablesArg,
validateVariablesAgainstProject,
} from "../../utils/variables.js";
import { withMeta } from "../../utils/updateCheck.js";
import type { Example } from "../_examples.js";
import {
DEFAULT_MAX_WAIT_MS,
DEFAULT_POLL_INTERVAL_MS,
PollTimeoutError,
createCloudClient,
downloadToFile,
pollUntilTerminal,
} from "../../cloud/index.js";
import { reportApiError } from "../../cloud/errors.js";
import { parseEnumFlag, parseIntFlag, parseNumericFlag } from "../../cloud/parsing.js";
import { colorStatus } from "../../cloud/statusColor.js";
import type {
CreateHyperframesRenderRequest,
HyperframesCloudClient,
HyperframesRenderDetail,
} from "../../cloud/index.js";
import { isAbsolute, resolve as resolvePath } from "node:path";
const VALID_QUALITY = ["draft", "standard", "high"] as const;
const VALID_FORMAT = ["mp4", "webm", "mov"] as const;
const VALID_RESOLUTION = [
"landscape",
"portrait",
"landscape-4k",
"portrait-4k",
"square",
"square-4k",
] as const;
const FORMAT_EXT: Record<string, string> = { mp4: ".mp4", webm: ".webm", mov: ".mov" };
export const examples: Example[] = [
["Render the current directory in the cloud", "hyperframes cloud render"],
[
"Pick a specific composition + output path",
"hyperframes cloud render . --composition compositions/intro.html -o ./renders/intro.mp4",
],
["Higher quality, 60fps", "hyperframes cloud render --quality high --fps 60"],
[
"Submit and exit; webhook fires when the render terminates",
"hyperframes cloud render --callback-url https://example.com/hook --no-wait",
],
[
"Override variables (parametrized render)",
'hyperframes cloud render --variables \'{"title":"Q4 Recap","theme":"dark"}\'',
],
["Re-render an already-uploaded zip", "hyperframes cloud render --asset-id asst_abc123"],
];
export default defineCommand({
meta: { name: "render", description: "Render a HyperFrames composition in the cloud" },
args: {
dir: { type: "positional", required: false, description: "Project directory (default: .)" },
fps: { type: "string", description: "Frames per second (1-240). Default: 30." },
quality: { type: "string", description: "draft | standard | high (default: standard)" },
format: { type: "string", description: "mp4 | webm | mov (default: mp4)" },
resolution: {
type: "string",
description:
"Resolution preset: landscape | portrait | landscape-4k | portrait-4k | square | square-4k",
},
composition: {
type: "string",
alias: "c",
description: "Entry HTML file inside the zip (default: index.html)",
},
variables: {
type: "string",
description:
'Inline JSON object overriding data-composition-variables. Example: --variables \'{"title":"X"}\'',
},
"variables-file": {
type: "string",
description: "Path to a JSON file with variable values (alternative to --variables)",
},
"strict-variables": {
type: "boolean",
description: "Fail when --variables keys are undeclared or have the wrong type",
default: false,
},
title: {
type: "string",
description: "Free-text label echoed back in detail responses",
},
"callback-url": {
type: "string",
description:
"HTTPS webhook fired when the render terminates. Fires regardless of whether the CLI is still polling — combine with --no-wait for true fire-and-forget.",
},
"callback-id": {
type: "string",
description: "Opaque tracking ID echoed in webhook payloads",
},
"asset-id": {
type: "string",
description:
"Skip zip+upload and submit an already-uploaded composition. Mutually exclusive with --url and the project dir.",
},
url: {
type: "string",
description:
"Public HTTPS URL of a composition zip. Mutually exclusive with --asset-id and the project dir.",
},
"no-wait": {
type: "boolean",
description: "Submit and exit; print the render_id to stdout",
default: false,
},
output: {
type: "string",
alias: "o",
description: "Destination path for the downloaded video (default: renders/<render_id>.<ext>)",
},
"poll-interval": {
type: "string",
description: `Poll cadence in seconds (default: ${DEFAULT_POLL_INTERVAL_MS / 1000})`,
},
"max-wait": {
type: "string",
description: `Max poll duration in minutes (default: ${DEFAULT_MAX_WAIT_MS / 60_000})`,
},
json: {
type: "boolean",
description: "Emit machine-readable JSON instead of human-friendly progress",
default: false,
},
"idempotency-key": {
type: "string",
description: "Optional Idempotency-Key for safe retries (1-255 chars from [A-Za-z0-9_:.-])",
},
},
// fallow-ignore-next-line complexity
async run({ args }) {
const asJson = Boolean(args.json);
const fps = parseIntFlag(args.fps, { flag: "--fps", min: 1, max: 240 });
const quality = parseEnumFlag(args.quality, VALID_QUALITY, { flag: "--quality" });
const format = parseEnumFlag(args.format, VALID_FORMAT, { flag: "--format" });
const resolution = parseEnumFlag(args.resolution, VALID_RESOLUTION, {
flag: "--resolution",
});
const pollIntervalMs = parsePollIntervalMs(args["poll-interval"]);
const maxWaitMs = parseMaxWaitMs(args["max-wait"]);
validateIdempotencyKey(args["idempotency-key"]);
// Project resolution runs BEFORE variables resolution so a user
// passing conflicting inputs (`dir + --asset-id`) sees the
// structural error before any variable parsing errors.
const project = resolveProjectInput({
dir: args.dir,
assetId: args["asset-id"],
url: args.url,
});
const variables = resolveVariablesAndValidateIfLocal(
args.variables,
args["variables-file"],
args["strict-variables"] ?? false,
project,
);
const client = await createCloudClient();
const upload = await maybeUploadProject(client, project, asJson, args["idempotency-key"]);
const submitted = await submitRender(client, {
projectInput: upload.projectInput,
fps,
quality,
format,
resolution,
composition: args.composition,
variables,
title: args.title,
callbackUrl: args["callback-url"],
callbackId: args["callback-id"],
idempotencyKey: args["idempotency-key"],
});
const renderId = submitted.render_id;
if (args["no-wait"]) {
if (asJson) {
console.log(
JSON.stringify(
withMeta({ render: { render_id: renderId, status: "queued" as const } }),
null,
2,
),
);
} else {
console.log("");
console.log(`${c.success("✓")} Submitted ${c.accent(renderId)}`);
console.log(c.dim(` Poll with: hyperframes cloud get ${renderId}`));
}
return;
}
if (!asJson) {
console.log("");
console.log(c.dim(` Polling ${renderId} every ${pollIntervalMs / 1000}s …`));
}
const detail = await pollWithProgress(client, renderId, asJson, {
intervalMs: pollIntervalMs,
maxWaitMs,
});
if (detail.status === "failed") {
handleFailedRender(detail, asJson);
}
if (!detail.video_url) {
errorBox(
"Render completed but returned no video_url",
`render_id: ${renderId}. Try \`hyperframes cloud get ${renderId}\` to inspect raw fields.`,
);
process.exit(1);
}
const outputPath = resolveOutputPath(args.output, renderId, detail.format);
const downloadResult = await streamVideo(detail.video_url, outputPath, asJson);
if (asJson) {
console.log(
JSON.stringify(
withMeta({
render: detail,
output_path: outputPath,
bytes_written: downloadResult.bytes,
}),
null,
2,
),
);
}
},
});
// ---------------------------------------------------------------------------
// Argument parsing — defers to cloud/parsing.ts for strict validators
// ---------------------------------------------------------------------------
function parsePollIntervalMs(raw: string | undefined): number {
const n = parseNumericFlag(raw, { flag: "--poll-interval", min: 1 });
return n === undefined ? DEFAULT_POLL_INTERVAL_MS : Math.round(n * 1000);
}
function parseMaxWaitMs(raw: string | undefined): number {
const n = parseNumericFlag(raw, { flag: "--max-wait", min: 0.0001 });
return n === undefined ? DEFAULT_MAX_WAIT_MS : Math.round(n * 60_000);
}
const IDEMPOTENCY_KEY_RE = /^[A-Za-z0-9_:.-]{1,255}$/;
function validateIdempotencyKey(key: string | undefined): void {
if (key === undefined) return;
if (!IDEMPOTENCY_KEY_RE.test(key)) {
errorBox("Invalid --idempotency-key", `Got "${key}". Must be 1-255 chars from [A-Za-z0-9_:.-]`);
process.exit(1);
}
}
// ---------------------------------------------------------------------------
// Project resolution (dir | asset-id | url) — exactly one source
// ---------------------------------------------------------------------------
interface ProjectInputSource {
kind: "dir" | "asset_id" | "url";
dir?: string;
assetId?: string;
url?: string;
}
// fallow-ignore-next-line complexity
function resolveProjectInput(opts: {
dir: string | undefined;
assetId: string | undefined;
url: string | undefined;
}): ProjectInputSource {
// Count every source the user explicitly supplied. The positional
// `dir` defaults to `undefined` when omitted (not to "."), so we
// can detect "user actually typed something" vs. "default to cwd".
const explicit = {
dir: opts.dir !== undefined && opts.dir !== "",
assetId: opts.assetId !== undefined && opts.assetId !== "",
url: opts.url !== undefined && opts.url !== "",
};
const count = Number(explicit.dir) + Number(explicit.assetId) + Number(explicit.url);
if (count > 1) {
errorBox("Conflicting inputs", "Pass only one of: project dir, --asset-id, --url.");
process.exit(1);
}
if (explicit.assetId) return { kind: "asset_id", assetId: opts.assetId };
if (explicit.url) return { kind: "url", url: opts.url };
return { kind: "dir", dir: opts.dir ?? "." };
}
function resolveVariablesAndValidateIfLocal(
inline: string | undefined,
filePath: string | undefined,
strict: boolean,
source: ProjectInputSource,
): Record<string, unknown> | undefined {
const variables = resolveVariablesArg(inline, filePath);
if (!variables || Object.keys(variables).length === 0) return variables;
// Only validate against the local composition when we actually have
// a local project on disk. For --asset-id / --url paths the schema
// lives on the server side, so we send the variables as-is and let
// the API surface any mismatch via `hyperframes_project_invalid`.
if (source.kind !== "dir") return variables;
// `resolveProject` calls process.exit on a missing/invalid dir, so
// there's no need to wrap this in try/catch — if it returns, the
// index.html is present. The earlier impl had a dead try/catch.
const { indexPath } = resolveProject(source.dir);
const issues = validateVariablesAgainstProject(indexPath, variables);
reportVariableIssues(issues, { strict, quiet: false });
return variables;
}
// ---------------------------------------------------------------------------
// Upload step (only when project is a local dir)
// ---------------------------------------------------------------------------
interface UploadResult {
projectInput: CreateHyperframesRenderRequest["project"];
}
// fallow-ignore-next-line complexity
async function maybeUploadProject(
client: HyperframesCloudClient,
source: ProjectInputSource,
asJson: boolean,
idempotencyKey: string | undefined,
): Promise<UploadResult> {
if (source.kind === "asset_id") {
return { projectInput: { type: "asset_id", asset_id: source.assetId! } };
}
if (source.kind === "url") {
return { projectInput: { type: "url", url: source.url! } };
}
const project = resolveProject(source.dir);
if (!asJson) {
console.log("");
console.log(`${c.accent("◆")} Zipping ${c.accent(project.name)}`);
}
let archive;
try {
archive = createPublishArchive(project.dir);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
errorBox("Zip failed", msg, "Check the project for missing files or unreadable permissions.");
process.exit(1);
}
if (!asJson) {
console.log(c.dim(` ${archive.fileCount} files · ${formatBytes(archive.buffer.byteLength)}`));
}
if (!asJson) {
console.log("");
console.log(`${c.accent("◆")} Uploading to /v3/assets`);
}
const uploadStart = Date.now();
let uploaded;
try {
uploaded = await client.uploadAsset({
file: archive.buffer,
filename: `${project.name}.zip`,
// Tag the multipart part with application/zip so downstream
// proxies / WAFs / any server-side path that keys off the
// part Content-Type see the intended type. The asset
// controller currently sniffs magic bytes from the file
// bytes, so this is belt-and-suspenders today; without it,
// FormData defaults to application/octet-stream.
mimeType: "application/zip",
idempotencyKey,
});
} catch (err) {
reportApiError("Upload failed", err);
}
if (!asJson) {
console.log(
c.dim(
` asset_id: ${c.accent(uploaded.asset_id)} · ${formatDuration(Date.now() - uploadStart)}`,
),
);
}
return { projectInput: { type: "asset_id", asset_id: uploaded.asset_id } };
}
// ---------------------------------------------------------------------------
// Submit step
// ---------------------------------------------------------------------------
interface SubmitOptions {
projectInput: CreateHyperframesRenderRequest["project"];
fps: number | undefined;
quality: "draft" | "standard" | "high" | undefined;
format: "mp4" | "webm" | "mov" | undefined;
resolution: CreateHyperframesRenderRequest["resolution"] | undefined;
composition: string | undefined;
variables: Record<string, unknown> | undefined;
title: string | undefined;
callbackUrl: string | undefined;
callbackId: string | undefined;
idempotencyKey: string | undefined;
}
async function submitRender(
client: HyperframesCloudClient,
opts: SubmitOptions,
): Promise<{ render_id: string }> {
const body = buildRenderBody(opts);
try {
return await client.createRender({ body, idempotencyKey: opts.idempotencyKey });
} catch (err) {
reportApiError("Submit failed", err);
}
}
// fallow-ignore-next-line complexity
function buildRenderBody(opts: SubmitOptions): CreateHyperframesRenderRequest {
const body: CreateHyperframesRenderRequest = { project: opts.projectInput };
if (opts.fps !== undefined) body.fps = opts.fps;
if (opts.quality !== undefined) body.quality = opts.quality;
if (opts.format !== undefined) body.format = opts.format;
if (opts.resolution !== undefined) body.resolution = opts.resolution;
if (opts.composition !== undefined) body.composition = opts.composition;
if (opts.variables !== undefined) body.variables = opts.variables;
if (opts.title !== undefined) body.title = opts.title;
if (opts.callbackUrl !== undefined) body.callback_url = opts.callbackUrl;
if (opts.callbackId !== undefined) body.callback_id = opts.callbackId;
return body;
}
// ---------------------------------------------------------------------------
// Poll + progress
// ---------------------------------------------------------------------------
// fallow-ignore-next-line complexity
async function pollWithProgress(
client: HyperframesCloudClient,
renderId: string,
asJson: boolean,
poll: { intervalMs: number; maxWaitMs: number },
): Promise<HyperframesRenderDetail> {
// ANSI carriage-return redraws only make sense on a TTY. CI logs and
// file redirects get one append per status change instead, and JSON
// mode stays silent altogether.
const interactive = !asJson && process.stdout.isTTY === true;
let lastStatus = "";
try {
return await pollUntilTerminal(client, renderId, {
intervalMs: poll.intervalMs,
maxWaitMs: poll.maxWaitMs,
// fallow-ignore-next-line complexity
onTick: (detail, elapsedMs) => {
if (asJson) return;
if (interactive) {
if (detail.status === lastStatus) {
process.stdout.write(`\r\x1b[2K ${formatTickLine(detail, elapsedMs)}`);
} else {
if (lastStatus) process.stdout.write("\n");
process.stdout.write(` ${formatTickLine(detail, elapsedMs)}`);
lastStatus = detail.status;
}
} else if (detail.status !== lastStatus) {
// Non-TTY: one line per status transition, no carriage returns.
console.log(` ${formatTickLine(detail, elapsedMs)}`);
lastStatus = detail.status;
}
},
});
} catch (err) {
if (!asJson && lastStatus && interactive) process.stdout.write("\n");
if (err instanceof PollTimeoutError) {
errorBox(
"Poll timed out",
err.message,
`The render may still complete. Resume with: hyperframes cloud get ${renderId}`,
);
process.exit(1);
}
return reportApiError("API error during poll", err, {
suggestion: `The render may still be running. Resume with: hyperframes cloud get ${renderId}`,
});
} finally {
if (!asJson && lastStatus && interactive) process.stdout.write("\n");
}
}
function formatTickLine(detail: HyperframesRenderDetail, elapsedMs: number): string {
const status = colorStatus(detail.status);
return `${status} ${c.dim(formatDuration(elapsedMs))}`;
}
// ---------------------------------------------------------------------------
// Terminal handlers
// ---------------------------------------------------------------------------
function handleFailedRender(detail: HyperframesRenderDetail, asJson: boolean): never {
if (asJson) {
console.log(JSON.stringify(withMeta({ render: detail }), null, 2));
process.exit(1);
}
errorBox(
"Render failed",
detail.failure_message ?? "(no failure_message returned)",
`Inspect: hyperframes cloud get ${detail.render_id}`,
);
process.exit(1);
}
function resolveOutputPath(output: string | undefined, renderId: string, format: string): string {
if (output) {
return isAbsolute(output) ? output : resolvePath(process.cwd(), output);
}
const ext = FORMAT_EXT[format] ?? `.${format}`;
return resolvePath(process.cwd(), "renders", `${renderId}${ext}`);
}
// fallow-ignore-next-line complexity
async function streamVideo(
url: string,
destPath: string,
asJson: boolean,
): Promise<{ bytes: number }> {
// `downloadToFile` already creates the parent directory and cleans
// up the partial file on error — no pre-mkdir needed here.
if (!asJson) {
console.log("");
console.log(`${c.accent("◆")} Downloading to ${c.accent(destPath)}`);
}
try {
const result = await downloadToFile(url, destPath);
if (!asJson) {
console.log(c.dim(` ${formatBytes(result.bytes)} written`));
}
return { bytes: result.bytes };
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
errorBox(
"Download failed",
message,
"The presigned URL is short-lived; re-fetch with `hyperframes cloud get`.",
);
process.exit(1);
}
}