// THE READS PAGE's REQUESTS (lane reads-find; app/api/report/reads/route.ts is this, behind its guards): every // request answered by the same functions `umtool reads` runs (reads.mjs, readsReplace.mjs, readsQueue.mjs), called // directly -- never an argv built from what a page typed. A write that acts on reads names them (`only`): the ids // the page counted, each checked; a list that names one id no read could have is refused whole (400), never // narrowed -- an unscoped re-read, pick or replace is the CLI's alone (no --only). // // Plain ESM: tested without the app (readsApi.test.mjs). import { READ_KINDS, filterReads, findInReads, projectReads, readIdsOf } from "./reads.mjs"; import { manifestToken } from "./manifest.mjs"; const view = (x) => ({ id: x.id, kind: x.kind, item: x.item, role: x.role, character: x.character, voice: x.voice, spoken: x.spoken, said: x.said, storedAt: x.storedAt, editable: x.editable, why: x.why, queueable: x.queueable !== false, state: x.state, because: x.because, take: x.take, newTake: x.newTake, ...(x.matches ? { matches: x.matches } : {}) }); void READ_KINDS; class Refused extends Error { constructor(message, status = 400) { super(message); this.status = status; } } /** `only` from a body: required here (`need`), each id checked. */ function onlyOf(body, need) { if (body.only === undefined || body.only === null) { if (need) throw new Refused("which reads? (only: the ids of the reads this acts on)"); return null; } const r = readIdsOf(body.only); if (r.error) throw new Refused(r.error); return r.ids; } const text = (v, what) => { if (typeof v !== "string") throw new Refused(`${what} is text`); return v; }; /** * The queue as the page shows it: its waiting sentence completed with the app's own runner -- its specific reason * (its last turn's error, what it waits for, not armed in this process) before the general one. */ export async function queueOf(project, { reportsRoot, queueDir, runner = null }) { const { queueView } = await import("./readsQueue.mjs"); const v = await queueView(project, { reportsRoot, queueDir }); if (!v.counts.waiting) return v; const st = runner ?? {}; const specific = st.lastError ? `waiting: the app's queue runner's last turn failed -- ${st.lastError}` : st.waiting ? `waiting: ${st.waiting}` : st.armed === false && st.enabled === false ? "waiting: this umtool app does not run the queue (UMTOOL_QUEUE_RUNNER is off here) -- the app that holds the queue's lease runs it" : null; return { ...v, waiting: specific && !/render mode/.test(v.waiting ?? "") ? specific : v.waiting }; } /** GET: the reads (filtered, with Find's matches), the queue, and whether the newest replace can be taken back. */ export async function readsGet(project, q, o) { const { rows, counts, tuningStale } = await projectReads(project, { reportsRoot: o.reportsRoot }); const character = q.get("character"); let list = filterReads(rows, { stale: q.get("stale") === "1", character: character && /^[a-z0-9][a-z0-9_-]{0,63}$/i.test(character) ? character : null }); const find = q.get("find"); const opts = { matchCase: q.get("case") === "1", word: q.get("word") === "1" }; let found = null; if (find && find.trim()) { found = findInReads(list, find, opts); list = found.rows; } const { replaceUndoState } = await import("./readsReplace.mjs"); return { ok: true, project: project.id, counts, settingsStale: tuningStale.length, reads: list.map(view), ...(found ? { find: { text: find, ...opts, matches: found.matches, lines: found.lines } } : {}), queue: await queueOf(project, o), undo: await replaceUndoState(project), }; } /** * POST: one op -- `{ status, json }`. preview / replace (`scope` "reads" | "say"; a replace of These reads names the * previewed reads), undo (the newest replace, of either scope), reread (the reads counted), stop, retry, pick (the * reads it picks). */ export async function readsPost(project, body, o) { try { const op = String(body.op ?? ""); const R = await import("./readsReplace.mjs"); const Q = await import("./readsQueue.mjs"); const opts = { matchCase: body.case === true, word: body.word === true, reportsRoot: o.reportsRoot }; const qo = { reportsRoot: o.reportsRoot, queueDir: o.queueDir }; let json; if (op === "preview" || op === "replace") { const from = text(body.from, "from"); const to = text(body.to ?? "", "to"); if (!from.trim()) throw new Refused("find what? (the words to replace)"); if (body.scope === "say") { if (!opts.word) throw new Refused(R.SAY_WHOLE_WORDS); if (op === "preview") { const plan = await R.sayOnlyPlan(project, from, to, opts); json = { scope: "say", entry: plan.entry, was: plan.was, stale: plan.stale, cards: plan.cards, matches: plan.matches }; } else { const done = await R.applySayOnly(project, from, to, opts); json = { scope: "say", entry: done.result.entry, changed: done.result.changed, was: done.plan.was, stale: done.plan.stale }; } } else if (body.scope === "reads") { // The reads it acts on, on the preview as on Apply: the rows the page's Find counted. const only = onlyOf(body, true); if (op === "preview") { // The draft's token as the preview read it: Apply writes only over that draft (409 otherwise). const token = await manifestToken(project.dir); const plan = await R.replacePlan(project, from, to, { ...opts, only }); json = { scope: "reads", lines: plan.lines, skipped: plan.skipped, notes: plan.notes, refused: plan.refused, matches: plan.matches, token }; } else { if (typeof body.token !== "string" || !body.token) throw new Refused("Apply goes with its preview's token (preview first)"); let done; try { done = await R.applyReplace(project, from, to, { ...opts, only, token: body.token }); } catch (err) { if (err?.constructor?.name === "StaleToken") throw new Refused("the draft changed since the preview: preview again", 409); throw err; } json = { scope: "reads", lines: done.plan.lines, token: done.result.token ?? null }; } } else throw new Refused("scope is reads or say"); } else if (op === "undo") { const st = await R.replaceUndoState(project); if (!st) throw new Refused("nothing to undo: no replace was made here"); json = st.scope === "say" ? { scope: "say", ...(await R.undoSayOnly(project)) } : { scope: "reads", ...(await R.undoReplace(project)) }; } else if (op === "reread") { const only = onlyOf(body, true); json = await Q.enqueueRereads(project, { ...qo, only, by: "the Reads page" }); o.kick?.(); } else if (op === "stop") json = await Q.stopQueue(project, qo); else if (op === "retry") { const [read] = onlyOf({ only: [body.read] }, true); json = await Q.retryRead(project, read, qo); o.kick?.(); } else if (op === "pick") { if (body.which !== "new" && body.which !== "old") throw new Refused("pick which: new or old"); const only = onlyOf(body, true); const r = await Q.pickReads(project, { which: body.which, only, reportsRoot: o.reportsRoot }); json = { picked: r.picked, token: r.result?.token ?? null }; } else throw new Refused(`no op ${op}`); return { status: 200, json: { ok: true, ...json, queue: await queueOf(project, o), undo: await R.replaceUndoState(project) } }; } catch (e) { const known = e instanceof Refused || ["ReplaceError", "QueueError", "StructureRefused", "StaleToken", "SayError"].includes(e?.constructor?.name); if (!known) throw e; return { status: e instanceof Refused ? e.status : e?.constructor?.name === "StaleToken" ? 409 : 400, json: { ok: false, error: e?.constructor?.name === "StructureRefused" ? e.errors.join("; ") : e.message } }; } }