feat(cli): share rendered videos through unified reviews (#7135)

This commit is contained in:
Terence Cho
2026-11-09 16:10:31 -08:00
parent 48a2b4e019
commit b72970cb4a
23 changed files with 1363 additions and 20 deletions
+1
View File
@@ -143,6 +143,7 @@ const commandLoaders = {
present: () => import("./commands/present.js").then((m) => m.default),
preview: () =>
assertStudioWorkspaceBuilt().then(() => import("./commands/preview.js").then((m) => m.default)),
share: () => import("./commands/share.js").then((m) => m.default),
publish: () => import("./commands/publish.js").then((m) => m.default),
open: () => import("./commands/open.js").then((m) => m.default),
"catch-up": () => import("./commands/catch-up.js").then((m) => m.default),
+29
View File
@@ -1422,6 +1422,35 @@ describe("renderLocal browser GPU config", () => {
expect(consumeCommandResult().exitCode).toBe(0);
});
it("does not finalize the host command or mask a later upload failure when embedded", async () => {
const success = await import("../utils/render-success-state.js");
const lifecycle = await import("../utils/commandResult.js");
const exit = vi.spyOn(lifecycle, "scheduleCliExit");
success._resetRenderSuccessForTests();
const uploadFailure = new Error("upload failed after render");
try {
const share = async () => {
await renderLocal(PROJECT_DIR, "/tmp/out.mp4", {
fps: { num: 30, den: 1 },
quality: "standard",
format: "mp4",
gpu: false,
browserGpuMode: "software",
hdrMode: "auto",
quiet: true,
embedded: true,
exitAfterComplete: true,
});
throw uploadFailure;
};
await expect(share()).rejects.toBe(uploadFailure);
expect(exit).not.toHaveBeenCalled();
expect(success.isRunDelivered()).toBe(false);
} finally {
success._resetRenderSuccessForTests();
}
});
it("still completes the render when the output registry cannot be written", async () => {
const project = mkdtempSync(join(tmpdir(), "hf-render-unrecorded-"));
mkdirSync(join(project, ".hyperframes"));
+7 -6
View File
@@ -572,6 +572,7 @@ export interface RenderOptions {
variables?: Record<string, unknown>;
entryFile?: string;
exitAfterComplete?: boolean;
embedded?: boolean;
/** Output resolution preset; see `resolveDeviceScaleFactor` for constraints. */
outputResolution?: CanvasResolution;
/** Whether the resolution names a tier without fixing an orientation. */
@@ -944,7 +945,7 @@ async function renderDocker(
// AND committed the artifact. Mirror renderLocal's post-success guarantee
// so any late throw here (telemetry flush, feedback prompt) cannot flip
// the exit code.
markRenderSucceeded();
if (!options.embedded) markRenderSucceeded();
await runPostRenderStepAsync("recordRenderSuccess", () =>
recordRenderSuccess(projectDir, outputPath, "completed", capture).then(() => {}),
);
@@ -986,7 +987,7 @@ async function renderDocker(
runPostRenderStep("warnIfWebmAlphaDropped", () =>
warnIfWebmAlphaDropped(outputPath, options.format, options.quiet),
);
if (options.exitAfterComplete) scheduleCliExit();
if (options.exitAfterComplete && !options.embedded) scheduleCliExit();
return { renderTimeMs: elapsed };
}
@@ -1250,7 +1251,7 @@ async function executeLocalRender(
// point on, ANY thrown teardown error must not be allowed to override
// the exit code. Field signal ts=1784169760 / ts=1784171150 / ts=1784172467
// (win32/x64, CLI 0.7.58): valid MP4 on disk, exited 1 with no error print.
markRenderSucceeded();
if (!options.embedded) markRenderSucceeded();
await runPostRenderStepAsync("recordRenderSuccess", () =>
recordRenderSuccess(
projectDir,
@@ -1296,7 +1297,7 @@ async function executeLocalRender(
}),
);
}
if (options.exitAfterComplete) scheduleCliExit();
if (options.exitAfterComplete && !options.embedded) scheduleCliExit();
const durationMs = job.perfSummary
? Math.round(job.perfSummary.compositionDurationSeconds * 1000)
: undefined;
@@ -1345,7 +1346,7 @@ async function renderRange(input: {
} catch (error: unknown) {
handleRenderError(error, options, input.startTime, input.cpu, false, "");
}
markRenderSucceeded();
if (!options.embedded) markRenderSucceeded();
const elapsed = Date.now() - input.startTime;
input.cpu.stop();
printRenderComplete({
@@ -1356,7 +1357,7 @@ async function renderRange(input: {
quiet: options.quiet,
format: options.format,
});
if (options.exitAfterComplete) scheduleCliExit();
if (options.exitAfterComplete && !options.embedded) scheduleCliExit();
return {
renderTimeMs: elapsed,
...reference,
+149
View File
@@ -0,0 +1,149 @@
import { defineCommand } from "../utils/defineCommand.js";
import { resolveProjectOrThrow } from "../utils/project.js";
import { CliUsageError, setCommandExitCode } from "../utils/commandResult.js";
import { isUnattended } from "../utils/attendedTerminal.js";
import * as prompts from "../ui/prompts.js";
import {
createShareService,
type ShareAction,
type ShareState,
type ShareService,
} from "../share/service.js";
import { shareError } from "../share/errors.js";
import { jsonFailure } from "../utils/jsonError.js";
import type { Example } from "./_examples.js";
export const examples: Example[] = [
["Create a review anyone with its link can open", "hyperframes share --public"],
["Add the current video as a new version", "hyperframes share --update"],
["Read the existing share without uploading edits", "hyperframes share --status --json"],
["Open sharing settings on the web", "hyperframes share --manage"],
];
export default defineCommand({
meta: {
name: "share",
description: "Share a rendered video for review, using the same sharing as Desktop",
},
args: {
dir: { type: "positional", description: "Project directory", required: false },
public: {
type: "boolean",
description: "Explicitly allow anyone with the link on first share",
},
team: { type: "boolean", description: "First share with this workspace" },
"invite-only": { type: "boolean", description: "First share with invited people only" },
private: { type: "boolean", description: "First share with private access" },
update: {
type: "boolean",
description: "Render and add a new video version to the existing share",
},
status: { type: "boolean", description: "Read status without rendering or uploading" },
manage: { type: "boolean", description: "Open this share's web management page" },
space: { type: "string", description: "Owning workspace for a new share" },
"wait-seconds": {
type: "string",
description: "Wait for processing (1–1800 seconds)",
default: "300",
},
json: { type: "boolean", description: "Emit a machine-readable result" },
yes: {
type: "boolean",
alias: "y",
description: "Do not prompt; an explicit first-share audience is still required",
},
},
async run({ args }) {
try {
const input = parseInput(args);
const project = resolveProjectOrThrow(args.dir);
const service: ShareService = createShareService(project.dir, (value) => {
if (value && !args.json)
process.stderr.write(
`Sharing: ${value.step}${value.slow ? " (still processing)" : ""}\r`,
);
});
await chooseAudience(input, args, service);
const result = await service.run(input);
await presentResult(result, input, Boolean(args.json));
} catch (error) {
const failure = shareError(error);
if (args.json) console.log(JSON.stringify(jsonFailure(failure.code, failure.message)));
else console.error(failure.message);
setCommandExitCode(error instanceof CliUsageError ? 2 : 1);
}
},
});
interface ShareArgs {
public?: boolean;
team?: boolean;
"invite-only"?: boolean;
private?: boolean;
update?: boolean;
status?: boolean;
manage?: boolean;
yes?: boolean;
json?: boolean;
"wait-seconds"?: string;
space?: string;
}
function parseInput(args: ShareArgs): ShareAction {
const waitSeconds = Number(args["wait-seconds"]);
if (!Number.isInteger(waitSeconds) || waitSeconds < 1 || waitSeconds > 1800)
throw new CliUsageError("--wait-seconds must be an integer from 1 to 1800.");
if ([args.update, args.status, args.manage].filter(Boolean).length > 1)
throw new CliUsageError("Choose only one of --update, --status or --manage.");
const audience = requestedAudience(args);
const action = args.status ? "status" : args.manage ? "manage" : args.update ? "update" : "share";
return { action, audience, space: args.space, waitSeconds };
}
function requestedAudience(args: ShareArgs) {
const audiences: NonNullable<ShareAction["audience"]>[] = [];
if (args.public) audiences.push("public");
if (args.team) audiences.push("team");
if (args["invite-only"]) audiences.push("invite");
if (args.private) audiences.push("private");
if (audiences.length > 1) throw new CliUsageError("Choose one first-share audience.");
return audiences[0];
}
function shouldPrompt(input: ShareAction, args: ShareArgs) {
return input.action === "share" && !input.audience && !args.yes && !args.json && !isUnattended();
}
async function chooseAudience(input: ShareAction, args: ShareArgs, service: ShareService) {
if (!shouldPrompt(input, args)) return;
if ((await service.status()).share) return;
const selected = await prompts.select({
message: "Who should be able to open this review?",
options: [
{ value: "public", label: "Anyone with the link (available on Free)" },
{ value: "team", label: "Workspace members" },
{ value: "invite", label: "Invited people" },
{ value: "private", label: "Only me" },
],
});
if (prompts.isCancel(selected)) throw new CliUsageError("Sharing cancelled.");
if (
selected === "public" ||
selected === "team" ||
selected === "invite" ||
selected === "private"
)
input.audience = selected;
}
async function presentResult(result: ShareState, input: ShareAction, json: boolean) {
if (json) console.log(JSON.stringify({ ok: true, ...result }));
else if (input.action === "manage") {
console.log(result.manageUrl);
if (!isUnattended()) await (await import("open")).default(result.manageUrl);
} else if (result.ready) console.log(`Shared video ready: ${result.url}`);
else if (result.state === "not_shared") console.log("This project has not been shared yet.");
else if (result.state === "link_off")
console.log("This share's link is off. Run hyperframes share --manage to turn it on.");
else console.log("Your video is still processing. Run hyperframes share --status to check it.");
}
+63
View File
@@ -0,0 +1,63 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ResolvedCredential } from "../auth/resolver.js";
const mocks = vi.hoisted(() => ({
resolve: vi.fn<() => Promise<ResolvedCredential>>(),
refresh: vi.fn(),
user: vi.fn(),
}));
vi.mock("../auth/resolver.js", () => ({ resolveCredential: mocks.resolve }));
vi.mock("../auth/oauth.js", () => ({ refreshTokens: mocks.refresh }));
vi.mock("../auth/client.js", () => ({
apiBaseUrl: () => "https://api.heygen.com",
AuthClient: class {
getCurrentUser = mocks.user;
},
}));
import { createShareAccess } from "./auth.js";
const oauth = (token: string): ResolvedCredential => ({
type: "oauth",
access_token: token,
source: "file_json",
refreshable: false,
});
beforeEach(() => {
vi.resetAllMocks();
mocks.user.mockResolvedValue({ username: "owner", email: "owner@example.com" });
});
describe("share OAuth identity", () => {
it("rejects API keys before any account request", async () => {
mocks.resolve.mockResolvedValue({ type: "api_key", key: "secret", source: "env" });
await expect(createShareAccess().access()).rejects.toMatchObject({ code: "UNAUTHENTICATED" });
expect(mocks.user).not.toHaveBeenCalled();
});
it("never falls back to an API key after refresh", async () => {
mocks.resolve
.mockResolvedValueOnce({
...oauth("old"),
type: "oauth",
access_token: "old",
refresh_token: "refresh",
refreshable: true,
})
.mockResolvedValueOnce({ type: "api_key", key: "key", source: "env" });
await expect(createShareAccess().access()).rejects.toMatchObject({ code: "UNAUTHENTICATED" });
expect(mocks.refresh).toHaveBeenCalledWith("refresh");
expect(mocks.user).not.toHaveBeenCalled();
});
it("resolves the actor again when the credential changes", async () => {
mocks.resolve.mockResolvedValueOnce(oauth("a")).mockResolvedValueOnce(oauth("b"));
mocks.user
.mockResolvedValueOnce({ username: "first" })
.mockResolvedValueOnce({ username: "second" });
const auth = createShareAccess();
expect((await auth.access()).owner).toBe("first");
expect((await auth.access()).owner).toBe("second");
});
it("does not retry a refused environment token", async () => {
mocks.resolve.mockResolvedValue(oauth("refused"));
await expect(createShareAccess().access("refused")).rejects.toMatchObject({
code: "UNAUTHENTICATED",
});
expect(mocks.refresh).not.toHaveBeenCalled();
});
});
+60
View File
@@ -0,0 +1,60 @@
import { apiBaseUrl, AuthClient } from "../auth/client.js";
import { tokenEndpoint, oauthEnvironment } from "../auth/config.js";
import { AuthError } from "../auth/errors.js";
import { refreshTokens } from "../auth/oauth.js";
import { resolveCredential } from "../auth/resolver.js";
export function shareSite(): string {
return oauthEnvironment() === "dev" ? "https://dev.hyperframes.dev" : "https://hyperframes.dev";
}
export function createShareAccess() {
let identity: { token: string; owner: string; email: string | null } | undefined;
const userClient = new AuthClient();
const access = async (refused?: string) => {
const credential = await shareCredential(refused);
if (identity?.token !== credential.access_token) {
const user = await userClient.getCurrentUser(credential);
if (!user.username) throw loginRequired();
identity = {
token: credential.access_token,
owner: user.username,
email: user.email ?? null,
};
}
return {
token: credential.access_token,
heygen: new URL(tokenEndpoint()).origin,
heygenApi: apiBaseUrl(),
owner: identity.owner,
};
};
return {
access,
signedInEmail: async () => {
await access();
return identity?.email ?? null;
},
};
}
function loginRequired(): AuthError {
return new AuthError(
"UNAUTHENTICATED",
"Sharing requires a signed-in HeyGen account.",
"Run hyperframes auth login. API keys cannot own shared projects.",
);
}
async function shareCredential(refused?: string) {
let credential = await resolveCredential();
if (credential.type !== "oauth") throw loginRequired();
if (credential.refreshable || credential.access_token === refused) {
if (!credential.refresh_token) throw loginRequired();
await refreshTokens(credential.refresh_token);
credential = await resolveCredential();
if (credential.type !== "oauth") throw loginRequired();
}
if (credential.access_token === refused) throw loginRequired();
return credential;
}
+37
View File
@@ -0,0 +1,37 @@
import { ReviewFailed, reviewSentence } from "@hyperframes/share";
import { isAuthError } from "../auth/errors.js";
import { CliUsageError } from "../utils/commandResult.js";
const HINTS: Record<string, string> = {
review_upload_origins_required:
"Review video storage is not configured. Set HYPERFRAMES_REVIEW_UPLOAD_ORIGINS to the exact storage origins provided by your deployment.",
review_project_limit_reached:
"Your workspace has used its five free shared projects. Update an existing share, or manage and remove one to free a slot. Turning a link off does not free a slot.",
review_subscription_required:
"That sharing option is not included in this workspace's plan. Choose an available audience explicitly or manage your plan.",
workspace_mismatch:
"This folder already shares into another workspace. Manage the existing share instead of changing its identity.",
review_binding_changed:
"The review linked to this folder changed. Run hyperframes share --status before trying again.",
manage_existing_audience:
"Manage this existing share to change its audience. Copying or updating a share preserves its settings.",
not_shared:
"This project has no shared review yet. Run hyperframes share with an explicit audience.",
};
export function shareError(error: unknown): { code: string; message: string } {
if (error instanceof CliUsageError) return { code: error.code, message: error.message };
if (isAuthError(error))
return {
code: error.code.toLowerCase(),
message: `${error.message} ${error.hint ?? ""}`.trim(),
};
if (error instanceof ReviewFailed)
return {
code: error.reason || "share_failed",
message: HINTS[error.reason] ?? reviewSentence(error),
};
return {
code: "share_failed",
message: error instanceof Error ? error.message : "Sharing failed. Try again.",
};
}
+67
View File
@@ -0,0 +1,67 @@
import { basename } from "node:path";
import { realpathSync } from "node:fs";
import {
bindShareHost,
projectFingerprint,
ReviewFailed,
setReviewSite,
signedInRequest,
} from "@hyperframes/share";
import { reviewUploadOrigins } from "@hyperframes/share/host.mjs";
import { findFFprobe } from "../browser/ffmpeg.js";
import { latestShareRender } from "./render.js";
import { shareSite } from "./auth.js";
import { cliReviewUploadOrigins } from "./uploadOrigins.js";
const projects = new Set<string>();
function isStorageOrigin(origin: string): boolean {
if (!URL.canParse(origin)) return false;
const url = new URL(origin);
const loopback = url.protocol === "http:" && url.hostname === "127.0.0.1";
return (
url.origin === origin && !url.hostname.includes("*") && (url.protocol === "https:" || loopback)
);
}
export function assertReviewUploadStorage(): void {
const origins = reviewUploadOrigins().filter(Boolean);
if (origins.length === 0 || !origins.every(isStorageOrigin))
throw new ReviewFailed(503, "review_upload_origins_required");
}
export function bindCliShareProject(path: string): string {
const dir = realpathSync(path);
projects.add(dir);
bindShareHost({
reviewUploadOrigins: cliReviewUploadOrigins(),
normalize: realpathSync,
assertOpenProject: (path) => {
const normalized = realpathSync(path);
if (!projects.has(normalized)) throw new Error("This project is not open for sharing.");
return normalized;
},
resolveOpenProjectByPath: (path) => {
const normalized = realpathSync(path);
return projects.has(normalized) ? { id: normalized, dir: normalized } : null;
},
listOpenProjects: () => [...projects].map((dir) => ({ dir })),
homeName: basename,
latestExportFile: latestShareRender,
projectFingerprint,
signedInRequest: (deps) =>
signedInRequest({
...deps,
headers: { "X-HeyGen-Source": "cli", "X-HeyGen-Client-Source": "hyperframes" },
}),
ffBinary: () => {
const binary = findFFprobe();
if (!binary) throw new Error("Install FFmpeg to prepare a shared video.");
return binary;
},
channelSite: "https://hyperframes.dev",
signinSites: ["https://hyperframes.dev", "https://dev.hyperframes.dev"],
});
setReviewSite(shareSite());
return dir;
}
@@ -0,0 +1,61 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { existsSync, mkdtempSync, realpathSync, readdirSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { RenderExecutionDependencies } from "../commands/render/execute.js";
import type { RenderOptions } from "../commands/render.js";
const mocks = vi.hoisted(() => ({ render: vi.fn(), plan: vi.fn(), execute: vi.fn() }));
vi.mock("@hyperframes/share", () => ({ projectFingerprint: async () => "unchanged" }));
vi.mock("../commands/render/plan.js", () => ({ createRenderPlan: mocks.plan }));
vi.mock("../commands/render/execute.js", () => ({ executeRenderPlan: mocks.execute }));
vi.mock("../commands/render.js", () => ({
renderLocal: mocks.render,
checkRenderResolutionPreflight: vi.fn(),
}));
import { latestShareRender, prepareShareRender } from "./render.js";
let project: string;
const options: RenderOptions = {
fps: { num: 30, den: 1 },
quality: "standard",
format: "mp4",
gpu: false,
browserGpuMode: "software",
hdrMode: "auto",
quiet: true,
exitAfterComplete: true,
};
beforeEach(() => {
vi.resetAllMocks();
project = realpathSync(mkdtempSync(join(tmpdir(), "hf-share-render-lifecycle-")));
mocks.plan.mockImplementation((plan) => plan);
mocks.execute.mockImplementation(
async (plan: { output: string }, dependencies: RenderExecutionDependencies) => {
await dependencies.renderLocal(project, plan.output, options);
},
);
mocks.render.mockImplementation(async (_dir: string, output: string) => {
writeFileSync(output, "rendered-video");
});
});
afterEach(() => rmSync(project, { recursive: true, force: true }));
it("keeps rendering embedded even when the command plan asks to exit", async () => {
await prepareShareRender(project);
expect(mocks.render).toHaveBeenCalledWith(
project,
expect.any(String),
expect.objectContaining({ embedded: true, exitAfterComplete: false }),
undefined,
);
expect(options.exitAfterComplete).toBe(true);
expect(latestShareRender(project)?.fingerprint).toBe("unchanged");
});
it("propagates render failures without publishing a successful artifact record", async () => {
const error = new Error("render failed");
mocks.render.mockImplementation(async (_dir: string, output: string) => {
writeFileSync(output, "partial-video");
throw error;
});
await expect(prepareShareRender(project)).rejects.toBe(error);
expect(existsSync(join(project, ".hyperframes", "share-render.json"))).toBe(false);
expect(readdirSync(join(project, ".hyperframes", "share-renders"))).toEqual([]);
});
+44
View File
@@ -0,0 +1,44 @@
import { mkdtempSync, mkdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { latestShareRender, prepareShareRender } from "./render.js";
const dirs: string[] = [];
function folder() {
const dir = realpathSync(mkdtempSync(join(tmpdir(), "hf-share-")));
dirs.push(dir);
return dir;
}
afterEach(() => {
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
describe("local sharing render boundary", () => {
it("rejects a symlinked state directory before creating descendants", async () => {
const dir = folder();
const outside = folder();
writeFileSync(join(dir, "index.html"), "<html></html>");
symlinkSync(outside, join(dir, ".hyperframes"));
await expect(prepareShareRender(dir)).rejects.toThrow("without symlinks");
});
it("does not accept a sidecar pointing outside the project", () => {
const dir = folder();
mkdirSync(join(dir, ".hyperframes"));
writeFileSync(
join(dir, ".hyperframes", "share-render.json"),
JSON.stringify({ id: "../../escape", path: "/tmp/escape.mp4", fingerprint: "f" }),
);
expect(latestShareRender(dir)).toBeNull();
});
it("reuses only the exact locally recorded file", () => {
const dir = folder();
const id = "41c4587b-abcd-42ab-87ab-21a7b64cc010";
const output = join(dir, ".hyperframes", "share-renders", `${id}.mp4`);
mkdirSync(join(dir, ".hyperframes", "share-renders"), { recursive: true });
writeFileSync(output, "video");
writeFileSync(
join(dir, ".hyperframes", "share-render.json"),
JSON.stringify({ id, path: output, fingerprint: "f" }),
);
expect(latestShareRender(dir)).toEqual({ id, path: output, fingerprint: "f" });
});
});
+92
View File
@@ -0,0 +1,92 @@
import { randomUUID } from "node:crypto";
import { existsSync, readFileSync, realpathSync } from "node:fs";
import { mkdir, writeFile, rename, rm } from "node:fs/promises";
import { join } from "node:path";
import { projectFingerprint } from "@hyperframes/share";
export interface ShareRender {
path: string;
id: string;
fingerprint: string;
}
export function latestShareRender(dir: string): ShareRender | null {
try {
const value: unknown = JSON.parse(
readFileSync(join(dir, ".hyperframes", "share-render.json"), "utf8"),
);
if (
!value ||
typeof value !== "object" ||
!("path" in value) ||
!("id" in value) ||
!("fingerprint" in value)
)
return null;
if (
typeof value.path !== "string" ||
typeof value.id !== "string" ||
typeof value.fingerprint !== "string" ||
!/^[a-f0-9-]{36}$/.test(value.id)
)
return null;
const expected = join(realpathSync(dir), ".hyperframes", "share-renders", `${value.id}.mp4`);
if (value.path !== expected || !existsSync(expected) || realpathSync(expected) !== expected)
return null;
return { path: expected, id: value.id, fingerprint: value.fingerprint };
} catch {
return null;
}
}
export async function prepareShareRender(dir: string): Promise<void> {
const before = await projectFingerprint(dir);
const previous = latestShareRender(dir);
if (previous?.fingerprint === before) return;
const stateFolder = join(dir, ".hyperframes");
if (existsSync(stateFolder) && realpathSync(stateFolder) !== stateFolder)
throw new Error("Sharing state must stay inside this project, without symlinks.");
await mkdir(stateFolder, { recursive: true });
const folder = join(stateFolder, "share-renders");
if (existsSync(folder) && realpathSync(folder) !== folder)
throw new Error("Sharing state must stay inside this project, without symlinks.");
await mkdir(folder, { recursive: true });
if (realpathSync(folder) !== folder)
throw new Error("Sharing state must stay inside this project, without symlinks.");
const id = randomUUID();
const output = join(folder, `${id}.mp4`);
const [{ createRenderPlan }, { executeRenderPlan }, render] = await Promise.all([
import("../commands/render/plan.js"),
import("../commands/render/execute.js"),
import("../commands/render.js"),
]);
const target = join(stateFolder, "share-render.json");
const temporary = `${target}.${id}.tmp`;
try {
const plan = createRenderPlan({ dir, output, format: "mp4", quiet: true, strict: true });
await executeRenderPlan(plan, {
renderLocal: (project, output, options, cancellation) =>
render.renderLocal(
project,
output,
{ ...options, embedded: true, exitAfterComplete: false },
cancellation,
),
renderDocker: async () => {
throw new Error("Share renders locally.");
},
checkResolution: render.checkRenderResolutionPreflight,
});
if (!existsSync(output))
throw new Error("The render did not produce a video. Run hyperframes render to diagnose it.");
if ((await projectFingerprint(dir)) !== before)
throw new Error(
"The project changed while rendering. Share again to capture the current project.",
);
await writeFile(temporary, JSON.stringify({ id, path: output, fingerprint: before }));
await rename(temporary, target);
} catch (error) {
await Promise.allSettled([rm(output, { force: true }), rm(temporary, { force: true })]);
throw error;
}
}
+259
View File
@@ -0,0 +1,259 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
status: vi.fn(),
version: vi.fn(),
record: vi.fn(),
project: vi.fn(),
spaces: vi.fn(),
flags: vi.fn(),
render: vi.fn(),
create: vi.fn(),
add: vi.fn(),
pending: vi.fn(),
refresh: vi.fn(),
}));
vi.mock("@hyperframes/share", () => ({
reviewClient: () => ({ project: mocks.project, spaces: mocks.spaces, reviewFlags: mocks.flags }),
reviewStatus: mocks.status,
reviewVersion: mocks.version,
reviewRecord: mocks.record,
shareForReview: mocks.create,
addVersion: mocks.add,
pendingReviewExport: mocks.pending,
refreshReviewExport: mocks.refresh,
setReviewAccess: vi.fn(),
turnOffReviewLink: vi.fn(),
ReviewFailed: class extends Error {
constructor(
public status: number,
public reason: string,
) {
super(reason);
}
},
}));
vi.mock("./auth.js", () => ({
createShareAccess: () => ({ access: vi.fn() }),
shareSite: () => "https://hyperframes.dev",
}));
vi.mock("./host.js", () => ({
assertReviewUploadStorage: vi.fn(),
bindCliShareProject: (path: string) => path,
}));
vi.mock("./render.js", () => ({ prepareShareRender: mocks.render }));
import { createShareService } from "./service.js";
const shared = {
projectId: "project",
url: "https://hyperframes.dev/review/link",
access: "public",
space: { id: "space" },
};
beforeEach(() => {
vi.resetAllMocks();
mocks.status.mockResolvedValue(null);
mocks.record.mockResolvedValue(null);
mocks.pending.mockResolvedValue(null);
mocks.version.mockResolvedValue({ last: null, source: "ready" });
mocks.project.mockResolvedValue({ latest_ready_version_id: "version-id" });
mocks.flags.mockResolvedValue({ versionSharing: true });
mocks.spaces.mockResolvedValue([
{
space_id: "space",
bound: true,
can_create_review: true,
review_entitlements: {
can_register_project: true,
allowed_collaborative_access_modes: ["public"],
},
},
]);
});
describe("share operation consent and identity", () => {
it("reads an existing link without rendering or creating a version", async () => {
mocks.status.mockResolvedValue(shared);
expect((await createShareService("/project").run({ action: "share" })).url).toBe(shared.url);
expect(mocks.render).not.toHaveBeenCalled();
expect(mocks.create).not.toHaveBeenCalled();
expect(mocks.add).not.toHaveBeenCalled();
});
it("never chooses an audience for unattended first share", async () => {
await expect(createShareService("/project").run({ action: "share" })).rejects.toMatchObject({
code: "audience_required",
});
expect(mocks.render).not.toHaveBeenCalled();
expect(mocks.create).not.toHaveBeenCalled();
});
it("checks free quota before rendering", async () => {
mocks.spaces.mockResolvedValue([
{
space_id: "space",
bound: true,
can_create_review: true,
review_entitlements: { can_register_project: false },
},
]);
await expect(
createShareService("/project").run({ action: "share", audience: "public" }),
).rejects.toMatchObject({ reason: "review_project_limit_reached" });
expect(mocks.render).not.toHaveBeenCalled();
});
it("preserves existing workspace and audience", async () => {
mocks.status.mockResolvedValue(shared);
const service = createShareService("/project");
await expect(service.run({ action: "update", space: "other" })).rejects.toMatchObject({
reason: "workspace_mismatch",
});
await expect(service.run({ action: "share", audience: "private" })).rejects.toMatchObject({
reason: "manage_existing_audience",
});
expect(mocks.render).not.toHaveBeenCalled();
});
it("refuses a public share opened while a private first share was rendering", async () => {
mocks.render.mockImplementation(async () => {
mocks.create.mockResolvedValue(shared);
});
await expect(
createShareService("/project").run({ action: "share", audience: "private" }),
).rejects.toMatchObject({ reason: "manage_existing_audience" });
expect(mocks.add).not.toHaveBeenCalled();
});
it("refuses a first share bound to another workspace during rendering", async () => {
mocks.render.mockImplementation(async () => {
mocks.create.mockResolvedValue({ ...shared, space: { id: "other" } });
});
await expect(
createShareService("/project").run({ action: "share", audience: "public", space: "space" }),
).rejects.toMatchObject({ reason: "workspace_mismatch" });
expect(mocks.add).not.toHaveBeenCalled();
});
it("refuses an update when the folder changes review projects during rendering", async () => {
mocks.status.mockResolvedValue(shared);
mocks.render.mockImplementation(async () => {
mocks.status.mockResolvedValue({ ...shared, projectId: "different-project" });
});
await expect(createShareService("/project").run({ action: "update" })).rejects.toMatchObject({
reason: "review_binding_changed",
});
expect(mocks.add).not.toHaveBeenCalled();
});
it("refuses an update when access changes during rendering", async () => {
mocks.status.mockResolvedValue({ ...shared, access: "private" });
mocks.render.mockImplementation(async () => {
mocks.status.mockResolvedValue(shared);
});
await expect(createShareService("/project").run({ action: "update" })).rejects.toMatchObject({
reason: "manage_existing_audience",
});
expect(mocks.add).not.toHaveBeenCalled();
});
it("pins the approved project into a first upload", async () => {
mocks.create.mockImplementation(async () => {
mocks.status.mockResolvedValue(shared);
return shared;
});
mocks.add.mockResolvedValue(null);
await createShareService("/project").run({ action: "share", audience: "public" });
expect(mocks.create).toHaveBeenCalledWith(expect.objectContaining({ spaceId: "space" }));
expect(mocks.add).toHaveBeenCalledWith(expect.objectContaining({ projectId: "project" }));
});
it("retries an unfinished first share in its saved workspace", async () => {
mocks.record.mockResolvedValue({ spaceId: "saved", projectId: "project" });
mocks.spaces.mockResolvedValue([
{ space_id: "space", bound: true, can_create_review: true },
{ space_id: "saved", can_create_review: true },
]);
mocks.create.mockImplementation(async () => {
const saved = { ...shared, space: { id: "saved" }, access: "private" };
mocks.status.mockResolvedValue(saved);
return saved;
});
mocks.add.mockResolvedValue(null);
const service = createShareService("/project");
await expect(
service.run({ action: "share", audience: "private", space: "space" }),
).rejects.toMatchObject({ reason: "workspace_mismatch" });
expect(mocks.render).not.toHaveBeenCalled();
await service.run({ action: "share", audience: "private" });
expect(mocks.create).toHaveBeenCalledWith(expect.objectContaining({ spaceId: "saved" }));
expect(mocks.add).toHaveBeenCalledWith(expect.objectContaining({ projectId: "project" }));
});
it("does not report a different project's link if the folder changes during upload", async () => {
mocks.status.mockResolvedValue(shared);
mocks.add.mockImplementation(async () => {
mocks.status.mockResolvedValue({ ...shared, projectId: "different-project" });
return null;
});
await expect(createShareService("/project").run({ action: "update" })).rejects.toMatchObject({
reason: "review_binding_changed",
});
expect(mocks.add).toHaveBeenCalledWith(expect.objectContaining({ projectId: "project" }));
});
it("does not label an old ready version as a completed update", async () => {
mocks.status.mockResolvedValue(shared);
mocks.add.mockResolvedValue(null);
mocks.version.mockResolvedValue({ last: { current: false }, source: "ready" });
const result = await createShareService("/project").run({ action: "update" });
expect(result).toMatchObject({ state: "processing", ready: false, url: null });
});
it("reports rejection discovered after the upload watch ends", async () => {
mocks.status.mockResolvedValue(shared);
mocks.add.mockResolvedValue(null);
mocks.refresh.mockResolvedValueOnce(undefined).mockImplementationOnce(async () => {
mocks.version.mockResolvedValue({ last: null, source: "ready", failure: "Video rejected." });
});
await expect(createShareService("/project").run({ action: "update" })).rejects.toThrow(
"Video rejected.",
);
});
it("does not silently upload changed edits while resuming first share", async () => {
mocks.status.mockResolvedValue(shared);
mocks.project.mockResolvedValue({ latest_ready_version_id: null });
mocks.version.mockResolvedValue({ last: null, source: "stale" });
await expect(createShareService("/project").run({ action: "share" })).rejects.toThrow(
"--update",
);
expect(mocks.render).not.toHaveBeenCalled();
expect(mocks.add).not.toHaveBeenCalled();
});
it("keeps an off link off on repeat share", async () => {
mocks.status.mockResolvedValue({ ...shared, url: null });
expect((await createShareService("/project").run({ action: "share" })).state).toBe("link_off");
expect(mocks.create).not.toHaveBeenCalled();
});
});
describe("asynchronous share recovery", () => {
it("reconciles completion before reading project and local status", async () => {
mocks.status.mockResolvedValue(shared);
mocks.pending.mockResolvedValue({ projectId: "project", videoId: "video-id" });
mocks.refresh.mockImplementation(async () => {
mocks.pending.mockResolvedValue(null);
});
const result = await createShareService("/project").run({ action: "status" });
expect(mocks.refresh).toHaveBeenCalledOnce();
expect(mocks.refresh.mock.invocationCallOrder[0]).toBeLessThan(
mocks.project.mock.invocationCallOrder[0] ?? 0,
);
expect(result).toMatchObject({ state: "ready", ready: true, url: shared.url });
expect(mocks.add).not.toHaveBeenCalled();
expect(mocks.render).not.toHaveBeenCalled();
});
it("keeps an active upload processing even if unrelated IDs happen to match", async () => {
mocks.status.mockResolvedValue(shared);
mocks.pending.mockResolvedValue({ projectId: "project", videoId: "version-id" });
expect(await createShareService("/project").status()).toMatchObject({
state: "processing",
ready: false,
url: null,
});
});
});
+224
View File
@@ -0,0 +1,224 @@
import { basename } from "node:path";
import { CliUsageError } from "../utils/commandResult.js";
import {
addVersion,
pendingReviewExport,
refreshReviewExport,
reviewClient,
reviewRecord,
reviewStatus,
reviewVersion,
shareForReview,
setReviewAccess,
turnOffReviewLink,
ReviewFailed,
type AccessMode,
type ReviewClient,
type ReviewExportProgress,
type ReviewShare,
} from "@hyperframes/share";
import { createShareAccess, shareSite } from "./auth.js";
import { assertReviewUploadStorage, bindCliShareProject } from "./host.js";
import { prepareShareRender } from "./render.js";
export interface ShareAction {
action: "share" | "update" | "status" | "manage";
audience?: AccessMode;
space?: string;
waitSeconds?: number;
}
function linkState(share: ReviewShare | null, ready: boolean): string {
if (!share) return "not_shared";
if (!share.url) return "link_off";
return ready ? "ready" : "processing";
}
async function readStatus(dir: string, client: ReviewClient, expectedProjectId?: string) {
const share = await reviewStatus({ projectPath: dir, client });
if (expectedProjectId) assertUploadProject(share, expectedProjectId);
if (share) await refreshReviewExport(dir, client);
const project = await readProject(share, client);
const latest = project?.latest_ready_version_id ?? null;
const version = await reviewVersion(dir, { latestReadyVersionId: latest });
const pending = await pendingReviewExport(dir);
const activeUrl = share?.url ?? null;
const processing = isProcessing(pending, share);
const ready = Boolean(activeUrl && latest && !processing);
return {
share,
version,
pending,
state: linkState(share, ready),
ready,
...statusLinks(activeUrl, ready, processing, project),
};
}
async function readProject(share: ReviewShare | null, client: ReviewClient) {
return share?.projectId ? client.project(share.projectId) : null;
}
function statusLinks(
url: string | null,
ready: boolean,
processing: boolean,
project: Awaited<ReturnType<typeof readProject>>,
) {
return {
url: ready ? url : null,
previousUrl: processing && project?.latest_ready_version_id ? url : null,
manageUrl: project?.authenticated_review_url ?? `${shareSite()}/shares`,
};
}
function isProcessing(
pending: Awaited<ReturnType<typeof pendingReviewExport>>,
share: ReviewShare | null,
) {
return Boolean(pending && pending.projectId === share?.projectId);
}
function selectSpace(spaces: Awaited<ReturnType<ReviewClient["spaces"]>>, id?: string) {
if (id) return spaces.find((space) => space.space_id === id);
return spaces.find((space) => space.bound) ?? spaces.find((space) => space.kind === "personal");
}
function assertUploadProject(share: ReviewShare | null, expectedId?: string): string {
const id = share?.projectId;
if (!id || (expectedId && id !== expectedId))
throw new ReviewFailed(409, "review_binding_changed");
return id;
}
function assertExistingIntent(share: ReviewShare | null, input: ShareAction) {
if (!share) {
if (input.action === "update") throw new ReviewFailed(404, "not_shared");
return;
}
if (input.space && share.space?.id !== input.space)
throw new ReviewFailed(409, "workspace_mismatch");
if (input.audience && share.access !== input.audience)
throw new ReviewFailed(409, "manage_existing_audience");
}
function retrievesExisting(current: ShareState, input: ShareAction) {
return current.share && input.action === "share" && current.state !== "processing";
}
async function preflightFirst(dir: string, client: ReviewClient, input: ShareAction) {
const audience = input.audience;
if (!audience)
throw new CliUsageError(
"Choose an audience with --public, --team, --invite-only or --private. --yes is not audience consent.",
{ code: "audience_required" },
);
const [spaces, record] = await Promise.all([client.spaces(), reviewRecord(dir)]);
const space = selectSpace(spaces, registrationSpace(record, input.space));
if (!space || !space.can_create_review) throw new ReviewFailed(403, "workspace_cannot_share");
assertQuota(record, space);
assertAudience(audience, space);
return space.space_id;
}
type Space = Awaited<ReturnType<ReviewClient["spaces"]>>[number];
type ShareRecord = Awaited<ReturnType<typeof reviewRecord>>;
function registrationSpace(record: ShareRecord, requested?: string) {
if (!record?.spaceId) return requested;
if (!requested || requested === record.spaceId) return record.spaceId;
if (record.registration || record.projectId) throw new ReviewFailed(409, "workspace_mismatch");
return requested;
}
function assertQuota(record: ShareRecord, space: Space) {
if (record?.registration || record?.projectId) return;
if (space.review_entitlements?.can_register_project === false)
throw new ReviewFailed(402, "review_project_limit_reached");
}
function assertAudience(audience: AccessMode, space: Space) {
if (audience === "private") return;
if (!space.review_entitlements?.allowed_collaborative_access_modes.includes(audience))
throw new ReviewFailed(402, "review_subscription_required");
}
function assertResumeSource(current: ShareState, input: ShareAction) {
if (current.share && input.action === "share" && current.version.source !== "ready")
throw new Error(
"The shared video is unfinished and local edits have changed. Run hyperframes share --update to explicitly upload the current project.",
);
}
export function createShareService(
projectPath: string,
progress: (value: ReviewExportProgress | null) => void = () => {},
) {
const dir = bindCliShareProject(projectPath);
const auth = createShareAccess();
const client = reviewClient(auth);
const status = async (expectedProjectId?: string) => {
await auth.access();
return readStatus(dir, client, expectedProjectId);
};
const upload = async (input: ShareAction, projectId: string) => {
const end = Date.now() + (input.waitSeconds ?? 300) * 1000;
let added = false;
const failure = await addVersion({
projectPath: dir,
projectId,
title: basename(dir),
client,
onProgress: progress,
allowPending: true,
onAdded: () => {
added = true;
},
open: () => Date.now() < end,
});
if (failure) throw new Error(failure);
const result = await status(projectId);
if (result.version.failure) throw new Error(result.version.failure);
if (!added && !result.version.last?.current)
return { ...result, state: "processing", ready: false, url: null };
return result;
};
const uploadTarget = async (current: ReviewShare | null, input: ShareAction, space?: string) => {
const share = current
? await reviewStatus({ projectPath: dir, client })
: await shareForReview({
projectPath: dir,
title: basename(dir),
client,
spaceId: space,
audience: input.audience,
});
const projectId = assertUploadProject(share, current?.projectId);
if (share?.takedown) throw new ReviewFailed(409, "moderation_hold");
assertExistingIntent(share, {
...input,
space: input.space ?? space,
audience: input.audience ?? current?.access,
});
return projectId;
};
const run = async (input: ShareAction) => {
const current = await status();
if (input.action === "status" || input.action === "manage") return current;
assertExistingIntent(current.share, input);
if (retrievesExisting(current, input)) return current;
if (!(await client.reviewFlags()).versionSharing)
throw new ReviewFailed(403, "feature_unavailable");
const space = current.share
? current.share.space?.id
: await preflightFirst(dir, client, input);
assertResumeSource(current, input);
assertReviewUploadStorage();
await prepareShareRender(dir);
return upload(input, await uploadTarget(current.share, input, space));
};
return {
status,
run,
capabilities: () => client.reviewFlags(),
spaces: () => client.spaces(),
setAccess: async (access: AccessMode) => {
await setReviewAccess({ projectPath: dir, client, change: { access } });
return status();
},
linkOff: async () => {
await turnOffReviewLink({ projectPath: dir, client });
return status();
},
linkOn: async () => {
await shareForReview({ projectPath: dir, title: basename(dir), client });
return status();
},
};
}
export type ShareService = ReturnType<typeof createShareService>;
export type ShareState = Awaited<ReturnType<typeof readStatus>>;
@@ -0,0 +1,90 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { cliReviewUploadOrigins } from "./uploadOrigins.js";
import { assertReviewUploadStorage, bindCliShareProject } from "./host.js";
import { trustedUploadUrl } from "@hyperframes/share/reviewUpload.mjs";
let dir: string;
beforeEach(() => {
for (const key of [
"HYPERFRAMES_REVIEW_UPLOAD_ORIGINS",
"HYPERFRAMES_ENV",
"HEYGEN_API_URL",
"HYPERFRAMES_OAUTH_TOKEN_URL",
"HYPERFRAMES_OAUTH_CLIENT_ID",
])
vi.stubEnv(key, undefined);
dir = mkdtempSync(join(tmpdir(), "share-upload-origins-"));
});
afterEach(() => {
vi.unstubAllEnvs();
rmSync(dir, { recursive: true, force: true });
});
it("trusts only the production video and source storage origins by default", () => {
expect(cliReviewUploadOrigins()).toEqual([
"https://heygen-hyperframes-reviews-prod-767398024897-us-east-2.s3.amazonaws.com",
"https://heygen-hyperframes-reviews-prod-767398024897-us-east-2.s3.us-east-2.amazonaws.com",
"https://hyperframes-composition-sync-prod.s3.us-east-2.amazonaws.com",
]);
bindCliShareProject(dir);
expect(() => assertReviewUploadStorage()).not.toThrow();
for (const origin of cliReviewUploadOrigins())
expect(trustedUploadUrl(`${origin}/object?signature=fixture`)).not.toBeNull();
});
it.each([
["HYPERFRAMES_ENV", "dev"],
["HEYGEN_API_URL", "https://custom.example"],
["HYPERFRAMES_OAUTH_TOKEN_URL", "https://custom.example/token"],
["HYPERFRAMES_OAUTH_CLIENT_ID", "custom-client"],
])("does not inherit production trust when %s changes", (key, value) => {
bindCliShareProject(dir);
const production = cliReviewUploadOrigins()[0];
vi.stubEnv(key, value);
bindCliShareProject(dir);
expect(cliReviewUploadOrigins()).toEqual([]);
expect(() => assertReviewUploadStorage()).toThrow();
expect(trustedUploadUrl(`${production}/object`)).toBeNull();
});
it("replaces defaults with an explicit exact-origin override for custom deployments", () => {
vi.stubEnv("HYPERFRAMES_ENV", "dev");
vi.stubEnv(
"HYPERFRAMES_REVIEW_UPLOAD_ORIGINS",
" https://storage.example , https://sources.example ",
);
bindCliShareProject(dir);
expect(cliReviewUploadOrigins()).toEqual(["https://storage.example", "https://sources.example"]);
expect(() => assertReviewUploadStorage()).not.toThrow();
expect(trustedUploadUrl("https://storage.example/object")).not.toBeNull();
expect(
trustedUploadUrl("https://hyperframes-composition-sync-prod.s3.us-east-2.amazonaws.com/object"),
).toBeNull();
});
it.each(["", " , "])("keeps explicit empty overrides fail-closed (%j)", (override) => {
vi.stubEnv("HYPERFRAMES_REVIEW_UPLOAD_ORIGINS", override);
bindCliShareProject(dir);
expect(cliReviewUploadOrigins()).toEqual([]);
expect(() => assertReviewUploadStorage()).toThrow();
});
it("rejects sibling buckets, userinfo, non-HTTPS and accelerated hosts", () => {
bindCliShareProject(dir);
for (const url of [
"https://other-bucket.s3.us-east-2.amazonaws.com/object",
"https://hyperframes-composition-sync-prod.s3.us-east-2.amazonaws.com.evil.example/object",
"https://user:password@hyperframes-composition-sync-prod.s3.us-east-2.amazonaws.com/object",
"http://hyperframes-composition-sync-prod.s3.us-east-2.amazonaws.com/object",
"https://heygen-hyperframes-reviews-prod-767398024897-us-east-2.s3-accelerate.amazonaws.com/object",
])
expect(trustedUploadUrl(url)).toBeNull();
});
it.each(["https://storage.example/path", "https://*.example", "http://storage.example"])(
"does not accept invalid override %s",
(override) => {
vi.stubEnv("HYPERFRAMES_REVIEW_UPLOAD_ORIGINS", override);
bindCliShareProject(dir);
expect(() => assertReviewUploadStorage()).toThrow();
},
);
+28
View File
@@ -0,0 +1,28 @@
import { apiBaseUrl } from "../auth/client.js";
import {
defaultClientId,
oauthEnvironment,
resolveClientId,
tokenEndpoint,
} from "../auth/config.js";
const PRODUCTION_UPLOAD_ORIGINS = [
"https://heygen-hyperframes-reviews-prod-767398024897-us-east-2.s3.amazonaws.com",
"https://heygen-hyperframes-reviews-prod-767398024897-us-east-2.s3.us-east-2.amazonaws.com",
"https://hyperframes-composition-sync-prod.s3.us-east-2.amazonaws.com",
] as const;
export function cliReviewUploadOrigins(): readonly string[] {
const override = process.env.HYPERFRAMES_REVIEW_UPLOAD_ORIGINS;
if (override !== undefined)
return override
.split(",")
.map((origin) => origin.trim())
.filter(Boolean);
const standardProduction =
oauthEnvironment() === "prod" &&
apiBaseUrl() === "https://api.heygen.com" &&
tokenEndpoint() === "https://api2.heygen.com/v1/oauth/token" &&
resolveClientId() === defaultClientId();
return standardProduction ? PRODUCTION_UPLOAD_ORIGINS : [];
}
@@ -40,6 +40,7 @@ describe("runPostRenderStep", () => {
const originalExitCode = process.exitCode;
beforeEach(() => {
markRenderSucceeded();
registerRootExitCodeSanitizer(() => {
process.exitCode = 0;
});
@@ -126,6 +127,7 @@ describe("runPostRenderStepAsync", () => {
const originalExitCode = process.exitCode;
beforeEach(() => {
markRenderSucceeded();
registerRootExitCodeSanitizer(() => {
process.exitCode = 0;
});
@@ -164,3 +166,30 @@ describe("runPostRenderStepAsync", () => {
expect(process.exitCode).toBe(0);
});
});
it("does not sanitize the host exit code after embedded-render cleanup fails", async () => {
_resetRenderSuccessForTests();
const sanitize = vi.fn();
registerRootExitCodeSanitizer(sanitize);
try {
runPostRenderStep(
"metrics",
() => {
throw new Error("metrics failed");
},
vi.fn(),
);
await runPostRenderStepAsync(
"history",
async () => {
throw new Error("history failed");
},
vi.fn(),
);
expect(sanitize).not.toHaveBeenCalled();
expect(isRenderSucceeded()).toBe(false);
} finally {
registerRootExitCodeSanitizer(() => {});
_resetRenderSuccessForTests();
}
});
@@ -69,10 +69,10 @@ const defaultErrorSink: PostRenderErrorSink = (message) => {
/**
* Run a post-artifact-validated cleanup step so a throw cannot flip the CLI
* exit code. `markRenderSucceeded()` MUST have been called first — this
* helper is only safe on the success path where the artifact is already
* committed to disk. Logs a compact warning to stderr, asks the root CLI to
* clear a stray exit code, and swallows the error.
* exit code. Use only after the artifact is committed to disk. Logs a compact
* warning and swallows the error. Only a top-level render that called
* `markRenderSucceeded()` may ask the root CLI to clear a stray exit code;
* an embedded render does not own the surrounding command’s outcome.
*/
export function runPostRenderStep(
label: string,
@@ -103,5 +103,5 @@ function reportPostRenderStepFailure(label: string, err: unknown, sink: PostRend
sink(` [hyperframes] Post-render step '${label}' failed (render already succeeded): ${message}`);
// The failing step (or something it triggered) may have set a non-zero
// exitCode. The render succeeded, so ask the root CLI owner to clear it.
sanitizeSuccessfulExitCode();
if (isRenderSucceeded()) sanitizeSuccessfulExitCode();
}