import { afterEach, describe, expect, it, vi } from "vitest"; import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync, type ReadStream, } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import fs from "node:fs"; import { get, Server } from "node:http"; import { syncBuiltinESMExports } from "node:module"; import { inProcessAnswer, serveStaticProjectHtml, type StaticProjectServer, } from "./staticProjectServer.js"; import { injectMediaCodecMapIntoHtml } from "@hyperframes/studio-server/media-proxy-preview"; import { MAX_OPEN_MEDIA_RANGE_BYTES } from "@hyperframes/studio-server"; // `serveStaticProjectHtml` reaches these two studio-server helpers via a // absolute module regardless of which file's relative specifier reaches it). // // The error class lives inside this `vi.hoisted` block (not a plain top-level // `class`) because `vi.mock` factories run during static-import resolution — // before any of this file's own top-level statements execute — so a `class` // declared below would still be in its temporal dead zone. const mocks = vi.hoisted(() => { class FakeProxyTranscodeError extends Error { readonly exitCode: number | null; readonly stderrTail: string; constructor(message: string, exitCode: number | null = null, stderrTail = "") { super(message); this.name = "ProxyTranscodeError"; this.exitCode = exitCode; this.stderrTail = stderrTail; } } class FakeProxyCapacityError extends FakeProxyTranscodeError { constructor(message = "media proxy queue is full") { super(message); this.name = "ProxyCapacityError"; } } return { resolveProxy: vi.fn< ( projectDir: string, absoluteSourcePath: string, variant?: string, box?: unknown, options?: { signal?: AbortSignal }, ) => Promise >( // Benign default so `injectMediaCodecMap`'s fire-and-forget pre-warm // (called for every hostile map entry) always gets a promise to // `.catch()`, even in tests that don't care about the proxy path. async () => "/unused-prewarm-proxy-path", ), scanProjectMediaCodecMap: vi.fn< ( ...args: unknown[] ) => Promise< Record< string, { codecName: string; browserHostile: boolean; representativeMime: string | null } > > >(async () => ({})), probeAssetCodec: vi.fn(async () => ({ codecName: "hevc", hasAlpha: false, browserHostile: true, representativeMime: null, })), decideMediaProxyEligibility: vi.fn< () => { eligible: true } | { eligible: false; reason: "browser_safe_codec" } >(() => ({ eligible: true })), ProxyTranscodeError: FakeProxyTranscodeError, ProxyCapacityError: FakeProxyCapacityError, }; }); const FakeProxyTranscodeError = mocks.ProxyTranscodeError; vi.mock("@hyperframes/studio-server/proxy-transcoder", () => ({ resolveProxy: mocks.resolveProxy, ProxyTranscodeError: mocks.ProxyTranscodeError, ProxyCapacityError: mocks.ProxyCapacityError, })); vi.mock("@hyperframes/studio-server/media-codec-map", () => ({ probeAssetCodec: mocks.probeAssetCodec, decideMediaProxyEligibility: mocks.decideMediaProxyEligibility, isProxyVariant: (value: string) => value === "h264" || value === "vp8", isProxyVariantRequest: (value: string) => value === "auto" || value === "h264" || value === "vp8", recordProxyRequest: () => {}, proxyVariantFor: (facts: { hasAlpha?: boolean }) => (facts.hasAlpha ? "vp8" : "h264"), resolveProxyVariantRequest: (request: "auto" | "h264" | "vp8", facts: { hasAlpha?: boolean }) => { const expected = facts.hasAlpha ? "vp8" : "h264"; return request === "auto" || request === expected ? expected : null; }, PROXY_VARIANT_CONFIG: { h264: { extension: ".mp4", contentType: "video/mp4" }, vp8: { extension: ".webm", contentType: "video/webm" }, }, })); // The shared injection helper ships as a self-contained dist bundle (its copy // of scanProjectMediaCodecMap is inlined), so it must be mocked wholesale — // mocking the media-codec-map subpath can't reach inside it. The fake mirrors // the real contract (scan → inject tag) via this file's scan mock so the // injection assertions stay meaningful. Mirrors commands/play.test.ts. vi.mock("@hyperframes/studio-server/media-proxy-preview", () => ({ injectMediaCodecMapIntoHtml: vi.fn( async (html: string, projectDir: string, htmlSources: unknown[]) => { const map = await mocks.scanProjectMediaCodecMap(projectDir, htmlSources); const tag = ``; return html.includes("") ? html.replace("", `${tag}\n`) : `${tag}\n${html}`; }, ), })); let server: StaticProjectServer | undefined; let dir: string | undefined; afterEach(async () => { await server?.close(); server = undefined; if (dir) rmSync(dir, { recursive: true, force: true }); dir = undefined; mocks.resolveProxy.mockReset(); mocks.resolveProxy.mockResolvedValue("/unused-prewarm-proxy-path"); mocks.scanProjectMediaCodecMap.mockReset(); mocks.scanProjectMediaCodecMap.mockResolvedValue({}); mocks.probeAssetCodec.mockClear(); mocks.decideMediaProxyEligibility.mockClear(); mocks.decideMediaProxyEligibility.mockReturnValue({ eligible: true }); }); const TAGGED_PNG = Buffer.from( "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAABGNJQ1ABAQABlXPCVgAAAAxJREFUeJxj0NfXBwABHgCOTp25kgAAAABJRU5ErkJggg==", "base64", ); async function serveWith(bytes: Buffer, name = "tone.wav"): Promise<{ url: string }> { dir = mkdtempSync(join(tmpdir(), "hf-static-")); writeFileSync(join(dir, name), bytes); server = await serveStaticProjectHtml(dir, ""); return { url: server.url }; } describe("serveStaticProjectHtml colour-tagged PNGs", () => { it("serves a BT.709-tagged PNG without the tag, so check and snapshot see the file's values", async () => { const { url } = await serveWith(TAGGED_PNG, "tagged.png"); const res = await fetch(`${url}tagged.png`); const body = Buffer.from(await res.arrayBuffer()); expect(body.includes("cICP")).toBe(false); expect(body.includes("IDAT")).toBe(true); expect(res.headers.get("content-length")).toBe(String(body.length)); }); }); describe("serveStaticProjectHtml content types", () => { it("tells the browser not to sniff a type, so an image cannot load as a script or stylesheet", async () => { const { url } = await serveWith(Buffer.from("window.ran = true;"), "scene.png"); for (const path of ["", "scene.png", "missing.js"]) { const response = await fetch(`${url}${path}`); expect(response.headers.get("x-content-type-options"), path).toBe("nosniff"); } expect((await fetch(`${url}scene.png`)).headers.get("content-type")).toBe("image/png"); }); }); describe("serveStaticProjectHtml range support", () => { it("answers a Range request with 206 + the requested byte slice", async () => { // Chromium needs byte-range seekability or WAV `.duration` reports Infinity, // which makes `hyperframes validate` falsely warn it cannot read the duration. const body = Buffer.from("0123456789", "utf-8"); const { url } = await serveWith(body); const res = await fetch(`${url}tone.wav`, { headers: { Range: "bytes=2-5" } }); expect(res.status).toBe(206); expect(res.headers.get("accept-ranges")).toBe("bytes"); expect(res.headers.get("content-range")).toBe(`bytes 2-5/${body.length}`); expect(await res.text()).toBe("2345"); }); it("advertises Accept-Ranges even on a full 200 response", async () => { const { url } = await serveWith(Buffer.from("abcdef", "utf-8")); const res = await fetch(`${url}tone.wav`); expect(res.status).toBe(200); expect(res.headers.get("accept-ranges")).toBe("bytes"); expect(await res.text()).toBe("abcdef"); }); it.each([undefined, "invalid", "items=0-1"])( "serves an empty asset with Range %j and keeps serving the project", async (range) => { const { url } = await serveWith(Buffer.alloc(0)); const res = await fetch(`${url}tone.wav`, { headers: range === undefined ? {} : { Range: range }, signal: AbortSignal.timeout(1500), }); expect(res.status).toBe(200); expect(res.headers.get("content-length")).toBe("0"); expect(res.headers.get("accept-ranges")).toBe("bytes"); expect(res.headers.get("content-range")).toBeNull(); expect(await res.text()).toBe(""); const project = await fetch(url); expect(project.status).toBe(200); expect(await project.text()).toContain(""); }, ); it.each(["bytes=0-", "bytes=0-0", "bytes=-1"])( "rejects the unsatisfiable range %s on an empty asset", async (range) => { const { url } = await serveWith(Buffer.alloc(0)); const res = await fetch(`${url}tone.wav`, { headers: { Range: range } }); expect(res.status).toBe(416); expect(res.headers.get("content-range")).toBe("bytes */0"); expect(await res.text()).toBe(""); }, ); it("streams a small slice out of a large file without buffering the whole thing", async () => { // 8MB file, ask for 4 bytes deep inside it. The handler must createReadStream // the [start,end] window only, not readFileSync the whole 8MB and slice. const size = 8 * 1024 * 1024; const big = Buffer.alloc(size, 0x61); // 'a' everywhere... big.write("WXYZ", 5_000_000); // ...except a 4-byte marker const { url } = await serveWith(big); const res = await fetch(`${url}tone.wav`, { headers: { Range: "bytes=5000000-5000003" } }); expect(res.status).toBe(206); expect(res.headers.get("content-range")).toBe(`bytes 5000000-5000003/${size}`); expect(res.headers.get("content-length")).toBe("4"); expect(await res.text()).toBe("WXYZ"); }); it("returns 416 for an unsatisfiable range", async () => { const body = Buffer.from("abc", "utf-8"); const { url } = await serveWith(body); const res = await fetch(`${url}tone.wav`, { headers: { Range: "bytes=99-200" } }); expect(res.status).toBe(416); expect(res.headers.get("content-range")).toBe(`bytes */${body.length}`); }); it("answers an open-ended media range with a bounded piece, not the rest of the file", async () => { // A media element reads `bytes=N-` until its buffer is full, then leaves the response open. // Served to EOF, each