Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions packages/cli/src/commands/check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { terminalText } from "@hyperframes/core";
import { captureArtifactRevision } from "../utils/artifactCapture.js";
import { pngDimensions } from "../utils/pngDimensions.js";
import { randomUUID } from "node:crypto";
import { mkdirSync, writeFileSync } from "node:fs";
import { writeFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import {
recordArtifacts,
Expand Down Expand Up @@ -54,6 +54,7 @@ import {
readCachedPass,
storePass,
} from "../utils/checkCache.js";
import { recordFolder } from "../utils/projectRecords.js";
import { VERSION } from "../version.js";

export const examples: Example[] = [
Expand Down Expand Up @@ -113,6 +114,13 @@ export function checkReportFile(projectDir: string, id: string): string {
return join(projectDir, ".hyperframes", "artifacts", "checks", `${id}.json`);
}

function makeReportFolder(path: string, projectDir: string): void {
if (!recordFolder(projectDir, "artifacts/checks"))
throw new Error(
`${dirname(path)} is reached through a link or a file; remove it and run again`,
);
}

async function saveCheckReport(
project: ProjectDir,
options: CheckOptions,
Expand All @@ -121,7 +129,7 @@ async function saveCheckReport(
id: string,
): Promise<SavedCheck> {
const path = checkReportFile(project.dir, id);
mkdirSync(dirname(path), { recursive: true });
makeReportFolder(path, project.dir);
writeFileSync(path, JSON.stringify(report, null, 2) + "\n", { flag: "wx" });
const reportScope =
"scope" in report && typeof report.scope === "object" && report.scope !== null
Expand Down
11 changes: 6 additions & 5 deletions packages/cli/src/commands/lambda/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ import { failCommand } from "../../utils/commandResult.js";
* can symlink the directory.
*/

import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";
import { dirname, join } from "node:path";
import { replaceFileAtomically } from "@hyperframes/core/atomic-file";
import { existsSync, readdirSync, readFileSync, rmSync } from "node:fs";
import { join } from "node:path";
import { writeRecord } from "../../utils/projectRecords.js";

export interface StackOutputs {
/** Project-name prefix passed to `deploy`. Used as CloudFormation stack-name suffix. */
Expand Down Expand Up @@ -52,8 +52,9 @@ export function stateFilePath(

export function writeStackOutputs(outputs: StackOutputs, cwd: string = process.cwd()): string {
const path = stateFilePath(outputs.stackName, cwd);
mkdirSync(dirname(path), { recursive: true });
replaceFileAtomically(path, JSON.stringify(outputs, null, 2) + "\n");
const name = `${STATE_FILE_PREFIX}${outputs.stackName}.json`;
if (!writeRecord(cwd, name, JSON.stringify(outputs, null, 2) + "\n"))
throw new Error(`Could not write ${path}: it, or .hyperframes, is a link or not a plain file`);
return path;
}

Expand Down
6 changes: 5 additions & 1 deletion packages/cli/src/commands/snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
sdrCanvasColourFilters,
} from "@hyperframes/engine";
import { mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries";
import { projectFolder } from "../utils/projectRecords.js";
import { screenshotOnceMore } from "../utils/screenshotOnceMore.js";
import { parseTimeoutMs } from "../utils/timeoutArg.js";
import type { Page } from "puppeteer-core";
Expand Down Expand Up @@ -1172,7 +1173,10 @@ export async function captureSnapshots(
: null;

const snapshotDir = opts.outputDir ?? artifactDirectory(projectDir, "snapshots");
mkdirSync(snapshotDir, { recursive: true });
if (!projectFolder(projectDir, snapshotDir))
throw new Error(
`${snapshotDir} is reached through a link or a file; remove it and run again`,
);
if (!opts.keep) replaced.push(...clearEarlierStills(snapshotDir));
if (replaced.length > 0) {
log(` ${c.warn("⚠")} ${clearedNote(replaced.length, snapshotDir)}`);
Expand Down
8 changes: 6 additions & 2 deletions packages/cli/src/commands/templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
writeFileSync,
} from "node:fs";
import { makeOutputFolder } from "../utils/outputFolder.js";
import { recordFolder } from "../utils/projectRecords.js";
import { processIsAlive } from "../utils/processTree.js";
import { basename, dirname, join, resolve } from "node:path";
import { resolveCloudAuthHeaders } from "../cloud/auth.js";
Expand Down Expand Up @@ -209,7 +210,6 @@ async function unpack(
pack: TemplatePack,
): Promise<string | null> {
makeOutputFolder(dirname(dest));
makeOutputFolder(stage);
removeAbandonedParts(stage, dest);
const work = createStagingDir(stage, `${partPrefix(dest)}${process.pid}-`);
const stopWatching = removeOnStop(work);
Expand Down Expand Up @@ -269,7 +269,11 @@ export async function pullTemplate(slug: string, dir: string): Promise<string> {
);
const dest = resolve(dir, "templates", slug);
if (alreadyPulled(dest, pack)) return dest;
const stage = resolve(dir, ".hyperframes", "template-pulls");
const stage = recordFolder(resolve(dir), "template-pulls");
if (!stage)
throw new PullRefused(
`${resolve(dir, ".hyperframes")} is a link or not a folder; remove it and pull again.`,
);
const aside = await unpack(await download(await bundleUrl(pack), pack), dest, stage, pack);
if (aside)
console.log(
Expand Down
67 changes: 65 additions & 2 deletions packages/cli/src/heygen/v3.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import {
linkSync,
lstatSync,
mkdirSync,
mkdtempSync,
readFileSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
Expand All @@ -14,7 +22,7 @@ vi.mock("../cloud/auth.js", () => ({
resolveCloudBaseUrl: () => "https://api.test",
}));

const { idempotencyKey, ownVoices, runJob } = await import("./v3.js");
const { idempotencyKey, keepVoice, ownVoices, runJob } = await import("./v3.js");

/** A job route through the generated client: the create and the status GET it polls. */
const X: JobRoute = {
Expand Down Expand Up @@ -583,3 +591,58 @@ describe("ownVoices", () => {
await expect(ownVoices(5)).rejects.toMatchObject({ fix: "npx hyperframes auth login" });
});
});

describe("a project's job log in place of which a link was planted", () => {
const VICTIM = "victim bytes\n";
const planted = (linkJobLog: boolean) => {
const projectDir = mkdtempSync(join(tmpdir(), "hf-v3-planted-"));
const outside = mkdtempSync(join(tmpdir(), "hf-v3-outside-"));
const victim = join(outside, "heygen-jobs.jsonl");
writeFileSync(victim, VICTIM);
if (linkJobLog) {
mkdirSync(join(projectDir, ".hyperframes"));
symlinkSync(victim, join(projectDir, ".hyperframes/heygen-jobs.jsonl"));
} else {
symlinkSync(outside, join(projectDir, ".hyperframes"));
}
return { projectDir, victim };
};

for (const [what, linkJobLog] of [
["the job log", true],
["the .hyperframes folder", false],
] as const) {
it(`never appends a job or a voice pick through a link in place of ${what}`, async () => {
const { projectDir, victim } = planted(linkJobLog);
vi.stubGlobal("fetch", async () => reply(200, { data: { id: "j1", status: "completed" } }));
await expect(runJob(X, {}, "k1", { log: { projectDir, what: "a line" } })).rejects.toThrow(
/never written through/,
);
expect(() => keepVoice(projectDir, "en", { voice_id: "v1", name: "Ann" })).toThrow(
/never written through/,
);
expect(readFileSync(victim, "utf8")).toBe(VICTIM);
expect(
lstatSync(
join(projectDir, linkJobLog ? ".hyperframes/heygen-jobs.jsonl" : ".hyperframes"),
).isSymbolicLink(),
).toBe(true);
});
}

it("never appends to a job log hard-linked to a file outside the project", async () => {
const projectDir = mkdtempSync(join(tmpdir(), "hf-v3-planted-"));
mkdirSync(join(projectDir, ".hyperframes"));
const victim = join(mkdtempSync(join(tmpdir(), "hf-v3-outside-")), "victim");
writeFileSync(victim, VICTIM);
linkSync(victim, join(projectDir, ".hyperframes/heygen-jobs.jsonl"));
vi.stubGlobal("fetch", async () => reply(200, { data: { id: "j1", status: "completed" } }));
await expect(runJob(X, {}, "k1", { log: { projectDir, what: "a line" } })).rejects.toThrow(
/never written through/,
);
expect(() => keepVoice(projectDir, "en", { voice_id: "v1", name: "Ann" })).toThrow(
/never written through/,
);
expect(readFileSync(victim, "utf8")).toBe(VICTIM);
});
});
26 changes: 19 additions & 7 deletions packages/cli/src/heygen/v3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { resolveCredential } from "../auth/resolver.js";
import { refreshIfNeeded, resolveCloudAuthHeaders, resolveCloudBaseUrl } from "../cloud/auth.js";
import { HyperframesApiError, HyperframesCloudClient } from "../cloud/_gen/client.js";
import { Fix } from "../measure/media.js";
import { appendRecord } from "../utils/projectRecords.js";
import { creditLimit, creditsSpent } from "../media-use/lib/credit-limit.mjs";
import { cliCheckoutLink, pageUrl } from "./plan.js";

Expand Down Expand Up @@ -237,14 +238,24 @@ export interface JobLog {
what: string;
}

const JOB_LOG = "heygen-jobs.jsonl";

function appendJobLog(projectDir: string, line: Record<string, unknown>): void {
if (
!appendRecord(
projectDir,
JOB_LOG,
`${JSON.stringify({ at: new Date().toISOString(), ...line })}\n`,
)
)
throw new Fix(
`${join(projectDir, ".hyperframes", JOB_LOG)} could not be added to; a link or anything but a plain file there, or in place of .hyperframes, is never written through`,
"remove that link or file and run the same command again",
);
}

function log(entry: JobLog, record: Record<string, unknown>) {
if (!entry.projectDir) return;
const dir = join(entry.projectDir, ".hyperframes");
mkdirSync(dir, { recursive: true });
appendFileSync(
join(dir, "heygen-jobs.jsonl"),
`${JSON.stringify({ at: new Date().toISOString(), what: entry.what, ...record })}\n`,
);
if (entry.projectDir) appendJobLog(entry.projectDir, { what: entry.what, ...record });
}

export interface RunOptions {
Expand Down Expand Up @@ -420,6 +431,7 @@ export function keptVoice(projectDir: string | null, request: string): Voice | u
}

export function keepVoice(projectDir: string | null, request: string, voice: Voice): void {
if (projectDir) return appendJobLog(projectDir, { voice_pick: request, voice });
const file = picksFile(projectDir);
mkdirSync(dirname(file), { recursive: true });
appendFileSync(
Expand Down
9 changes: 3 additions & 6 deletions packages/cli/src/server/studioServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import type { HttpBindings } from "@hono/node-server";
import { Hono, type Context } from "hono";
import { streamSSE } from "hono/streaming";
import { realpath } from "@hyperframes/core";
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync, unlinkSync } from "node:fs";
import { existsSync, readFileSync, statSync, writeFileSync, unlinkSync } from "node:fs";
import { replaceFileAtomically } from "@hyperframes/core/atomic-file";
import { createHash } from "node:crypto";
import { fileURLToPath } from "node:url";
Expand Down Expand Up @@ -45,6 +45,7 @@ import {
} from "@hyperframes/studio-server/request-identity";
import { mountShareRoutes } from "./shareRoutes.js";
import { isDevMode } from "../utils/env.js";
import { recordFolder } from "../utils/projectRecords.js";
import { outsideAssetsAllowed } from "../utils/receivedRender.js";
import { insideHostApp } from "../utils/desktopApp.js";
import { runRenderSetupWorker } from "../utils/cancellableProcess.js";
Expand Down Expand Up @@ -467,11 +468,7 @@ function rewriteWrittenToHostViewport(projectDir: string, written: string[]): vo
}

function createStateFolderBeforeWatching(projectDir: string): void {
try {
mkdirSync(join(projectDir, ".hyperframes"), { recursive: true });
} catch {
return;
}
recordFolder(projectDir, "");
}

export function createStudioServer(options: StudioServerOptions): StudioServer {
Expand Down
15 changes: 6 additions & 9 deletions packages/cli/src/share/render.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { randomUUID } from "node:crypto";
import { existsSync, readFileSync, realpathSync } from "node:fs";
import { mkdir, writeFile, rename, rm } from "node:fs/promises";
import { mkdir, rm } from "node:fs/promises";
import { join } from "node:path";
import { projectFingerprint, shareSourceFingerprint } from "@hyperframes/share";
import { writeRecord } from "../utils/projectRecords.js";

export const shareContentFingerprint = shareSourceFingerprint;

Expand Down Expand Up @@ -76,8 +77,6 @@ export async function prepareShareRender(dir: string): Promise<void> {
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, {
Expand All @@ -103,13 +102,11 @@ export async function prepareShareRender(dir: string): Promise<void> {
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, contentFingerprint: content }),
);
await rename(temporary, target);
const record = { id, path: output, fingerprint: before, contentFingerprint: content };
if (!writeRecord(dir, "share-render.json", JSON.stringify(record)))
throw new Error("Sharing state must stay inside this project, without symlinks.");
} catch (error) {
await Promise.allSettled([rm(output, { force: true }), rm(temporary, { force: true })]);
await rm(output, { force: true });
throw error;
}
}
3 changes: 1 addition & 2 deletions packages/cli/src/utils/checkBrowser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { logCheckProgress } from "./checkProgress.js";
import { BrowserCleanupError, closeManagedBrowser, onStopSignal } from "../browser/launch.js";
import { collectMotionBlurDrafts, dropMotionBlurConsoleEcho } from "./checkMotionBlur.js";
import { checkSnapshotDirectory } from "./checkSnapshotDirectory.js";
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import { existsSync, writeFileSync } from "node:fs";
import os from "node:os";
import { join, resolve } from "node:path";
import type { Browser, Page } from "puppeteer-core";
Expand Down Expand Up @@ -789,7 +789,6 @@ async function withFindingCapturePage<T>(
chromeBrowser = session.browser;
await waitForPreferredSeekTarget(session.page);
const snapshotDir = checkSnapshotDirectory(project.dir);
mkdirSync(snapshotDir, { recursive: true });
return await capture(session.page, snapshotDir, server);
} catch (error) {
failure = { kind: "failed", error };
Expand Down
3 changes: 1 addition & 2 deletions packages/cli/src/utils/checkPipeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import {
findingFrameRequests,
} from "./checkFindingFrames.js";
export { selectFindingFrames } from "./checkFindingFrames.js";
import { mkdirSync, writeFileSync } from "node:fs";
import { writeFileSync } from "node:fs";
import { readFile } from "node:fs/promises";
import type { PrelaunchedBrowser } from "../capture/captureCompositionFrame.js";
import { join, relative } from "node:path";
Expand Down Expand Up @@ -2415,7 +2415,6 @@ async function writeSnapshot(
pngBase64: string,
): Promise<string> {
const snapshotDir = checkSnapshotDirectory(projectDir);
mkdirSync(snapshotDir, { recursive: true });
const filename = `frame-${String(index).padStart(2, "0")}-at-${time.toFixed(1)}s.png`;
const path = join(snapshotDir, filename);
writeFileSync(path, Buffer.from(pngBase64, "base64"));
Expand Down
3 changes: 3 additions & 0 deletions packages/cli/src/utils/checkSnapshotDirectory.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { resolve } from "node:path";
import { artifactDirectory, finishSnapshotRun } from "@hyperframes/studio-server/history";
import { projectFolder } from "./projectRecords.js";

const runDirectories = new Map<string, string>();
const activeChecks = new Map<string, number>();
Expand All @@ -16,6 +17,8 @@ export function checkSnapshotDirectory(projectDir: string): string {
directory = artifactDirectory(project, "snapshots");
runDirectories.set(project, directory);
}
if (!projectFolder(project, directory))
throw new Error(`${directory} is reached through a link or a file; remove it and run again`);
return directory;
}

Expand Down
Loading
Loading