Files
hyperframes/packages/cli/src/utils/publishProject.test.ts
T
Michael WangandClaude Opus 5.5 c96ff540c4 fix(cli): harden lambda destroy, snapshot media, upgrade and project file serving (#7509)
* fix(cli): lambda destroy runs SAM in a private folder and acts only on the selected stack

- sam delete outside a checkout runs in a fresh private temp folder,
  removed afterwards, instead of the shared temp directory.
- A stack state file must name the stack it is selected by.
- destroy and deploy derive the video repository name from the stack
  name instead of trusting the recorded value.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cli): snapshot keeps remote clips in a private folder and reads only allowed URLs

- A video URL the download policy refuses (plain http, or a private,
  loopback or link-local host) is no longer handed to FFmpeg; the clip
  is skipped instead, as render does.
- Remote clips are cached in a per-user, owner-only temp folder; a
  folder open to other users is never reused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cli): upgrade --project writes package.json through an exclusive temp file

The rewrite now uses the shared atomic replace, which creates a fresh,
unpredictable sibling with exclusive creation, so an existing
package.json.tmp entry is never written through.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cli): keep env files, Git data and tool records out of served and uploaded projects

- play and present answer 404 for .env files, .git and the tools'
  private .hyperframes records, as Studio's preview does for the records.
- publish and cloud render never stage an env file or tool record, even
  when markup references it, and never pull in an env file from outside
  the project.
- Cloud site uploads (Lambda and Cloud Run deploySite) leave env files out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cli): lambda commands accept a state file whose stack name differs only in case

On a case-insensitive disk, deploy --stack-name=Demo and --stack-name=demo share one
state file, so a name that matches apart from case is the same stack the user deployed
and keeps working as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cli): snapshot's fallback media folder uses createStagingDir

The repository check forbids bare mkdtemp beside a caller-supplied path, because it
fails past 260 characters on Windows. Also trims a comment so the new helper file stays
within its package's comment share.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cli): snapshot never hands FFmpeg a remote URL

FFmpeg follows redirects and resolves hosts on its own, so a clip the downloader could
not fetch must not reach it as a URL. Snapshot now leaves such a clip out and warns,
as render does. A fallback media folder is removed when the process exits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cli): cover .envrc, .env-local and .env_prod, and test present's private-file 404

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 20:00:58 +00:00

1623 lines
60 KiB
TypeScript

