mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-23 11:29:54 +00:00
* fix(cli): project folder names print control characters as visible escapes check, info, compositions, benchmark, play, present and preview printed the project folder name, and in places the project path, straight to the terminal. A folder name can hold escape bytes on Linux and macOS, so a received project could move the cursor, rewrite earlier lines, set the window title or write the clipboard. Those lines now go through terminalText(), as validate, snapshot, layout and lint already do. This covers the preview summary, --status, --stop, --list and --kill-all lines, and the check report path. The CLI's own colours stay, and --json output is unchanged. The play page also HTML-escapes the name in its title and footer, as the present page does. * fix(cli): preview --selection and --context print Studio text as visible escapes The human output of preview --selection and --context printed the selected element's label, source file, target and thumbnail URL, and the preview server's project name, straight to the terminal. These come from the composition or from whichever preview server answers, so control characters in them could move the cursor, rewrite earlier lines, set the window title or write the clipboard. They now go through terminalText(), as do the failure messages these commands print. The CLI's own colours stay, and --json output is unchanged. * fix(cli): cloud get, list and delete print server fields as visible escapes The human output of cloud get printed render fields from the server, such as the failure message, title, composition and URLs, straight to the terminal. A failure message can quote text from the rendered project, so control characters in it could move the cursor, rewrite earlier lines, set the window title or write the clipboard. cloud get, cloud list (rows and the next-page token) and cloud delete now pass those fields through terminalText(). The CLI's own colours stay, and --json output is unchanged. * fix(inspector): the live inspection stamp gives the page only the generation id prepareLiveInspection wrote the project's absolute path into the preview page as window.__hfLiveInspection.project. Nothing in the page reads it, but any composition script on that page could, which told it the account name and folder layout. The page now gets only the generation id; the project path stays with the host that prepared the page. * fix(skills): locate.mjs keeps its grid font in a private per-run folder locate.mjs drew its grid labels with a font at the fixed shared path /tmp/locate-font.ttf. It used whatever file was already there and copied a system font onto that path otherwise, following any link in its place. On a machine shared with other accounts, someone else could plant that file first, so the grid showed wrong numbers, a file appeared where they chose, or every run failed. The font is now copied into a folder made with mkdtemp (mode 0700) for each run and removed when the run ends, so no file another account can create is read or written. The skills manifest hash is regenerated. * fix: escape the check report path and lint warnings, and harden locate.mjs font cleanup check's report path notice and its not-recorded warning, and preview's "Lint did not finish" warning, now print control characters as visible escapes, like the other lines that carry the project path. locate.mjs escapes the font path for ffmpeg's filter syntax, so a temp folder with ':', ',', quotes or brackets in its name still works, and it removes its font folder when the run is stopped by SIGINT or SIGTERM before re-raising the signal. play and present share one HTML escape helper. * refactor(cli): keep the shared HTML escape helper within the comment budget * fix: one HTML escape helper for the CLI, and locate.mjs escapes its font path in one pass The sign-in callback page uses the shared escapeHtml helper, which now also escapes single quotes. locate.mjs escapes the font path for ffmpeg's option list and filtergraph in a single replacement with the same result as before, and removes its font folder on SIGHUP as well as SIGINT and SIGTERM. * fix(cli): escape render output paths and cloud upload names A finished render printed its output path and the desktop app hint raw. The default output path sits under the project folder and is named after it, so the folder name reached the terminal on every render. Batch renders printed row output paths and the manifest path raw, and cloud render printed the archive name in its upload progress lines and walked file names in its left-out warnings raw. These lines now go through terminalText() or terminalLines(). --json output is unchanged.
482 lines
14 KiB
TypeScript
482 lines
14 KiB
TypeScript
import { failCommand } from "../utils/commandResult.js";
|
|
import { replaceFileAtomically } from "@hyperframes/core/atomic-file";
|
|
import { makeOutputFolder } from "../utils/outputFolder.js";
|
|
import { readJsonFileText } from "../utils/jsonFlag.js";
|
|
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
import { c } from "../ui/colors.js";
|
|
import { terminalText } from "@hyperframes/core";
|
|
import { errorBox } from "../ui/format.js";
|
|
import { normalizeErrorMessage as errorMessage } from "../utils/errorMessage.js";
|
|
import type { ReferenceBackground, ReferenceBackgroundResult } from "@hyperframes/producer";
|
|
import {
|
|
loadProjectVariableSchema,
|
|
reportVariableIssues,
|
|
validateVariablesAgainstSchema,
|
|
} from "../utils/variables.js";
|
|
|
|
export class BatchRenderInputError extends Error {
|
|
readonly title: string;
|
|
readonly hint: string | undefined;
|
|
|
|
constructor(title: string, message: string, hint?: string) {
|
|
super(message);
|
|
this.name = "BatchRenderInputError";
|
|
this.title = title;
|
|
this.hint = hint;
|
|
}
|
|
}
|
|
|
|
export interface PreparedBatchRow {
|
|
index: number;
|
|
variables: Record<string, unknown>;
|
|
outputPath: string;
|
|
}
|
|
|
|
export interface PreparedBatchRender {
|
|
batchPath: string;
|
|
manifestPath: string;
|
|
variableIssueCount: number;
|
|
rows: PreparedBatchRow[];
|
|
}
|
|
|
|
interface BatchRenderResult extends Partial<ReferenceBackgroundResult> {
|
|
durationMs?: number;
|
|
renderTimeMs: number;
|
|
}
|
|
|
|
export interface BatchManifestRow {
|
|
index: number;
|
|
outputPath: string;
|
|
status: "pending" | "running" | "completed" | "failed" | "skipped";
|
|
durationMs: number | null;
|
|
renderTimeMs: number | null;
|
|
reference_background: ReferenceBackground | null;
|
|
error: string | null;
|
|
startedAt: string | null;
|
|
completedAt: string | null;
|
|
variables: Record<string, unknown>;
|
|
}
|
|
|
|
export interface BatchManifest {
|
|
version: 1;
|
|
batchPath: string;
|
|
manifestPath: string;
|
|
total: number;
|
|
completed: number;
|
|
failed: number;
|
|
skipped: number;
|
|
rows: BatchManifestRow[];
|
|
}
|
|
|
|
interface PrepareBatchRenderOptions {
|
|
batchPath: string;
|
|
outputTemplate: string;
|
|
indexPath: string;
|
|
strictVariables: boolean;
|
|
quiet: boolean;
|
|
json: boolean;
|
|
readFile?: (path: string) => string;
|
|
}
|
|
|
|
interface RunBatchRenderOptions {
|
|
prepared: PreparedBatchRender;
|
|
concurrency: number;
|
|
failFast: boolean;
|
|
quiet: boolean;
|
|
json: boolean;
|
|
renderOne: (row: PreparedBatchRow) => Promise<BatchRenderResult>;
|
|
}
|
|
|
|
const PLACEHOLDER_RE = /\{([A-Za-z0-9_.-]+)\}/g;
|
|
const ROWS_NAME_WHOLE_OUTPUT_PATH = "{path}";
|
|
|
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
}
|
|
|
|
function parseJson(raw: string, source: string): unknown {
|
|
try {
|
|
return JSON.parse(raw);
|
|
} catch (error: unknown) {
|
|
throw new BatchRenderInputError("Invalid JSON in --batch", `${source}: ${errorMessage(error)}`);
|
|
}
|
|
}
|
|
|
|
export function parseBatchRows(raw: string, source: string): Record<string, unknown>[] {
|
|
const parsed = parseJson(raw, source);
|
|
const rows = Array.isArray(parsed) ? parsed : isRecord(parsed) ? parsed.rows : undefined;
|
|
|
|
if (!Array.isArray(rows)) {
|
|
throw new BatchRenderInputError(
|
|
"Invalid batch payload",
|
|
'--batch must be a JSON array of objects, or an object with a "rows" array.',
|
|
);
|
|
}
|
|
if (rows.length === 0) {
|
|
throw new BatchRenderInputError("Empty batch", `${source} contains zero rows.`);
|
|
}
|
|
|
|
return rows.map((row, index) => {
|
|
if (!isRecord(row)) {
|
|
throw new BatchRenderInputError(
|
|
"Invalid batch row",
|
|
`Row ${index} must be a JSON object of variable values.`,
|
|
);
|
|
}
|
|
return row;
|
|
});
|
|
}
|
|
|
|
function placeholderValue(row: Record<string, unknown>, key: string, index: number): string {
|
|
if (key === "index") return String(index);
|
|
if (!Object.hasOwn(row, key)) {
|
|
throw new BatchRenderInputError(
|
|
"Invalid output template",
|
|
`Missing value for placeholder {${key}} in row ${index}.`,
|
|
);
|
|
}
|
|
|
|
const value = row[key];
|
|
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
return String(value);
|
|
}
|
|
|
|
throw new BatchRenderInputError(
|
|
"Invalid output template",
|
|
`Placeholder {${key}} in row ${index} must resolve to a string, number, or boolean.`,
|
|
);
|
|
}
|
|
|
|
export function resolveOutputTemplate(
|
|
template: string,
|
|
row: Record<string, unknown>,
|
|
index: number,
|
|
): string {
|
|
return template.replace(PLACEHOLDER_RE, (_match, key: string) =>
|
|
placeholderValue(row, key, index),
|
|
);
|
|
}
|
|
|
|
function folderOfPrefix(prefix: string): string {
|
|
return prefix.endsWith("/") || prefix.endsWith(sep) ? resolve(prefix) : dirname(resolve(prefix));
|
|
}
|
|
|
|
function checkOutputsInsideTemplateFolder(rows: readonly PreparedBatchRow[], template: string) {
|
|
if (template === ROWS_NAME_WHOLE_OUTPUT_PATH) return;
|
|
const firstPlaceholder = template.search(PLACEHOLDER_RE);
|
|
if (firstPlaceholder < 0) return;
|
|
const folder =
|
|
firstPlaceholder === 0 ? resolve() : folderOfPrefix(template.slice(0, firstPlaceholder));
|
|
for (const row of rows) {
|
|
const rel = relative(folder, row.outputPath);
|
|
const outside = rel === "" || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel);
|
|
if (!outside) continue;
|
|
throw new BatchRenderInputError(
|
|
"Batch output outside --output folder",
|
|
`Row ${row.index} resolves to ${row.outputPath}, outside ${folder}.`,
|
|
"Row values may name subfolders of the --output folder but not leave it.",
|
|
);
|
|
}
|
|
}
|
|
|
|
function isSameOrChildPath(path: string, parent: string): boolean {
|
|
return path === parent || path.startsWith(parent.endsWith(sep) ? parent : parent + sep);
|
|
}
|
|
|
|
function commonOutputDirectory(outputPaths: readonly string[]): string {
|
|
const firstPath = outputPaths[0];
|
|
if (!firstPath) return resolve("renders");
|
|
|
|
let common = dirname(firstPath);
|
|
for (const outputPath of outputPaths.slice(1)) {
|
|
const dir = dirname(outputPath);
|
|
while (!isSameOrChildPath(dir, common)) {
|
|
const parent = dirname(common);
|
|
if (parent === common) return common;
|
|
common = parent;
|
|
}
|
|
}
|
|
return common;
|
|
}
|
|
|
|
function checkOutputCollisions(rows: readonly PreparedBatchRow[], manifestPath: string): void {
|
|
const seen = new Map<string, number>();
|
|
for (const row of rows) {
|
|
const previous = seen.get(row.outputPath);
|
|
if (previous !== undefined) {
|
|
throw new BatchRenderInputError(
|
|
"Batch output collision",
|
|
`Rows ${previous} and ${row.index} both resolve to ${row.outputPath}.`,
|
|
"Use placeholders such as {index} or a unique row key in --output.",
|
|
);
|
|
}
|
|
if (row.outputPath === manifestPath) {
|
|
throw new BatchRenderInputError(
|
|
"Batch output collision",
|
|
`Row ${row.index} resolves to the manifest path: ${manifestPath}.`,
|
|
);
|
|
}
|
|
seen.set(row.outputPath, row.index);
|
|
}
|
|
}
|
|
|
|
function validateBatchVariables(
|
|
rows: readonly Record<string, unknown>[],
|
|
indexPath: string,
|
|
strictVariables: boolean,
|
|
quiet: boolean,
|
|
json: boolean,
|
|
): number {
|
|
const schema = loadProjectVariableSchema(indexPath);
|
|
let issueCount = 0;
|
|
const strictRows: number[] = [];
|
|
|
|
for (let index = 0; index < rows.length; index++) {
|
|
const row = rows[index];
|
|
if (!row || Object.keys(row).length === 0) continue;
|
|
const rowIssueCount = reportBatchVariableIssues(row, index, schema, quiet, json);
|
|
if (rowIssueCount === 0) continue;
|
|
issueCount += rowIssueCount;
|
|
if (strictVariables) strictRows.push(index);
|
|
}
|
|
|
|
if (strictRows.length > 0) {
|
|
throw new BatchRenderInputError(
|
|
"Variable validation failed",
|
|
`Aborting batch due to variable issues in row ${strictRows.join(", ")} (--strict-variables mode).`,
|
|
);
|
|
}
|
|
|
|
return issueCount;
|
|
}
|
|
|
|
function reportBatchVariableIssues(
|
|
row: Record<string, unknown>,
|
|
index: number,
|
|
schema: ReturnType<typeof loadProjectVariableSchema>,
|
|
quiet: boolean,
|
|
json: boolean,
|
|
): number {
|
|
const issues = validateVariablesAgainstSchema(row, schema);
|
|
if (issues.length === 0) return 0;
|
|
if (!quiet && !json) {
|
|
console.log("");
|
|
console.log(c.dim(`Batch row ${index}:`));
|
|
}
|
|
reportVariableIssues(issues, { strict: false, quiet: quiet || json });
|
|
return issues.length;
|
|
}
|
|
|
|
export function prepareBatchRender(options: PrepareBatchRenderOptions): PreparedBatchRender {
|
|
const batchPath = resolve(options.batchPath);
|
|
const read = options.readFile ?? readJsonFileText;
|
|
let raw: string;
|
|
try {
|
|
raw = read(batchPath);
|
|
} catch (error: unknown) {
|
|
throw new BatchRenderInputError(
|
|
"Could not read --batch",
|
|
`${batchPath}: ${errorMessage(error)}`,
|
|
);
|
|
}
|
|
|
|
const variableRows = parseBatchRows(raw, batchPath);
|
|
const rows = variableRows.map((variables, index) => ({
|
|
index,
|
|
variables,
|
|
outputPath: resolve(resolveOutputTemplate(options.outputTemplate, variables, index)),
|
|
}));
|
|
checkOutputsInsideTemplateFolder(rows, options.outputTemplate);
|
|
const manifestPath = join(
|
|
commonOutputDirectory(rows.map((row) => row.outputPath)),
|
|
"manifest.json",
|
|
);
|
|
if (manifestPath === batchPath) {
|
|
throw new BatchRenderInputError(
|
|
"Batch manifest collision",
|
|
`The generated manifest would overwrite the batch input: ${batchPath}.`,
|
|
"Use a separate output directory in --output, such as renders/{index}.mp4.",
|
|
);
|
|
}
|
|
checkOutputCollisions(rows, manifestPath);
|
|
|
|
const variableIssueCount = validateBatchVariables(
|
|
variableRows,
|
|
options.indexPath,
|
|
options.strictVariables,
|
|
options.quiet,
|
|
options.json,
|
|
);
|
|
|
|
return {
|
|
batchPath,
|
|
manifestPath,
|
|
variableIssueCount,
|
|
rows,
|
|
};
|
|
}
|
|
|
|
function makeInitialManifest(prepared: PreparedBatchRender): BatchManifest {
|
|
return {
|
|
version: 1,
|
|
batchPath: prepared.batchPath,
|
|
manifestPath: prepared.manifestPath,
|
|
total: prepared.rows.length,
|
|
completed: 0,
|
|
failed: 0,
|
|
skipped: 0,
|
|
rows: prepared.rows.map((row) => ({
|
|
index: row.index,
|
|
outputPath: row.outputPath,
|
|
status: "pending",
|
|
durationMs: null,
|
|
renderTimeMs: null,
|
|
reference_background: null,
|
|
error: null,
|
|
startedAt: null,
|
|
completedAt: null,
|
|
variables: row.variables,
|
|
})),
|
|
};
|
|
}
|
|
|
|
function summarizeManifest(manifest: BatchManifest): void {
|
|
manifest.completed = manifest.rows.filter((row) => row.status === "completed").length;
|
|
manifest.failed = manifest.rows.filter((row) => row.status === "failed").length;
|
|
manifest.skipped = manifest.rows.filter((row) => row.status === "skipped").length;
|
|
}
|
|
|
|
function writeManifest(manifest: BatchManifest): void {
|
|
summarizeManifest(manifest);
|
|
makeOutputFolder(dirname(manifest.manifestPath));
|
|
replaceFileAtomically(manifest.manifestPath, JSON.stringify(manifest, null, 2) + "\n");
|
|
}
|
|
|
|
async function renderBatchRow(
|
|
row: PreparedBatchRow,
|
|
manifest: BatchManifest,
|
|
options: RunBatchRenderOptions,
|
|
): Promise<boolean> {
|
|
const manifestRow = manifest.rows[row.index];
|
|
if (!manifestRow) {
|
|
throw new Error(`Batch manifest is missing row ${row.index}`);
|
|
}
|
|
|
|
manifestRow.status = "running";
|
|
manifestRow.startedAt = new Date().toISOString();
|
|
writeManifest(manifest);
|
|
if (!options.quiet && !options.json) {
|
|
console.log(c.dim(terminalText(`Batch row ${row.index}: ${row.outputPath}`)));
|
|
}
|
|
|
|
try {
|
|
makeOutputFolder(dirname(row.outputPath));
|
|
const result = await options.renderOne(row);
|
|
manifestRow.status = "completed";
|
|
manifestRow.durationMs = result.durationMs ?? null;
|
|
manifestRow.renderTimeMs = result.renderTimeMs;
|
|
manifestRow.reference_background = result.reference_background ?? null;
|
|
manifestRow.completedAt = new Date().toISOString();
|
|
writeManifest(manifest);
|
|
return true;
|
|
} catch (error: unknown) {
|
|
manifestRow.status = "failed";
|
|
manifestRow.error = errorMessage(error);
|
|
manifestRow.completedAt = new Date().toISOString();
|
|
writeManifest(manifest);
|
|
if (!options.quiet && !options.json) {
|
|
console.log(c.error(` Row ${row.index} failed: ${manifestRow.error}`));
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function markUnstartedRowsSkipped(manifest: BatchManifest): void {
|
|
for (const row of manifest.rows) {
|
|
if (row.status !== "pending") continue;
|
|
row.status = "skipped";
|
|
row.error = "Skipped after --batch-fail-fast.";
|
|
row.completedAt = new Date().toISOString();
|
|
}
|
|
}
|
|
|
|
export async function runBatchRender(options: RunBatchRenderOptions): Promise<BatchManifest> {
|
|
if (options.concurrency < 1) {
|
|
throw new BatchRenderInputError(
|
|
"Invalid batch-concurrency",
|
|
`Got "${options.concurrency}". Must be a positive integer.`,
|
|
);
|
|
}
|
|
|
|
const manifest = makeInitialManifest(options.prepared);
|
|
writeManifest(manifest);
|
|
|
|
if (!options.quiet && !options.json) {
|
|
console.log("");
|
|
console.log(
|
|
c.accent("◆") +
|
|
` Batch rendering ${options.prepared.rows.length} rows` +
|
|
c.dim(` → ${options.prepared.manifestPath}`),
|
|
);
|
|
console.log(c.dim(` batch concurrency: ${options.concurrency}`));
|
|
console.log("");
|
|
}
|
|
|
|
let cursor = 0;
|
|
let stopLaunching = false;
|
|
const workerCount = Math.min(options.concurrency, options.prepared.rows.length);
|
|
|
|
await Promise.all(
|
|
Array.from({ length: workerCount }, async () => {
|
|
while (!stopLaunching) {
|
|
const row = options.prepared.rows[cursor];
|
|
if (!row) return;
|
|
cursor++;
|
|
|
|
const ok = await renderBatchRow(row, manifest, options);
|
|
if (!ok && options.failFast) {
|
|
stopLaunching = true;
|
|
}
|
|
}
|
|
}),
|
|
);
|
|
|
|
if (stopLaunching) markUnstartedRowsSkipped(manifest);
|
|
writeManifest(manifest);
|
|
if (options.json) {
|
|
console.log(
|
|
JSON.stringify({
|
|
type: "batch-complete",
|
|
manifestPath: manifest.manifestPath,
|
|
total: manifest.total,
|
|
completed: manifest.completed,
|
|
failed: manifest.failed,
|
|
skipped: manifest.skipped,
|
|
rows: manifest.rows,
|
|
}),
|
|
);
|
|
}
|
|
|
|
if (!options.quiet && !options.json) {
|
|
console.log("");
|
|
console.log(
|
|
manifest.failed > 0
|
|
? c.warn(
|
|
`Batch complete: ${manifest.completed} completed, ${manifest.failed} failed, ${manifest.skipped} skipped.`,
|
|
)
|
|
: c.success(`Batch complete: ${manifest.completed} completed.`),
|
|
);
|
|
console.log(c.dim(terminalText(`Manifest: ${manifest.manifestPath}`)));
|
|
}
|
|
|
|
return manifest;
|
|
}
|
|
|
|
export function exitBatchRenderInputError(error: unknown): never {
|
|
if (error instanceof BatchRenderInputError) {
|
|
errorBox(error.title, error.message, error.hint);
|
|
failCommand();
|
|
}
|
|
throw error;
|
|
}
|