import { invalidateProjects, projectRef } from "@/lib/projects";
import { refuseCaller } from "@/lib/report/caller";
import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs";
import { StaleToken, StructureRefused } from "@/lib/report/manifest.mjs";
import { isTakeId } from "@/lib/report/takes.mjs";
import { VersionRefused, openVersion } from "@/lib/report/versions.mjs";
export const dynamic = "force-dynamic";
// OPEN A VERSION IN THE DRAFT (lib/report/versions.mjs openVersion; the CLI
// twin is `umtool takes open
`). The draft is saved first as the
// next version when it has edits since its parent; the version is then
// written over the draft with one undo point ("Undo open ": the Cut
// tab's Undo last edit, `umtool timeline undo`). The pick is untouched.
//
// POST JSON { project, take, token? } -> { ok, opened, how, saved, snapshot, token }
// POST a FORM (the Open in draft page's button, no script needed) with
// project, take, token, next (where to land: a /projects/… address), back
// -> 303 to `next`; refused -> 303 to `back` with `?error=`.
//
// A stale token is a 409 (the draft changed since the page was read).
const isForm = (request: Request) => /application\/x-www-form-urlencoded|multipart\/form-data/.test(request.headers.get("content-type") ?? "");
const local = (v: unknown) => (typeof v === "string" && v.startsWith("/projects/") && !v.startsWith("//") ? v : null);
export async function POST(request: Request) {
const refused = refuseCaller(request, "/api/report/takes/open");
if (refused) return refused;
// A plain form carries no token: a write another site's page posts is refused (lib/report/sameOrigin.mjs).
const cross = crossSiteRefusal(request.headers);
if (cross) return Response.json({ error: cross }, { status: 403 });
const form = isForm(request);
let body: Record | null = null;
if (form) {
const f = await request.formData().catch(() => null);
body = f ? Object.fromEntries([...f.entries()].map(([k, v]) => [k, typeof v === "string" ? v : ""])) : null;
} else body = (await request.json().catch(() => null)) as Record | null;
if (!body || typeof body !== "object") return Response.json({ error: "bad body" }, { status: 400 });
const back = local(body.back);
const fail = (status: number, error: string, extra: Record = {}) => {
if (form && back) return new Response(null, { status: 303, headers: { location: `${back}${back.includes("?") ? "&" : "?"}error=${encodeURIComponent(error)}` } });
return Response.json({ error, ...extra }, { status });
};
if (!isTakeId(body.take)) return fail(400, "take must be a take id");
const project = await projectRef(String(body.project ?? ""));
if (!project) return fail(404, "no such project");
const token = body.token === undefined || body.token === null || body.token === "" ? null : String(body.token);
try {
const r = await openVersion(project, body.take, { token });
invalidateProjects();
const next = local(body.next);
if (form) return new Response(null, { status: 303, headers: { location: next ?? `/projects/${project.id}/play` } });
return Response.json({ ok: true, ...r }, { headers: { "cache-control": "no-store" } });
} catch (e) {
if (e instanceof StaleToken) return fail(409, "the draft changed since this page was read — look again", { stale: true });
if (e instanceof StructureRefused) return fail(400, e.message, { errors: (e as unknown as { errors?: string[] }).errors ?? [] });
const message = e instanceof Error ? e.message : String(e);
if (e instanceof VersionRefused) return fail(/^no take /.test(message) ? 404 : 400, message);
return fail(500, message);
}
}