import path from "node:path";
import { realpath, stat } from "node:fs/promises";
import { composeIntroPreview } from "@/lib/report/onscreen.mjs";
import { introPreviewSrc, rangeResponse, resolveReport } from "@/lib/report/serve.mjs";
import { selectVariant } from "umtool-report-to-video/build-video";
import { INTRO_STANDIN_SOUND, introEntry, isIntro } from "umtool-report-to-video/intro";
import { validateIntroSettings } from "umtool-report-to-video/modules/intro";
import { cachedTakeManifest, takePlayDir, writePlayManifest } from "@/lib/report/takeManifest.mjs";
import { isTakeId } from "@/lib/report/takes.mjs";
import { introState, setVersionIntro } from "@/lib/report/introEdit.mjs";
import { StaleToken } from "@/lib/report/manifest.mjs";
import { refuseCaller } from "@/lib/report/caller";
import {
INTRO_GROUNDS, INTRO_LINE_MAX, INTRO_LINES_MAX, INTRO_MARKS, INTRO_SECONDS, INTRO_SECONDS_MAX, INTRO_SECONDS_MIN, INTRO_STYLE_DEFAULT,
INTRO_STYLES, INTRO_TITLE_MAX,
} from "yt-dlp-transcript-common/lib/report/intro.mjs";
export const dynamic = "force-dynamic";
// THE INTRO, PLAYABLE (`render.intro`; operator, 8 Nov 2026: "more first-class intro support (view in
// play the cut)"): the cut's brand intro composed as the build draws it -- report-to-video intro.mjs's
// own page (writeIntroPage), Play's seek appended (onscreen.mjs composeIntroPreview) -- so Play,
// Present and the Cut tab's intro editor show the real intro instead of a placeholder. No render.
//
// POST { project, take?, intro? } -> { intro: { id, style, seconds, width, height, src, sound } | null }
// the cut's intro (or a take's), as selectVariant opens the cut with it; with `intro` (the editor's
// unsaved value, `null` for none) that value instead, composed as the editor's draft page. A value the
// build would refuse is a 400 { errors }.
// GET ?project=
-> introState: the intro as written, its entry, each version's
// GET ?project=
&sound=1[&path=] -> the intro's sound (the stand-in, or a file of the project)
// PUT { project, take, on, token? } -> a VERSION with (on) or without the cut's intro: its patch's
// `render.intro: null` (introEdit.mjs setVersionIntro)
// The project's own intro is written by the look writer, PUT /api/report/render { patch: { intro } }.
const noStore = { "cache-control": "no-store" };
/** The sound files the intro route serves, by extension, and their content types. */
const AUDIO_TYPES: Record = {
".wav": "audio/wav",
".mp3": "audio/mpeg",
".m4a": "audio/mp4",
".aac": "audio/aac",
".ogg": "audio/ogg",
".opus": "audio/ogg",
".flac": "audio/flac",
};
const inside = (base: string, p: string) => {
const rel = path.relative(base, p);
return !!rel && !rel.startsWith("..") && !path.isAbsolute(rel);
};
/** The sound a page plays with the intro: the stand-in (the sound absent), a project file, or none. */
function soundSrc(projectId: string, sound: unknown): string | null {
if (sound === false) return null;
const q = new URLSearchParams({ project: projectId, sound: "1" });
if (typeof sound === "string" && sound) q.set("path", sound);
return `/api/report/chrome/intro?${q.toString()}`;
}
export async function GET(request: Request) {
const url = new URL(request.url);
const r = await resolveReport(url.searchParams.get("project") ?? "");
if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
if (url.searchParams.get("sound") === "1") {
const rel = url.searchParams.get("path");
let abs: string | null = null;
if (!rel) abs = INTRO_STANDIN_SOUND;
else {
// A project's own sound file only (render.intro.sound is relative to the manifest).
const base = await realpath(r.project.dir).catch(() => null);
const real = await realpath(path.resolve(r.project.dir, rel)).catch(() => null);
if (base && real && inside(base, real)) abs = real;
}
// Audio only, by its extension: this route never serves any other file of the project.
const type = abs ? AUDIO_TYPES[path.extname(abs).toLowerCase()] : undefined;
const st = abs && type ? await stat(abs).catch(() => null) : null;
if (!abs || !type || !st?.isFile()) return new Response("no intro sound here", { status: 404 });
return rangeResponse(request, { abs, size: st.size, headers: { "content-type": type, "accept-ranges": "bytes", "cache-control": "no-store" } });
}
try {
const state = await introState(r.project);
return Response.json(
{
...state,
choices: {
styles: INTRO_STYLES, styleDefault: INTRO_STYLE_DEFAULT, marks: INTRO_MARKS, grounds: INTRO_GROUNDS,
seconds: { min: INTRO_SECONDS_MIN, max: INTRO_SECONDS_MAX, default: INTRO_SECONDS },
titleMax: INTRO_TITLE_MAX, linesMax: INTRO_LINES_MAX, lineMax: INTRO_LINE_MAX,
},
},
{ headers: noStore },
);
} catch (e) {
return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
}
}
export async function POST(request: Request) {
let body: Record;
try {
body = await request.json();
} catch {
return Response.json({ error: "expected JSON" }, { status: 400 });
}
const r = await resolveReport(String(body.project ?? ""), body.variant ? String(body.variant) : null);
if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
const take = body.take === undefined || body.take === null || body.take === "" ? null : String(body.take);
if (take !== null && !isTakeId(take)) return Response.json({ error: "take is a take id" }, { status: 400 });
const draft = "intro" in body;
let manifest = r.manifest as Record;
let target: { dir: string } = r.project;
if (take && !draft) {
try {
manifest = (await cachedTakeManifest(r.project.dir, take)).manifest;
target = { dir: takePlayDir(r.project.dir, take) };
await writePlayManifest(r.project.dir, take, manifest);
} catch (e) {
return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 404 });
}
}
const selected = selectVariant(manifest, r.variant) as Record & { timeline?: Record[]; render?: Record };
const render = (selected.render ?? {}) as Record;
let entry: Record | null;
if (draft) {
// The editor's unsaved intro: checked as the writer will check it, then made into the entry the cut would open with.
const value = body.intro ?? null;
const errors = validateIntroSettings(value);
if (errors.length) return Response.json({ error: errors.join("; "), errors }, { status: 400 });
try {
entry = value === null ? null : (introEntry({ ...render, intro: value }, { provenance: (manifest.provenance ?? null) as never, manifest }) as Record | null);
} catch (e) {
return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
}
} else {
entry = (selected.timeline ?? []).find(isIntro) ?? null;
}
if (!entry) return Response.json({ intro: null }, { headers: noStore });
const width = typeof render.width === "number" ? render.width : 1920;
const height = typeof render.height === "number" ? render.height : 1080;
try {
const c = await composeIntroPreview(target, r.variant, entry, render, { draft });
return Response.json(
{
intro: {
id: String(entry.id),
style: String(entry.style),
seconds: Number(entry.seconds),
width,
height,
src: `${introPreviewSrc(r.project.id, r.variant, draft ? null : take, c.file)}?v=${Date.now()}`,
sound: soundSrc(r.project.id, entry.sound),
...(typeof entry.title === "string" ? { title: entry.title } : {}),
...(Array.isArray(entry.lines) ? { lines: entry.lines } : {}),
},
},
{ headers: noStore },
);
} catch (e) {
return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500 });
}
}
export async function PUT(request: Request) {
const refused = refuseCaller(request, "/api/report/chrome/intro");
if (refused) return refused;
let body: Record;
try {
body = await request.json();
} catch {
return Response.json({ error: "expected JSON" }, { status: 400 });
}
const r = await resolveReport(String(body.project ?? ""));
if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
const take = String(body.take ?? "");
if (!isTakeId(take)) return Response.json({ error: "take is a take id" }, { status: 400 });
if (typeof body.on !== "boolean") return Response.json({ error: "on is true (the cut's intro) or false (none)" }, { status: 400 });
try {
// A take's patch is not a generated manifest: no edit notes (takeScope.mjs's rule).
const result = await setVersionIntro(r.project.dir, take, body.on as boolean, { token: body.token === undefined || body.token === null ? null : String(body.token) });
return Response.json({ ok: true, take, intro: body.on ? "cut" : "off", unchanged: result.unchanged, token: result.token }, { headers: noStore });
} catch (e) {
if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 });
return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
}
}