import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
import {
mkdtempSync,
mkdirSync,
readFileSync,
renameSync,
rmSync,
utimesSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, posix, relative } from "node:path";
import AdmZip from "adm-zip";
import { parseHTML } from "linkedom";
const authMocks = vi.hoisted(() => ({
tryResolveCredential: vi.fn(),
}));
vi.mock("../auth/index.js", () => ({
tryResolveCredential: authMocks.tryResolveCredential,
}));
const linkMocks = vi.hoisted(() => ({
writeProjectLink: vi.fn(),
}));
vi.mock("./projectLink.js", () => ({
writeProjectLink: linkMocks.writeProjectLink,
}));
const oauthMocks = vi.hoisted(() => ({
refreshTokens: vi.fn(),
}));
vi.mock("../auth/oauth.js", () => ({
refreshTokens: oauthMocks.refreshTokens,
}));
import { ErrRefreshFailed } from "../auth/errors.js";
import { setupTempAuthEnv } from "../auth/_test-utils.js";
import { writeStore } from "../auth/store.js";
import {
buildPublishFileMap,
createPublishArchive,
getPublishApiBaseUrl,
localizeExternalAssets,
publishProjectArchive,
readStaged,
stagePublishFiles,
uploadTimeoutMs,
zipPublishFileMap,
} from "./publishProject.js";
function makeProjectDir(): string {
return mkdtempSync(join(tmpdir(), "hf-publish-"));
}
/** Writes an external asset and returns its path relative to `fromDir`, POSIX-slashed. */
function stageExternalAsset(
extDir: string,
fromDir: string,
filename: string,
content: string,
): string {
writeFileSync(join(extDir, filename), content, "utf-8");
return relative(fromDir, join(extDir, filename)).replaceAll("\\", "/");
}
/** A single-entry files map for `localizeExternalAssets`, keyed on index.html. */
function indexHtmlFiles(html: string): Map<string, Buffer> {
const files = new Map<string, Buffer>();
files.set("index.html", Buffer.from(html, "utf-8"));
return files;
}
/**
* Stages one external asset in a fresh project/ext dir pair, builds the
* files map from it via `buildFiles`, runs `localizeExternalAssets`, and
* cleans up both dirs. Covers the single-external-asset test shape shared
* by most `localizeExternalAssets` cases.
*/
function localizeSingleAsset(
assetName: string,
assetContent: string,
buildFiles: (relToExt: string, projectDir: string) => Map<string, Buffer>,
): { count: number; files: Map<string, Buffer>; relToExt: string } {
const projectDir = makeProjectDir();
const extDir = mkdtempSync(join(tmpdir(), "hf-ext-"));
try {
const relToExt = stageExternalAsset(extDir, projectDir, assetName, assetContent);
const files = buildFiles(relToExt, projectDir);
const count = localizeExternalAssets(projectDir, files);
return { count, files, relToExt };
} finally {
rmSync(projectDir, { recursive: true, force: true });
rmSync(extDir, { recursive: true, force: true });
}
}
/** Runs `localizeExternalAssets`, asserts nothing was rewritten, and returns the (unchanged) index.html. */
function expectNoLocalization(projectDir: string, files: Map<string, Buffer>): string {
const count = localizeExternalAssets(projectDir, files);
expect(count).toBe(0);
return files.get("index.html")!.toString("utf-8");
}
/** Asserts a `localizeSingleAsset` result rewrote index.html exactly once, and returns it. */
function expectLocalizedHtml(result: {
count: number;
files: Map<string, Buffer>;
relToExt: string;
}): string {
expect(result.count).toBe(1);
const rewrittenHtml = result.files.get("index.html")!.toString("utf-8");
expect(rewrittenHtml).toContain("_ext/");
expect(rewrittenHtml).not.toContain(result.relToExt);
return rewrittenHtml;
}
/** The staged `/publish/upload` success response, overridable per test. */
function uploadResponse(overrides?: Record<string, unknown>): Response {
return new Response(
JSON.stringify({
data: {
upload_url: "https://s3.example.com/upload",
upload_key: "ephemeral_store/hyperframes/project_uploads/upload-1/demo.zip",
upload_headers: { "content-type": "application/zip" },
content_type: "application/zip",
...overrides,
},
}),
{ status: 200 },
);
}
/** The `/publish/complete` (or legacy `/publish`) success response, overridable per test. */
function publishedResponse(overrides?: Record<string, unknown>): Response {
return new Response(
JSON.stringify({
data: {
project_id: "hfp_123",
title: "demo",
file_count: 1,
url: "https://hyperframes.dev/p/hfp_123",
claim_token: "claim-token",
...overrides,
},
}),
{ status: 200 },
);
}
/** What the server returns when it accepted the credential and owns the project. */
const OWNED = { claim_token: "", claimed: true };
/** Full staged flow: upload, S3 PUT, complete. */
function stagedFetch(completeData?: Record<string, unknown>, uploadData?: Record<string, unknown>) {
return vi
.fn()
.mockResolvedValueOnce(uploadResponse(uploadData))
.mockResolvedValueOnce(new Response(null, { status: 200 }))
.mockResolvedValueOnce(publishedResponse(completeData));
}
/** Legacy multipart flow: staged upload 404s, falls back to direct publish. */
function directFetch(completeData?: Record<string, unknown>) {
return vi
.fn()
.mockResolvedValueOnce(new Response("not found", { status: 404 }))
.mockResolvedValueOnce(publishedResponse(completeData));
}
function networkFailure(
code: string,
message: string,
metadata: Record<string, unknown> = {},
): TypeError {
return new TypeError("fetch failed", {
cause: Object.assign(new Error(message), { code, ...metadata }),
});
}
/** Asserts the Nth fetch call, always requiring an AbortSignal alongside the given init. */
function expectFetchCall(
fetchMock: ReturnType<typeof vi.fn>,
n: number,
url: string,
init: Record<string, unknown>,
): void {
expect(fetchMock).toHaveBeenNthCalledWith(
n,
url,
expect.objectContaining({ signal: expect.any(AbortSignal), ...init }),
);
}
/** Resolves `tryResolveCredential` to a stubbed OAuth token for authenticated-request tests. */
function withOAuthCredential(): void {
authMocks.tryResolveCredential.mockResolvedValue({
type: "oauth",
access_token: "test-token",
source: "file_json",
refreshable: false,
});
}
/** Asserts the given fetch call carried the stubbed bearer token. */
function expectAuthorizedHeaders(fetchMock: ReturnType<typeof vi.fn>, callIndex: number): void {
expect(fetchMock.mock.calls[callIndex]![1].headers).toEqual(
expect.objectContaining({ authorization: "Bearer test-token" }),
);
}
/** Stubs an OAuth credential and fetch, then publishes a minimal project through `dir`. */
async function runAuthenticatedPublish(
fetchMock: ReturnType<typeof vi.fn>,
dir: string,
): Promise<void> {
withOAuthCredential();
vi.stubGlobal("fetch", fetchMock);
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
await publishProjectArchive(dir);
}
describe("createPublishArchive", () => {
it.each([
{ filename: "poster art.svg", reference: "poster%20art.svg" },
{ filename: "封面.svg", reference: "%E5%B0%81%E9%9D%A2.svg" },
{ filename: "100%.svg", reference: "100%.svg" },
{ filename: "poster%20art.svg", reference: "poster%20art.svg" },
{ filename: "poster#art.svg", reference: "poster%23art.svg" },
{ filename: "poster#art.svg", reference: "poster#art.svg" },
])("archives $filename referenced as $reference", ({ filename, reference }) => {
const projectDir = makeProjectDir();
const extDir = mkdtempSync(join(tmpdir(), "hf-ext-"));
try {
const entryPath = "compositions/scene.html";
const htmlDir = join(projectDir, dirname(entryPath));
mkdirSync(htmlDir, { recursive: true });
stageExternalAsset(extDir, htmlDir, filename, "POSTER_DATA");
if (reference !== filename) {
stageExternalAsset(extDir, htmlDir, reference, "LITERAL_DECOY");
}
const assetPath = relative(htmlDir, join(extDir, reference)).replaceAll("\\", "/");
const html = `<html><body><img src="${assetPath}"><video src="../clip.mp4" poster="${assetPath}"></video></body></html>`;
writeFileSync(join(projectDir, "index.html"), "<html></html>");
writeFileSync(join(projectDir, entryPath), html);
writeFileSync(join(projectDir, "clip.mp4"), "MP4_DATA");
const archive = createPublishArchive(projectDir);
const zip = new AdmZip(archive.buffer);
const { document } = parseHTML(zip.readAsText(entryPath));
const src = document.querySelector("img")?.getAttribute("src");
if (!src) throw new Error("Archived image has no src");
expect(document.querySelector("video")?.getAttribute("poster")).toBe(src);
const url = new URL(src, `https://archive.example/${entryPath}`);
expect(url.hash).toBe("");
expect(url.search).toBe("");
const archivedPath = decodeURIComponent(url.pathname.slice(1));
expect(archivedPath).toMatch(/^_ext\//);
expect(posix.basename(archivedPath)).toBe(filename);
expect(zip.readFile(archivedPath)).toEqual(Buffer.from("POSTER_DATA"));
expect(archive.fileCount).toBe(4);
expect(readFileSync(join(projectDir, entryPath), "utf-8")).toBe(html);
} finally {
rmSync(projectDir, { recursive: true, force: true });
rmSync(extDir, { recursive: true, force: true });
}
});
it.each(["index.html", "compositions/scene.html"])(
"includes external video posters referenced from %s",
(entryPath) => {
const projectDir = makeProjectDir();
const extDir = mkdtempSync(join(tmpdir(), "hf-ext-"));
try {
const htmlDir = join(projectDir, dirname(entryPath));
mkdirSync(htmlDir, { recursive: true });
if (entryPath !== "index.html") {
writeFileSync(join(projectDir, "index.html"), "<html></html>");
}
const posterPath = stageExternalAsset(extDir, htmlDir, "poster.png", "PNG_DATA");
const videoPath = posix.relative(posix.dirname(entryPath), "clip.mp4");
const html = `<html><body><video src="${videoPath}" poster="${posterPath}"></video></body></html>`;
writeFileSync(join(projectDir, entryPath), html);
writeFileSync(join(projectDir, "clip.mp4"), "MP4_DATA");
const archive = createPublishArchive(projectDir);
const zip = new AdmZip(archive.buffer);
const posterEntries = zip
.getEntries()
.filter((entry) => entry.entryName.startsWith("_ext/") && entry.name === "poster.png");
expect(posterEntries).toHaveLength(1);
const archivedPoster = posterEntries[0]!;
expect(archivedPoster.getData()).toEqual(Buffer.from("PNG_DATA"));
expect(zip.readAsText(entryPath)).toContain(
`poster="${posix.relative(posix.dirname(entryPath), archivedPoster.entryName)}"`,
);
expect(zip.readAsText(entryPath)).toContain(`src="${videoPath}"`);
expect(archive.fileCount).toBe(entryPath === "index.html" ? 3 : 4);
expect(readFileSync(join(projectDir, entryPath), "utf-8")).toBe(html);
} finally {
rmSync(projectDir, { recursive: true, force: true });
rmSync(extDir, { recursive: true, force: true });
}
},
);
it("preserves internal, remote, and inline video posters", () => {
const projectDir = makeProjectDir();
try {
const posters = [
"poster.png",
"poster%20art.png",
"https://cdn.example.com/poster.png",
"https://cdn.example.com/poster%20art.png",
"data:image/png;base64,AA==",
];
const html = `<html><body>${posters.map((poster) => `<video src="clip.mp4" poster="${poster}"></video>`).join("")}</body></html>`;
writeFileSync(join(projectDir, "index.html"), html);
writeFileSync(join(projectDir, "poster.png"), "PNG_DATA");
writeFileSync(join(projectDir, "poster art.png"), "ENCODED_PNG_DATA");
writeFileSync(join(projectDir, "clip.mp4"), "MP4_DATA");
const archive = createPublishArchive(projectDir);
const zip = new AdmZip(archive.buffer);
expect(archive.fileCount).toBe(4);
expect(zip.readAsText("index.html")).toBe(html);
expect(zip.getEntries().some((entry) => entry.entryName.startsWith("_ext/"))).toBe(false);
} finally {
rmSync(projectDir, { recursive: true, force: true });
}
});
it("packages the project and skips hidden files and node_modules", () => {
const dir = makeProjectDir();
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
mkdirSync(join(dir, "assets"));
writeFileSync(join(dir, "assets/logo.svg"), "<svg />", "utf-8");
mkdirSync(join(dir, ".git"));
writeFileSync(join(dir, ".env"), "SECRET=1", "utf-8");
mkdirSync(join(dir, "node_modules"));
writeFileSync(join(dir, "node_modules/ignored.js"), "console.log('ignore')", "utf-8");
const archive = createPublishArchive(dir);
expect(archive.fileCount).toBe(2);
expect(archive.buffer.byteLength).toBeGreaterThan(0);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("skips root render outputs but keeps same-named nested source directories", () => {
const dir = makeProjectDir();
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
mkdirSync(join(dir, "renders"));
writeFileSync(join(dir, "renders", "old.mp4"), "render-output", "utf-8");
mkdirSync(join(dir, "snapshots"));
writeFileSync(join(dir, "snapshots", "frame.png"), "snapshot-output", "utf-8");
mkdirSync(join(dir, "assets", "renders"), { recursive: true });
writeFileSync(join(dir, "assets", "renders", "source.mp4"), "source", "utf-8");
const zip = new AdmZip(createPublishArchive(dir).buffer);
const entries = zip.getEntries().map((entry) => entry.entryName);
expect(entries).toContain("assets/renders/source.mp4");
expect(entries).not.toContain("renders/old.mp4");
expect(entries).not.toContain("snapshots/frame.png");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("applies gitignore-style rules from .hyperframesignore", () => {
const dir = makeProjectDir();
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
mkdirSync(join(dir, "exports"));
writeFileSync(join(dir, "exports", "draft.mp4"), "draft", "utf-8");
mkdirSync(join(dir, "assets"));
writeFileSync(join(dir, "assets", "discard.psd"), "discard", "utf-8");
writeFileSync(join(dir, "assets", "keep.psd"), "keep", "utf-8");
writeFileSync(
join(dir, ".hyperframesignore"),
["# Generated source files", "/exports/", "*.psd", "!assets/keep.psd", ""].join("\n"),
"utf-8",
);
const zip = new AdmZip(createPublishArchive(dir).buffer);
const entries = zip.getEntries().map((entry) => entry.entryName);
expect(entries).toContain("assets/keep.psd");
expect(entries).not.toContain("exports/draft.mp4");
expect(entries).not.toContain("assets/discard.psd");
expect(entries).not.toContain(".hyperframesignore");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("allows .hyperframesignore to re-include a default output directory", () => {
const dir = makeProjectDir();
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
mkdirSync(join(dir, "snapshots"));
writeFileSync(join(dir, "snapshots", "reference.png"), "reference", "utf-8");
writeFileSync(join(dir, ".hyperframesignore"), "!/snapshots/\n", "utf-8");
const zip = new AdmZip(createPublishArchive(dir).buffer);
expect(zip.getEntries().map((entry) => entry.entryName)).toContain("snapshots/reference.png");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("allows .hyperframesignore to re-include a hidden directory", () => {
const dir = makeProjectDir();
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
mkdirSync(join(dir, ".media"));
writeFileSync(join(dir, ".media", "logo.png"), "logo", "utf-8");
writeFileSync(join(dir, ".hyperframesignore"), "!/.media/\n!/.media/**\n", "utf-8");
const zip = new AdmZip(createPublishArchive(dir).buffer);
expect(zip.getEntries().map((entry) => entry.entryName)).toContain(".media/logo.png");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("still excludes an unmatched hidden directory by default", () => {
const dir = makeProjectDir();
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
mkdirSync(join(dir, ".cache"));
writeFileSync(join(dir, ".cache", "entry.bin"), "cache", "utf-8");
const zip = new AdmZip(createPublishArchive(dir).buffer);
expect(zip.getEntries().map((entry) => entry.entryName)).not.toContain(".cache/entry.bin");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("fails clearly when .hyperframesignore excludes index.html", () => {
const dir = makeProjectDir();
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
writeFileSync(join(dir, ".hyperframesignore"), "/index.html\n", "utf-8");
expect(() => createPublishArchive(dir)).toThrow(
"Project archive must include index.html at the root. Check that .hyperframesignore does not exclude it.",
);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});
describe("createPublishArchive (U6 cloud-render regression guard)", () => {
// `cloud/render.ts` (`maybeUploadProject`) calls `createPublishArchive`
// directly and must never see baked proxies (R2): this pins that
// `createPublishArchive` is exactly the thin composition of
// `buildPublishFileMap` + `zipPublishFileMap` with no baking hook, and that
// a local video asset's original bytes/HTML pass through unmodified.
it("zips the same files to the same bytes across a two-second boundary", () => {
// The flake this pins: adm-zip stamps each entry with `new Date()` as it is
// constructed, and a ZIP timestamp resolves to two seconds — so two runs
// either side of a boundary produced different bytes for identical content.
// The byte-identity assertion below could only ever fail this way, and did,
// rarely enough to survive since July.
//
// Moving the clock is what reproduces it: back-to-back builds land in the
// same bucket almost always, which is exactly why it hid.
const dir = makeProjectDir();
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
vi.useFakeTimers();
try {
vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z"));
const first = createPublishArchive(dir);
vi.setSystemTime(new Date("2026-01-01T00:00:03.000Z"));
const second = createPublishArchive(dir);
expect(first.buffer.equals(second.buffer)).toBe(true);
} finally {
vi.useRealTimers();
}
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("keeps a source video byte-identical and excludes proxies from the cloud-render archive", () => {
const dir = makeProjectDir();
try {
writeFileSync(
join(dir, "index.html"),
`<html><body><video src="clip.mp4"></video></body></html>`,
"utf-8",
);
const originalVideo = Buffer.from("original-video-bytes");
writeFileSync(join(dir, "clip.mp4"), originalVideo);
const direct = createPublishArchive(dir);
const composed = zipPublishFileMap(buildPublishFileMap(dir));
expect(direct.buffer.equals(composed.buffer)).toBe(true);
expect(direct.fileCount).toBe(composed.fileCount);
const zip = new AdmZip(direct.buffer);
const entries = zip.getEntries().map((e) => e.entryName);
expect(entries).toEqual(expect.arrayContaining(["index.html", "clip.mp4"]));
expect(entries.some((e) => e.startsWith("_proxy/"))).toBe(false);
expect(zip.readFile("clip.mp4")?.equals(originalVideo)).toBe(true);
expect(zip.readAsText("index.html")).toContain('src="clip.mp4"');
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});
describe("localizeExternalAssets", () => {
it("copies external src/href assets and rewrites HTML paths", () => {
const result = localizeSingleAsset("logo.png", "PNG_DATA", (rel) =>
indexHtmlFiles(`<html><body><img src="${rel}"></body></html>`),
);
expectLocalizedHtml(result);
const extEntries = [...result.files.keys()].filter((k) => k.startsWith("_ext/"));
expect(extEntries).toHaveLength(1);
expect(result.files.get(extEntries[0]!)!.toString("utf-8")).toBe("PNG_DATA");
});
it("rewrites CSS url() in <style> blocks", () => {
const result = localizeSingleAsset("bg.jpg", "JPEG_DATA", (rel) =>
indexHtmlFiles(
`<html><head><style>body { background: url("${rel}"); }</style></head></html>`,
),
);
const rewrittenHtml = expectLocalizedHtml(result);
expect(rewrittenHtml).toContain("url(");
});
});
describe("localizeExternalAssets", () => {
it("rewrites url() in standalone CSS files", () => {
const { count, files, relToExt } = localizeSingleAsset("font.woff2", "FONT_DATA", (rel) => {
const files = indexHtmlFiles("<html></html>");
files.set("styles.css", Buffer.from(`@font-face { src: url("${rel}"); }`, "utf-8"));
return files;
});
expect(count).toBe(1);
const rewrittenCss = files.get("styles.css")!.toString("utf-8");
expect(rewrittenCss).toContain("_ext/");
expect(rewrittenCss).not.toContain(relToExt);
});
it("leaves internal assets unchanged", () => {
const projectDir = makeProjectDir();
try {
mkdirSync(join(projectDir, "assets"));
writeFileSync(join(projectDir, "assets", "logo.svg"), "<svg/>", "utf-8");
const files = indexHtmlFiles(`<html><body><img src="assets/logo.svg"></body></html>`);
files.set("assets/logo.svg", Buffer.from("<svg/>", "utf-8"));
const rewrittenHtml = expectNoLocalization(projectDir, files);
expect(rewrittenHtml).toContain('src="assets/logo.svg"');
expect([...files.keys()].filter((k) => k.startsWith("_ext/"))).toHaveLength(0);
} finally {
rmSync(projectDir, { recursive: true, force: true });
}
});
});
describe("localizeExternalAssets", () => {
it("leaves remote URLs unchanged", () => {
const projectDir = makeProjectDir();
try {
const files = indexHtmlFiles(
`<html><body><img src="https://cdn.example.com/logo.png"><video src="http://cdn.example.com/vid.mp4"></video></body></html>`,
);
const rewrittenHtml = expectNoLocalization(projectDir, files);
expect(rewrittenHtml).toContain("https://cdn.example.com/logo.png");
expect(rewrittenHtml).toContain("http://cdn.example.com/vid.mp4");
} finally {
rmSync(projectDir, { recursive: true, force: true });
}
});
it("no-op when no external assets exist", () => {
const projectDir = makeProjectDir();
try {
const files = indexHtmlFiles(`<html><body><p>Hello</p></body></html>`);
expectNoLocalization(projectDir, files);
expect(files.size).toBe(1);
} finally {
rmSync(projectDir, { recursive: true, force: true });
}
});
it("skips references to non-existent external files", () => {
const projectDir = makeProjectDir();
try {
const files = indexHtmlFiles(`<html><body><img src="../nonexistent/file.png"></body></html>`);
const rewrittenHtml = expectNoLocalization(projectDir, files);
expect(rewrittenHtml).toContain("../nonexistent/file.png");
} finally {
rmSync(projectDir, { recursive: true, force: true });
}
});
});
describe("localizeExternalAssets", () => {
it("deduplicates: same external asset referenced from multiple files", () => {
const { count, files } = localizeSingleAsset("shared.png", "SHARED", (rel, projectDir) => {
const files = indexHtmlFiles(`<html><body><img src="${rel}"></body></html>`);
mkdirSync(join(projectDir, "compositions"));
files.set(
"compositions/scene.html",
Buffer.from(`<html><body><img src="../${rel}"></body></html>`, "utf-8"),
);
return files;
});
expect(count).toBe(1);
const extEntries = [...files.keys()].filter((k) => k.startsWith("_ext/"));
expect(extEntries).toHaveLength(1);
});
it("handles sub-composition HTML with external refs", () => {
const projectDir = makeProjectDir();
const extDir = mkdtempSync(join(tmpdir(), "hf-ext-"));
try {
mkdirSync(join(projectDir, "compositions"));
const relFromComps = stageExternalAsset(
extDir,
join(projectDir, "compositions"),
"overlay.png",
"OVERLAY",
);
const files = indexHtmlFiles("<html></html>");
files.set(
"compositions/scene.html",
Buffer.from(`<html><body><img src="${relFromComps}"></body></html>`, "utf-8"),
);
const count = localizeExternalAssets(projectDir, files);
expect(count).toBe(1);
const rewritten = files.get("compositions/scene.html")!.toString("utf-8");
expect(rewritten).toContain("_ext/");
expect(rewritten).not.toContain(relFromComps);
} finally {
rmSync(projectDir, { recursive: true, force: true });
rmSync(extDir, { recursive: true, force: true });
}
});
});
describe("localizeExternalAssets", () => {
it("rewrites inline style url() references", () => {
const result = localizeSingleAsset("bg.jpg", "JPEG_DATA", (rel) =>
indexHtmlFiles(
`<html><body><div style="background-image: url('${rel}')"></div></body></html>`,
),
);
expectLocalizedHtml(result);
});
it("createPublishArchive includes localized external assets", () => {
const projectDir = makeProjectDir();
const extDir = mkdtempSync(join(tmpdir(), "hf-ext-"));
try {
const relToExt = stageExternalAsset(extDir, projectDir, "video.mp4", "MP4_DATA");
writeFileSync(
join(projectDir, "index.html"),
`<html><body><video src="${relToExt}"></video></body></html>`,
"utf-8",
);
const archive = createPublishArchive(projectDir);
expect(archive.fileCount).toBe(2);
const zip = new AdmZip(archive.buffer);
const entries = zip.getEntries().map((e) => e.entryName);
expect(entries).toContain("index.html");
expect(entries.some((e) => e.startsWith("_ext/") && e.endsWith("video.mp4"))).toBe(true);
const indexHtml = zip.readAsText("index.html");
expect(indexHtml).toContain("_ext/");
expect(indexHtml).not.toContain(relToExt);
} finally {
rmSync(projectDir, { recursive: true, force: true });
rmSync(extDir, { recursive: true, force: true });
}
});
});
describe("uploadTimeoutMs", () => {
it("returns the minimum timeout for small files", () => {
expect(uploadTimeoutMs(0)).toBe(120_000);
expect(uploadTimeoutMs(50 * 1024 * 1024)).toBe(120_000);
});
it("scales above the floor for large files", () => {
expect(uploadTimeoutMs(64 * 1024 * 1024)).toBeGreaterThan(120_000);
expect(uploadTimeoutMs(500 * 1024 * 1024)).toBeGreaterThan(900_000);
});
it("returns an integer", () => {
expect(Number.isInteger(uploadTimeoutMs(123_456))).toBe(true);
});
});
// Shared across every `publishProjectArchive` group below (file-scoped, not
// nested in a describe) so the reset logic isn't duplicated per group.
beforeEach(() => {
authMocks.tryResolveCredential.mockReset().mockResolvedValue(null);
oauthMocks.refreshTokens.mockReset();
linkMocks.writeProjectLink.mockReset();
vi.stubEnv("HYPERFRAMES_PUBLISHED_PROJECTS_API_URL", "");
vi.stubEnv("HEYGEN_API_URL", "");
vi.stubEnv("HYPERFRAMES_ENV", "prod");
});
afterEach(() => {
vi.unstubAllGlobals();
vi.unstubAllEnvs();
});
const jsonHeaders = { "content-type": "application/json" };
const signedStagedS3Url =
"https://s3.example.com/upload?X-Amz-SignedHeaders=content-length;content-type;host;x-amz-server-side-encryption";
describe("publishProjectArchive", () => {
it("takes the publish service from the environment under HYPERFRAMES_ENV=dev", () => {
vi.stubEnv("HYPERFRAMES_ENV", "dev");
expect(getPublishApiBaseUrl()).toBe("https://api2.heygen.com");
vi.stubEnv("HEYGEN_API_URL", "https://api2.example.test");
expect(getPublishApiBaseUrl()).toBe("https://api2.example.test");
});
it("uploads through the staged publish flow and returns the stable project URL", async () => {
const dir = makeProjectDir();
const fetchMock = stagedFetch(
{ file_count: 2 },
{
upload_url: signedStagedS3Url,
upload_headers: {
"content-type": "application/zip",
"x-amz-server-side-encryption": "AES256",
},
},
);
vi.stubGlobal("fetch", fetchMock);
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
writeFileSync(join(dir, "styles.css"), "body {}", "utf-8");
const result = await publishProjectArchive(dir);
expect(getPublishApiBaseUrl()).toBe("https://api2.heygen.com");
expect(result).toMatchObject({
projectId: "hfp_123",
url: "https://hyperframes.dev/p/hfp_123",
});
expect(fetchMock).toHaveBeenCalledTimes(3);
expectFetchCall(
fetchMock,
1,
"https://api2.heygen.com/v1/hyperframes/projects/publish/upload",
{
method: "POST",
headers: jsonHeaders,
},
);
expectFetchCall(fetchMock, 2, signedStagedS3Url, {
method: "PUT",
headers: {
"content-length": expect.any(String),
"content-type": "application/zip",
"x-amz-server-side-encryption": "AES256",
},
});
expectFetchCall(
fetchMock,
3,
"https://api2.heygen.com/v1/hyperframes/projects/publish/complete",
{
method: "POST",
headers: jsonHeaders,
},
);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});
describe("publishProjectArchive", () => {
it("keeps server-sent upload headers in any case without adding duplicates", async () => {
const dir = makeProjectDir();
const serverHeaders = {
"Content-Type": "application/zip",
"Content-Length": "123",
"X-Amz-Server-Side-Encryption": "AES256",
};
const fetchMock = stagedFetch(
{ file_count: 1 },
{ upload_url: signedStagedS3Url, upload_headers: serverHeaders },
);
vi.stubGlobal("fetch", fetchMock);
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
await publishProjectArchive(dir);
expect(fetchMock.mock.calls[1]![1].headers).toEqual(serverHeaders);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});
describe("publishProjectArchive", () => {
it("authenticates staged metadata requests but not the presigned S3 upload", async () => {
const dir = makeProjectDir();
const fetchMock = stagedFetch(OWNED);
try {
await runAuthenticatedPublish(fetchMock, dir);
expect(authMocks.tryResolveCredential).toHaveBeenCalledTimes(1);
expectAuthorizedHeaders(fetchMock, 0);
expect(fetchMock.mock.calls[1]![1].headers).not.toHaveProperty("authorization");
expectAuthorizedHeaders(fetchMock, 2);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("authenticates the direct fallback request", async () => {
const dir = makeProjectDir();
const fetchMock = directFetch(OWNED);
try {
await runAuthenticatedPublish(fetchMock, dir);
expect(authMocks.tryResolveCredential).toHaveBeenCalledTimes(1);
expectAuthorizedHeaders(fetchMock, 0);
expectAuthorizedHeaders(fetchMock, 1);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});
describe("publishProjectArchive", () => {
it("falls back to the legacy multipart endpoint when staged publish is not deployed", async () => {
const dir = makeProjectDir();
const fetchMock = directFetch({ file_count: 2 });
vi.stubGlobal("fetch", fetchMock);
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
const result = await publishProjectArchive(dir);
expect(result.projectId).toBe("hfp_123");
expect(fetchMock).toHaveBeenCalledTimes(2);
expectFetchCall(fetchMock, 2, "https://api2.heygen.com/v1/hyperframes/projects/publish", {
method: "POST",
headers: {},
});
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("sends is_public in the staged complete body only when public is requested", async () => {
const dir = makeProjectDir();
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
const publicFetch = stagedFetch();
vi.stubGlobal("fetch", publicFetch);
await publishProjectArchive(dir, { public: true });
const publicCompleteBody = JSON.parse(publicFetch.mock.calls[2]![1].body);
expect(publicCompleteBody.is_public).toBe(true);
const defaultFetch = stagedFetch();
vi.stubGlobal("fetch", defaultFetch);
await publishProjectArchive(dir);
const defaultCompleteBody = JSON.parse(defaultFetch.mock.calls[2]![1].body);
expect(defaultCompleteBody).not.toHaveProperty("is_public");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});
describe("publishProjectArchive", () => {
it("sends is_public in the direct multipart form only when public is requested", async () => {
const dir = makeProjectDir();
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
const publicFetch = directFetch();
vi.stubGlobal("fetch", publicFetch);
await publishProjectArchive(dir, { public: true });
const publicForm = publicFetch.mock.calls[1]![1].body as FormData;
expect(publicForm.get("is_public")).toBe("true");
const defaultFetch = directFetch();
vi.stubGlobal("fetch", defaultFetch);
await publishProjectArchive(dir);
const defaultForm = defaultFetch.mock.calls[1]![1].body as FormData;
expect(defaultForm.get("is_public")).toBeNull();
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("does not fall back to multipart when a staged S3 upload fails", async () => {
const dir = makeProjectDir();
const fetchMock = vi
.fn()
.mockResolvedValueOnce(
uploadResponse({
upload_headers: {
"content-type": "application/zip",
"x-amz-server-side-encryption": "AES256",
},
}),
)
.mockResolvedValueOnce(new Response("denied", { status: 403 }));
vi.stubGlobal("fetch", fetchMock);
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
await expect(publishProjectArchive(dir)).rejects.toThrow("Failed to upload project archive");
expect(fetchMock).toHaveBeenCalledTimes(2);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("retries a transient presigned upload network failure once", async () => {
const dir = makeProjectDir();
const fetchMock = vi
.fn()
.mockResolvedValueOnce(uploadResponse())
.mockRejectedValueOnce(networkFailure("ECONNRESET", "socket disconnected"))
.mockResolvedValueOnce(new Response(null, { status: 200 }))
.mockResolvedValueOnce(publishedResponse());
vi.stubGlobal("fetch", fetchMock);
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
const result = await publishProjectArchive(dir);
expect(result.projectId).toBe("hfp_123");
expect(fetchMock).toHaveBeenCalledTimes(4);
expect(fetchMock.mock.calls[1]![0]).toBe("https://s3.example.com/upload");
expect(fetchMock.mock.calls[2]![0]).toBe("https://s3.example.com/upload");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("waits briefly before retrying a transport failure", async () => {
vi.useFakeTimers();
const dir = makeProjectDir();
const fetchMock = vi
.fn()
.mockResolvedValueOnce(uploadResponse())
.mockRejectedValueOnce(networkFailure("EAI_AGAIN", "temporary DNS failure"))
.mockResolvedValueOnce(new Response(null, { status: 200 }))
.mockResolvedValueOnce(publishedResponse());
vi.stubGlobal("fetch", fetchMock);
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
const publish = publishProjectArchive(dir);
await vi.advanceTimersByTimeAsync(0);
expect(fetchMock).toHaveBeenCalledTimes(2);
await vi.advanceTimersByTimeAsync(199);
expect(fetchMock).toHaveBeenCalledTimes(2);
await vi.advanceTimersByTimeAsync(1);
await expect(publish).resolves.toMatchObject({ projectId: "hfp_123" });
expect(fetchMock).toHaveBeenCalledTimes(4);
} finally {
await vi.runAllTimersAsync();
vi.useRealTimers();
rmSync(dir, { recursive: true, force: true });
}
});
it("reports the upload stage and transport cause after the retry is exhausted", async () => {
const dir = makeProjectDir();
const signedUrl =
"https://s3.example.com/upload?X-Amz-Credential=secret&X-Amz-Signature=do-not-print";
const fetchMock = vi
.fn()
.mockResolvedValueOnce(uploadResponse({ upload_url: signedUrl }))
.mockRejectedValueOnce(
networkFailure("EAI_AGAIN", "getaddrinfo EAI_AGAIN s3.example.com", {
errno: -3001,
syscall: "getaddrinfo",
}),
)
.mockRejectedValueOnce(
networkFailure("EAI_AGAIN", "getaddrinfo EAI_AGAIN s3.example.com", {
errno: -3001,
syscall: "getaddrinfo",
}),
);
vi.stubGlobal("fetch", fetchMock);
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
const promise = publishProjectArchive(dir);
await expect(promise).rejects.toThrow(
"Failed to upload project archive after 2 attempts: fetch failed (EAI_AGAIN, syscall=getaddrinfo, errno=-3001: getaddrinfo EAI_AGAIN s3.example.com)",
);
await expect(promise).rejects.not.toThrow("do-not-print");
expect(fetchMock).toHaveBeenCalledTimes(3);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("reports the prepare stage and explains disabled Node proxy support", async () => {
const dir = makeProjectDir();
vi.stubEnv("HTTPS_PROXY", "http://proxy.example.com:8080");
vi.stubEnv("NODE_USE_ENV_PROXY", "");
const fetchMock = vi
.fn()
.mockRejectedValueOnce(networkFailure("ENETUNREACH", "network is unreachable"))
.mockRejectedValueOnce(networkFailure("ENETUNREACH", "network is unreachable"));
vi.stubGlobal("fetch", fetchMock);
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
await expect(publishProjectArchive(dir)).rejects.toThrow(
"Failed to prepare project upload after 2 attempts: fetch failed (ENETUNREACH: network is unreachable). Proxy variables are set but ignored by Node fetch; if this network requires them, retry with NODE_USE_ENV_PROXY=1",
);
expect(fetchMock).toHaveBeenCalledTimes(2);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("retries a transient prepare-upload network failure once", async () => {
const dir = makeProjectDir();
const fetchMock = vi
.fn()
.mockRejectedValueOnce(networkFailure("EAI_AGAIN", "temporary DNS failure"))
.mockResolvedValueOnce(uploadResponse())
.mockResolvedValueOnce(new Response(null, { status: 200 }))
.mockResolvedValueOnce(publishedResponse());
vi.stubGlobal("fetch", fetchMock);
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
const result = await publishProjectArchive(dir);
expect(result.projectId).toBe("hfp_123");
expect(fetchMock).toHaveBeenCalledTimes(4);
expect(fetchMock.mock.calls[0]![0]).toBe(
"https://api2.heygen.com/v1/hyperframes/projects/publish/upload",
);
expect(fetchMock.mock.calls[1]![0]).toBe(
"https://api2.heygen.com/v1/hyperframes/projects/publish/upload",
);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("does not retry a request that reached its timeout", async () => {
const dir = makeProjectDir();
const fetchMock = vi
.fn()
.mockRejectedValueOnce(
new DOMException("The operation was aborted due to timeout", "TimeoutError"),
)
.mockResolvedValueOnce(uploadResponse())
.mockResolvedValueOnce(new Response(null, { status: 200 }))
.mockResolvedValueOnce(publishedResponse());
vi.stubGlobal("fetch", fetchMock);
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
await expect(publishProjectArchive(dir)).rejects.toThrow(
"Failed to prepare project upload: The operation was aborted due to timeout",
);
expect(fetchMock).toHaveBeenCalledTimes(1);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("reports the finalize stage and transport cause", async () => {
const dir = makeProjectDir();
const fetchMock = vi
.fn()
.mockResolvedValueOnce(uploadResponse())
.mockResolvedValueOnce(new Response(null, { status: 200 }))
.mockRejectedValueOnce(networkFailure("ECONNRESET", "socket disconnected"));
vi.stubGlobal("fetch", fetchMock);
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
await expect(publishProjectArchive(dir)).rejects.toThrow(
"Failed to finalize project publish: fetch failed (ECONNRESET: socket disconnected)",
);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});
/** Staged flow returning an already-owned, already-claimed stable project. */
function ownedStagedFetch() {
return stagedFetch({
project_id: "hfp_stable",
url: "https://hyperframes.dev/p/hfp_stable",
...OWNED,
});
}
describe("publishProjectArchive", () => {
it("sends and persists a stable project id when authenticated", async () => {
withOAuthCredential();
const dir = makeProjectDir();
const fetchMock = ownedStagedFetch();
vi.stubGlobal("fetch", fetchMock);
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
const result = await publishProjectArchive(dir, { projectId: "hfp_stable" });
const completeBody = JSON.parse(fetchMock.mock.calls[2]![1].body);
expect(completeBody.project_id).toBe("hfp_stable");
// An owned re-publish returns claimed with no claim token to append.
expect(result.claimed).toBe(true);
expect(result.claimToken).toBe("");
expect(linkMocks.writeProjectLink).toHaveBeenCalledWith(dir, {
projectId: "hfp_stable",
url: "https://hyperframes.dev/p/hfp_stable",
});
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("never sends a project id or persists a link when anonymous", async () => {
// Default credential is null (anonymous).
const dir = makeProjectDir();
const fetchMock = stagedFetch();
vi.stubGlobal("fetch", fetchMock);
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
await publishProjectArchive(dir, { projectId: "hfp_stable" });
const completeBody = JSON.parse(fetchMock.mock.calls[2]![1].body);
expect(completeBody).not.toHaveProperty("project_id");
expect(linkMocks.writeProjectLink).not.toHaveBeenCalled();
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
async function publishWithTeamSpace(authed: boolean) {
// Set explicitly (not just for the authed case) so calling this twice in one test —
// authed then anonymous — doesn't leak the credential mock across calls.
if (authed) withOAuthCredential();
else authMocks.tryResolveCredential.mockResolvedValue(null);
const dir = makeProjectDir();
const fetchMock = ownedStagedFetch();
vi.stubGlobal("fetch", fetchMock);
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
await publishProjectArchive(dir, { projectId: "hfp_stable", spaceId: "space-42" });
return fetchMock;
} finally {
rmSync(dir, { recursive: true, force: true });
}
}
it("sends X-Space-Id only when authenticated (metadata requests, never the S3 PUT)", async () => {
const authed = await publishWithTeamSpace(true);
// Metadata calls (upload=0, complete=2) carry the team space header...
expect(authed.mock.calls[0]![1].headers["x-space-id"]).toBe("space-42");
expect(authed.mock.calls[2]![1].headers["x-space-id"]).toBe("space-42");
// ...but the presigned S3 PUT (1) must NOT — extra headers break the signature.
expect(authed.mock.calls[1]![1].headers).not.toHaveProperty("x-space-id");
// Anonymous: the header is dropped entirely even if a space was requested.
const anon = await publishWithTeamSpace(false);
expect(anon.mock.calls[0]![1].headers).not.toHaveProperty("x-space-id");
expect(anon.mock.calls[2]![1].headers).not.toHaveProperty("x-space-id");
});
});
describe("publishProjectArchive with a credential the server rejects", () => {
const EXPIRED = "Your login expired. Run hyperframes auth login, then publish again.";
const unauthorized = () =>
new Response(JSON.stringify({ message: "Unauthorized" }), {
status: 401,
headers: { "content-type": "application/json" },
});
async function publishExpecting(fetchMock: ReturnType<typeof vi.fn>, message: string) {
const dir = makeProjectDir();
try {
await expect(runAuthenticatedPublish(fetchMock, dir)).rejects.toThrow(message);
} finally {
rmSync(dir, { recursive: true, force: true });
}
}
it("stops at the first request, before any upload, with a re-login message", async () => {
const fetchMock = vi.fn().mockResolvedValueOnce(unauthorized());
await publishExpecting(fetchMock, EXPIRED);
expect(fetchMock).toHaveBeenCalledTimes(1);
expectAuthorizedHeaders(fetchMock, 0);
});
it("says the same when the final publish request is refused", async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(uploadResponse())
.mockResolvedValueOnce(new Response(null, { status: 200 }))
.mockResolvedValueOnce(unauthorized());
await publishExpecting(fetchMock, EXPIRED);
});
it("says the same on the legacy multipart publish", async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(new Response("not found", { status: 404 }))
.mockResolvedValueOnce(unauthorized());
await publishExpecting(fetchMock, EXPIRED);
});
it("asks a signed-out publish to log in when the upload route answers 401, with no fallback", async () => {
const fetchMock = vi.fn().mockResolvedValueOnce(unauthorized());
vi.stubGlobal("fetch", fetchMock);
const dir = makeProjectDir();
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
await expect(publishProjectArchive(dir)).rejects.toThrow(
"Publishing needs an account. Run hyperframes auth login to publish.",
);
} finally {
rmSync(dir, { recursive: true, force: true });
}
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock.mock.calls[0]![0]).toMatch(/\/publish\/upload$/);
});
it("does not blame the login for a 401 from the storage upload, which carries no credential", async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(uploadResponse())
.mockResolvedValueOnce(new Response("denied", { status: 401 }));
await publishExpecting(fetchMock, "Failed to upload project archive");
});
it("refuses an anonymous result for a signed-in publish and links nothing", async () => {
await publishExpecting(stagedFetch(), EXPIRED);
await publishExpecting(directFetch(), EXPIRED);
expect(linkMocks.writeProjectLink).not.toHaveBeenCalled();
});
it("publishes with an API key, which the server never marks as owned, and links nothing", async () => {
const dir = makeProjectDir();
try {
authMocks.tryResolveCredential.mockResolvedValue({
type: "api_key",
key: "k",
source: "env",
});
vi.stubGlobal("fetch", stagedFetch());
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
const result = await publishProjectArchive(dir);
expect(result.claimToken).toBe("claim-token");
expect(linkMocks.writeProjectLink).not.toHaveBeenCalled();
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("names the environment API key instead of asking for a login it would not use", async () => {
const fetchMock = vi.fn().mockResolvedValueOnce(unauthorized());
const dir = makeProjectDir();
try {
authMocks.tryResolveCredential.mockResolvedValue({
type: "api_key",
key: "k",
source: "env",
});
vi.stubGlobal("fetch", fetchMock);
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
await expect(publishProjectArchive(dir)).rejects.toThrow(
"HEYGEN_API_KEY was rejected. Fix or unset it, then publish again.",
);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("names a rejected host access token instead of asking for a login it would not use", async () => {
const fetchMock = vi.fn().mockResolvedValueOnce(unauthorized());
const dir = makeProjectDir();
try {
authMocks.tryResolveCredential.mockResolvedValue({
type: "oauth",
access_token: "host-token",
source: "env_oauth",
refreshable: false,
});
vi.stubGlobal("fetch", fetchMock);
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
await expect(publishProjectArchive(dir)).rejects.toThrow(
"HEYGEN_ACCESS_TOKEN was rejected. Fix or unset it, then publish again.",
);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});
describe("publishProjectArchive with an expired login it can refresh", () => {
const expiredLogin = {
type: "oauth",
access_token: "stale-token",
refresh_token: "refresh-token",
source: "file_json",
refreshable: true,
};
it("refreshes the login and publishes with the new token", async () => {
oauthMocks.refreshTokens.mockResolvedValueOnce({ access_token: "fresh-token" });
authMocks.tryResolveCredential.mockResolvedValue(expiredLogin);
const fetchMock = stagedFetch(OWNED);
vi.stubGlobal("fetch", fetchMock);
const dir = makeProjectDir();
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
await publishProjectArchive(dir);
expect(oauthMocks.refreshTokens).toHaveBeenCalledWith("refresh-token");
expect(fetchMock.mock.calls[0]![1].headers).toEqual(
expect.objectContaining({ authorization: "Bearer fresh-token" }),
);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
// The command checks the login before a proxy bake that can outlast it.
it("refreshes a passed login that expired since it was checked, without resolving again", async () => {
oauthMocks.refreshTokens.mockResolvedValueOnce({ access_token: "fresh-token" });
const fetchMock = stagedFetch(OWNED);
vi.stubGlobal("fetch", fetchMock);
const dir = makeProjectDir();
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
await publishProjectArchive(dir, {
credential: {
...expiredLogin,
expires_at: new Date(Date.now() - 1000),
refreshable: false,
},
} as never);
expect(authMocks.tryResolveCredential).not.toHaveBeenCalled();
expect(fetchMock.mock.calls[0]![1].headers).toEqual(
expect.objectContaining({ authorization: "Bearer fresh-token" }),
);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("asks for a new login, without sending anything, when a passed login expired and cannot refresh", async () => {
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
const { refresh_token: _none, ...noRefresh } = expiredLogin;
const dir = makeProjectDir();
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
await expect(
publishProjectArchive(dir, {
credential: { ...noRefresh, expires_at: new Date(Date.now() - 1000), refreshable: false },
} as never),
).rejects.toThrow("Your login expired. Run hyperframes auth login, then publish again.");
expect(fetchMock).not.toHaveBeenCalled();
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("asks for a new login, without sending anything, when the refresh is refused", async () => {
oauthMocks.refreshTokens.mockRejectedValueOnce(ErrRefreshFailed("invalid_grant"));
authMocks.tryResolveCredential.mockResolvedValue(expiredLogin);
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
const dir = makeProjectDir();
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
await expect(publishProjectArchive(dir)).rejects.toThrow(
"Your login expired. Run hyperframes auth login, then publish again.",
);
expect(fetchMock).not.toHaveBeenCalled();
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});
describe("publishProjectArchive with an expired login and no refresh token", () => {
let fixture: Awaited<ReturnType<typeof setupTempAuthEnv>>;
beforeEach(async () => {
fixture = await setupTempAuthEnv("hf-publish-expired-");
const { tryResolveCredential } =
await vi.importActual<typeof import("../auth/resolver.js")>("../auth/resolver.js");
authMocks.tryResolveCredential.mockImplementation(tryResolveCredential);
});
afterEach(async () => {
await fixture.restore();
});
it("asks for a new login instead of publishing anonymously", async () => {
const past = new Date(Date.now() - 60 * 60 * 1000).toISOString();
await writeStore({ oauth: { access_token: "stale-token", expires_at: past } });
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
const dir = makeProjectDir();
try {
writeFileSync(join(dir, "index.html"), "<html></html>", "utf-8");
await expect(publishProjectArchive(dir)).rejects.toThrow(
"Your login expired. Run hyperframes auth login, then publish again.",
);
expect(fetchMock).not.toHaveBeenCalled();
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});
describe("readStaged", () => {
let dir: string;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "hf-staged-"));
writeFileSync(join(dir, "index.html"), "<html></html>");
writeFileSync(join(dir, "clip.bin"), "staged bytes");
});
afterEach(() => rmSync(dir, { recursive: true, force: true }));
it("reads a file left on disk only while it is the file that was staged", () => {
const staged = stagePublishFiles(dir, 4).get("clip.bin")!;
expect(Buffer.isBuffer(staged)).toBe(false);
expect(readStaged(staged).toString()).toBe("staged bytes");
writeFileSync(join(dir, "swap.bin"), "other bytes");
utimesSync(join(dir, "swap.bin"), 1, 1);
renameSync(join(dir, "swap.bin"), join(dir, "clip.bin"));
expect(() => readStaged(staged)).toThrow(/changed on disk/);
});
});
describe("createPublishArchive referenced dot-paths", () => {
const clip = ".hyperframes/prepared-assets/clip.mp4";
function projectWith(html: string, files: Record<string, string>): string {
const dir = makeProjectDir();
writeFileSync(join(dir, "index.html"), html, "utf-8");
for (const [name, body] of Object.entries(files)) {
mkdirSync(dirname(join(dir, name)), { recursive: true });
writeFileSync(join(dir, name), body, "utf-8");
}
return dir;
}
const names = (dir: string) =>
new AdmZip(createPublishArchive(dir).buffer).getEntries().map((e) => e.entryName);
it("carries a referenced file under a dot-folder", () => {
const dir = projectWith(`<video src="${clip}"></video>`, { [clip]: "v" });
expect(names(dir)).toContain(clip);
});
it("fails before upload when a referenced file is missing", () => {
const dir = projectWith(`<video src="${clip}"></video>`, {});
expect(() => createPublishArchive(dir)).toThrow(clip);
});
it("does not fail on a missing href, source fallback, srcset candidate or CSS url", () => {
const dir = projectWith(
`<link rel="stylesheet" href="s.css"><a href="notes.html">n</a><video><source src="a.webm"><source src="a.mp4"></video>` +
`<img src="a.png" srcset="a.png 1x, a@2x.png 2x"><style>.a{background:url(gone.jpg)}</style>`,
{ "a.mp4": "v", "a.png": "p", "s.css": ".a{background:url(gone.jpg)}" },
);
expect(() => createPublishArchive(dir)).not.toThrow();
expect(names(dir)).not.toContain("notes.html");
});
it("fails on a missing video, audio, img src or poster, naming the file", () => {
for (const tag of [
'video src="gone.mp4"',
'audio src="gone.mp3"',
'img src="gone.png"',
'video poster="gone.jpg"',
]) {
const name = /"(gone\.[a-z0-9]+)"/.exec(tag)![1]!;
expect(() =>
createPublishArchive(projectWith(`<${tag}></${tag.split(" ")[0]}>`, {})),
).toThrow(name);
}
});
it("leaves out an unreferenced .env", () => {
const dir = projectWith(`<video src="${clip}"></video>`, { [clip]: "v", ".env": "SECRET=1" });
expect(names(dir)).not.toContain(".env");
});
it("leaves out an env file or a tool record even when the markup names it", () => {
const dir = projectWith(
`<link href=".env"><img src=".env.local"><a href=".hyperframes/history-turn.json">h</a>`,
{ ".env": "SECRET=1", ".env.local": "SECRET=1", ".hyperframes/history-turn.json": "{}" },
);
expect(names(dir)).toEqual(["index.html"]);
});
});
describe("archive keys for names written in either Unicode form", () => {
// "é" as one code point (composed) and as e + a combining accent (decomposed): macOS file pickers store the latter.
const composed = "assets/Photos et vidéos 1.mp4";
const decomposed = "assets/Photos et vidéos 1.mp4";
it("keys a file stored decomposed by the composed name a page uses, so the renderer finds it", () => {
const dir = makeProjectDir();
mkdirSync(join(dir, "assets"), { recursive: true });
writeFileSync(join(dir, decomposed), "video");
writeFileSync(join(dir, "index.html"), `<video src="${composed}"></video>`);
const map = buildPublishFileMap(dir);
expect([...map.keys()].sort()).toEqual([composed, "index.html"]);
expect(map.get(composed)?.toString()).toBe("video");
const entries = new AdmZip(zipPublishFileMap(map).buffer).getEntries().map((e) => e.entryName);
expect(entries).toContain(composed);
});
it("rewrites a page and a stylesheet that name a decomposed file the way the disk lists it", () => {
const dir = makeProjectDir();
mkdirSync(join(dir, "assets"), { recursive: true });
writeFileSync(join(dir, decomposed), "video");
writeFileSync(
join(dir, "assets/styles.css"),
`.a { background: url("${decomposed.slice(7)}"); }`,
);
writeFileSync(
join(dir, "index.html"),
`<video src="${decomposed}"></video><img src="${encodeURI(decomposed)}">`,
);
const map = buildPublishFileMap(dir);
expect([...map.keys()].sort()).toEqual([composed, "assets/styles.css", "index.html"]);
expect(map.get("index.html")?.toString()).toBe(
`<video src="${composed}"></video><img src="${encodeURI(composed)}">`,
);
expect(map.get("assets/styles.css")?.toString()).toContain(composed.slice(7));
});
it("refuses two files that differ only by Unicode form instead of letting one overwrite the other", () => {
const dir = makeProjectDir();
mkdirSync(join(dir, "assets"), { recursive: true });
writeFileSync(join(dir, composed), "first");
writeFileSync(join(dir, decomposed), "second");
writeFileSync(join(dir, "index.html"), "<html></html>");
expect(() => buildPublishFileMap(dir)).toThrow(/same name|differ only/i);
});
});