import { askEditor, clearEditorMemo, EditorError } from "@/lib/articles/generation"; import { pressRefusal } from "@/lib/library/caller.mjs"; import { PressError } from "@/lib/library/presses.mjs"; // What the Posts library's press routes share (lane posts-library). // // THESE ROUTES ARE THE PAGE'S, AND ONLY THE PAGE'S: every press through them // is stamped the operator's (lib/library/presses.mjs), so a press is taken // only from umtool's own page in a browser (lib/library/caller.mjs // pressRefusal: what a browser sends, same-origin, to this machine). A // request no browser sent — curl, a script, an agent, the editor, with a // bearer or with nothing at all — is refused before its body is read, and // sent to `pnpm ops` / `umtool library`, where a caller says who it is. export const NO_STORE = { "cache-control": "no-store" }; // A read is always asked again: a press is judged against the rows as they are NOW (a bulk press's // targets and its undo), never an answer askEditor kept from two seconds ago. export const ask = (route: string, init?: { method?: "GET" | "POST"; body?: unknown }) => askEditor>(route, { ...init, fresh: true }); /** Run one press: the caller checked, the body parsed, the press's answer, or its refusal in its own words. */ export async function press(request: Request, run: (body: unknown) => Promise): Promise { const refused = pressRefusal(request.headers); if (refused) return Response.json({ error: refused.error }, { status: refused.status, headers: NO_STORE }); const body = await request.json().catch(() => null); try { return Response.json(await run(body), { headers: NO_STORE }); } catch (err) { const status = err instanceof PressError || err instanceof EditorError ? err.status : 500; const reason = err instanceof EditorError ? { reason: err.reason } : {}; return Response.json({ error: err instanceof Error ? err.message : String(err), ...reason }, { status, headers: NO_STORE }); } finally { // askEditor drops its kept reads when a write STARTS; a read that crossed the write on its way is // kept again with the old answer. Dropped once more now that the write has landed. clearEditorMemo(); } }