// THE POSTS LIBRARY PAGE'S PRESSES (lane posts-library): what // /api/library/{judge,watch,purge} do with a body, apart from Next. Each is // the editor's action, asked through `ask` (lib/library/client.mjs). // // EVERY PRESS FROM THE PAGE IS THE OPERATOR'S: `by: "operator"` is stamped // HERE, on the server. A `by` in the body is not read, so nothing a browser // (or anything else posting to these routes) sends can say otherwise; an // agent's hand is `pnpm ops` or `umtool library`, which say "agent". // // Plain ESM. import { JUDGE_STATES, archiveAccount, archiveSentence, judge, listLibraries, listLibrary, listLibraryRows, organise, publish, purge, watch } from "./client.mjs"; import { listingParamsOf, parseLibraryView } from "./filters.mjs"; import { pressSetOf, undoSetOf } from "./undo.mjs"; export const OPERATOR = "operator"; const SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; const ID = /^\d{1,32}$/; export class PressError extends Error { constructor(message, status = 400) { super(message); this.name = "PressError"; this.status = status; } } function libOf(body) { if (!body || typeof body !== "object" || Array.isArray(body)) throw new PressError("the body is a JSON object"); if (typeof body.lib !== "string" || !SLUG.test(body.lib)) throw new PressError(`"lib" is the library's slug`); return body.lib; } function cleanSet(set) { if (!Array.isArray(set) || set.length === 0) throw new PressError(`"set" is a list of judgements: [{"id" | "thread", "state", "note"?}, …]`); return set.map((item, i) => { const at = `set[${i}]`; if (!item || typeof item !== "object") throw new PressError(`${at} is an object`); const hasId = typeof item.id === "string"; const hasThread = typeof item.thread === "string"; if (hasId === hasThread) throw new PressError(`${at} names a post ("id") or a thread ("thread"), one of them`); const key = hasId ? item.id : item.thread; if (!ID.test(key)) throw new PressError(`${at}: "${key}" is not a post id`); if (!JUDGE_STATES.includes(item.state)) throw new PressError(`${at}: "state" is one of ${JUDGE_STATES.join(", ")}`); if (item.note !== undefined && typeof item.note !== "string") throw new PressError(`${at}: a note is text`); return { ...(hasId ? { id: key } : { thread: key }), state: item.state, ...(item.note && item.state !== "undecided" ? { note: item.note } : {}) }; }); } const n = (k, what = "post") => `${k} ${what}${k === 1 ? "" : "s"}`; function judgedSentence(out, state) { const skipped = out.skipped.length ? ` ${n(out.skipped.length, "id")} skipped: ${out.skipped[0].reason ?? "not judged"}.` : ""; const did = state === "undecided" ? "cleared" : state === "keep" ? "kept" : state === "drop" ? "dropped" : state === "later" ? "marked later" : "judged"; const archive = archiveSentence(out); // A later chunk failed: exactly how many were written, and that the rest were not. const failed = out.failed ? ` THE REST WERE NOT JUDGED: after ${n(out.failed.asked, "post")} the editor refused (${out.failed.error}), and ${n(out.failed.unasked, "post")} ${out.failed.unasked === 1 ? "was" : "were"} never asked. Undo puts back the ${out.written.length} that were written.` : ""; return `${n(out.written.length, "judgement")} ${state ? did : "written"}.${skipped}${archive ? ` ${archive}` : ""}${failed}`; } /** * POST /api/library/judge. * { lib, set: [{id | thread, state, note?}], undo? } the posts or threads named. `undo: true` is the * undo of a press: it archives nothing (and cancels no capture already queued). * { lib, bulk: { view, state, note? }, expect } every post the VIEW's filters match (the page's * URL parameters), judged post by post in chunks of at most 500. `expect` is the count the confirm * showed: when the filter no longer matches that many, nothing is judged. * Answers { ok, written, skipped, kept, archives, sentence, undo? } — `undo` (bulk) is the set that puts * every judged post back. * * @param {(route: string, init?: object) => Promise} ask * @param {any} body * @param {{ seenAt?: (lib: string, topic: string) => Promise }} [deps] */ export async function judgePress(ask, body, deps = {}) { const lib = libOf(body); if ((body.set === undefined) === (body.bulk === undefined)) throw new PressError(`give "set" (the posts or threads named) or "bulk" (everything a view's filters match), one of them`); if (body.set !== undefined) { const set = cleanSet(body.set); const out = await judge(ask, { slug: lib, by: OPERATOR, set, ...(body.undo === true ? { archive: false } : {}) }); const states = new Set(set.map((s) => s.state)); return { ok: true, ...out, sentence: body.undo === true ? `Undone: ${n(out.written.length, "judgement")} put back.` : judgedSentence(out, states.size === 1 ? set[0].state : null) }; } const bulk = body.bulk; if (!bulk || typeof bulk !== "object") throw new PressError(`"bulk" is {view, state, note?}`); if (!JUDGE_STATES.includes(bulk.state)) throw new PressError(`"bulk.state" is one of ${JUDGE_STATES.join(", ")}`); if (bulk.note !== undefined && typeof bulk.note !== "string") throw new PressError(`"bulk.note" is text`); if (!Number.isInteger(body.expect) || body.expect < 1) throw new PressError(`"expect" is the number of posts the confirm showed`); const view = { ...parseLibraryView(bulk.view && typeof bulk.view === "object" ? bulk.view : {}), lib }; const seenAt = view.fresh && view.topic && deps.seenAt ? await deps.seenAt(lib, view.topic) : null; // The rows as they are NOW, with their own judgements: the targets, and what an undo puts back. const rows = await listLibraryRows(ask, listingParamsOf(view, { seenAt })); if (rows.length !== body.expect) { throw new PressError(`The filter now matches ${n(rows.length)}, not the ${body.expect} the confirm showed: nothing was judged. Look again and press once more.`, 409); } // A bulk press judges POSTS. Clearing a post that is judged only through its thread would write nothing (it has // no entry of its own): those are left out and counted, not reported as cleared. const throughThread = bulk.state === "undecided" ? rows.filter((r) => !r.detail?.ownJudgement && r.judgement?.from === "thread") : []; const left = new Set(throughThread.map((r) => r.id)); const targets = rows.filter((r) => !left.has(r.id)).map((r) => ({ id: r.id })); const notChanged = throughThread.length ? ` ${n(throughThread.length, "post")} ${throughThread.length === 1 ? "is" : "are"} judged through ${throughThread.length === 1 ? "its" : "their"} thread: not changed (clear the thread, with Judging: the whole thread).` : ""; if (targets.length === 0) return { ok: true, written: [], skipped: [], kept: [], archives: [], asks: 0, undo: [], throughThread: throughThread.length, sentence: `Nothing cleared.${notChanged}` }; const out = await judge(ask, { slug: lib, by: OPERATOR, set: pressSetOf(targets, bulk.state, bulk.note ?? "") }); // The undo is of what WAS written: after a chunk that failed, the posts never asked are not in it. const written = new Set(out.written.map((w) => w.id)); const done = out.failed ? targets.filter((t) => written.has(t.id)) : targets; return { ok: true, ...out, ...(out.failed ? { partial: true } : {}), throughThread: throughThread.length, undo: undoSetOf(rows, done), sentence: `${judgedSentence(out, bulk.state)}${notChanged}` }; } /** * POST /api/library/seen: { lib, topics: [, …] } — Mark seen. The library and every topic are checked * THROUGH THE EDITOR'S LISTING before anything is written (umtool's own state never names a library or a topic * the editor does not hold). `mark(lib, topics)` writes (lib/library/seen.mjs markSeen). */ export async function seenPress(ask, body, { mark }) { const lib = libOf(body); if (!Array.isArray(body.topics) || body.topics.length === 0 || !body.topics.every((t) => typeof t === "string" && t)) throw new PressError(`"topics" is the list of topic ids to mark seen`); const libraries = await listLibraries(ask); if (!libraries.some((l) => l.slug === lib)) throw new PressError(`The editor has no library "${lib}".`, 404); const known = new Set((await listLibrary(ask, { slug: lib, limit: 1 })).topics.map((t) => t.id)); const unknown = body.topics.filter((t) => !known.has(t)); if (unknown.length) throw new PressError(`${lib} has no topic ${unknown.map((t) => `"${t}"`).join(", ")}: nothing was marked.`, 404); return { ok: true, ...(await mark(lib, [...new Set(body.topics)])) }; } /** * POST /api/library/watch: { lib, topic, on, intervalMinutes?, hours?, shots? } — one topic's switch, the * operator's (so it restarts a failing watch). Answers the editor's { ok, topic, watch, sentence }. */ export async function watchPress(ask, body) { const lib = libOf(body); if (typeof body.topic !== "string" || !body.topic) throw new PressError(`"topic" is the topic's id`); if (typeof body.on !== "boolean") throw new PressError(`"on" is true (watch the topic) or false (stop watching it)`); const int = (k) => { if (body[k] === undefined || body[k] === null || body[k] === "") return {}; if (!Number.isInteger(body[k])) throw new PressError(`"${k}" is a whole number`); return { [k]: body[k] }; }; return watch(ask, { slug: lib, topic: body.topic, on: body.on, ...(body.on ? { ...int("intervalMinutes"), ...int("hours"), ...(typeof body.shots === "boolean" ? { shots: body.shots } : {}) } : {}), by: OPERATOR, }); } /** * POST /api/library/purge: { lib, topic?, dryRun: true } counts; { lib, topic?, confirm } removes what that * dry run showed. The operator's, in two steps. Answers the editor's purge-trending answer. */ export async function purgePress(ask, body) { const lib = libOf(body); if (body.topic !== undefined && body.topic !== null && (typeof body.topic !== "string" || !body.topic)) throw new PressError(`"topic" is a topic's id`); const scope = { slug: lib, ...(body.topic ? { topic: body.topic } : {}) }; if (body.dryRun === true) return purge(ask, { ...scope, dryRun: true, by: OPERATOR }); if (typeof body.confirm !== "string" || !/^[0-9a-f]{16}$/.test(body.confirm)) throw new PressError(`A removal carries the "confirm" its dry run answered: press Purge, read what it would remove, then confirm.`); return purge(ask, { ...scope, confirm: body.confirm, by: OPERATOR }); } // ── lane x-trending-publish: organise, publish, archive an account ───────── const topicOf = (body, key, what) => { if (typeof body[key] !== "string" || !body[key].trim()) throw new PressError(`"${key}" is ${what}`); return body[key].trim(); }; /** * POST /api/library/organise — the editor's organise-trending, the operator's: * { lib, op: "rename", topic, title } * { lib, op: "move", to, ids: [..] | thread, create? } * { lib, op: "merge", into, from: [topic, …] } no unmerge: the page asks before it sends this * Answers the editor's answer. After a MERGE umtool's own Mark seen state follows (`deps.mergeSeen(lib, into, * from)`: the earliest mark stands), and the answer says so in `seen`. * @param {(route: string, init?: object) => Promise} ask * @param {any} body * @param {{ mergeSeen?: (lib: string, into: string, from: string[]) => Promise }} [deps] */ export async function organisePress(ask, body, deps = {}) { const lib = libOf(body); if (body.op === "rename") { return organise(ask, { slug: lib, op: "rename", topic: topicOf(body, "topic", "the topic's id"), title: topicOf(body, "title", "the topic's new name"), by: OPERATOR }); } if (body.op === "move") { const hasIds = body.ids !== undefined; const hasThread = body.thread !== undefined; if (hasIds === hasThread) throw new PressError(`a move names posts ("ids") or one thread ("thread"), one of them`); if (hasIds && (!Array.isArray(body.ids) || body.ids.length === 0 || !body.ids.every((id) => typeof id === "string" && ID.test(id)))) throw new PressError(`"ids" is a list of post ids`); if (hasThread && (typeof body.thread !== "string" || !ID.test(body.thread))) throw new PressError(`"thread" is a thread's root post id`); return organise(ask, { slug: lib, op: "move", to: topicOf(body, "to", "the topic the posts go to"), ...(hasIds ? { ids: [...new Set(body.ids)] } : { thread: body.thread }), ...(body.create === true ? { create: true } : {}), by: OPERATOR, }); } if (body.op === "merge") { const into = topicOf(body, "into", "the topic that stays"); if (!Array.isArray(body.from) || body.from.length === 0 || !body.from.every((t) => typeof t === "string" && t.trim())) throw new PressError(`"from" is the list of topics merged into it`); const out = await organise(ask, { slug: lib, op: "merge", into, from: body.from.map((t) => t.trim()), by: OPERATOR }); // The editor's ids, not the names asked with. const merged = Array.isArray(out.merged) ? out.merged.map((m) => m.id) : []; let seen = null; if (deps.mergeSeen && out.into?.id && merged.length) { try { seen = await deps.mergeSeen(lib, out.into.id, merged); } catch (err) { // The merge is done and cannot be undone: the mark not following is said, never thrown. seen = { error: err instanceof Error ? err.message : String(err) }; } } return { ...out, ...(seen ? { seen } : {}) }; } throw new PressError(`"op" is "rename", "move" or "merge"`); } /** * POST /api/library/publish: { lib, topic, dryRun: true, channel? } says what would be written; { lib, topic, * confirm, channel? } publishes what that dry run showed. The operator's, in two steps. Answers the editor's * publish-trending answer. */ export async function publishPress(ask, body) { const lib = libOf(body); const topic = topicOf(body, "topic", "the topic's id"); if (body.channel !== undefined && body.channel !== null && body.channel !== "" && (typeof body.channel !== "string" || !SLUG.test(body.channel))) { throw new PressError(`"channel" is the channel's slug: letters, digits, ".", "_" and "-"`); } const scope = { slug: lib, topic, ...(body.channel ? { channel: body.channel } : {}) }; if (body.dryRun === true) return publish(ask, { ...scope, dryRun: true, by: OPERATOR }); if (typeof body.confirm !== "string" || !/^[0-9a-f]{24}$/.test(body.confirm)) throw new PressError(`A publish carries the "confirm" its dry run answered: press Publish, read what it would write, then confirm.`); return publish(ask, { ...scope, confirm: body.confirm, by: OPERATOR }); } /** * POST /api/library/archive: { lib, handle, name?, dryRun? } — "Archive this account": the editor's * x-search-lead (action "archive") for an account of the library. It makes `-x` on NO site, WITH SYNC OFF, * and ASKS X NOTHING, now or at the scheduler's next tick: this route never sends "fetch". Answers * { ok, slug, jobIds?, dryRun?, fields?, sentence }. */ export async function archivePress(ask, body) { const lib = libOf(body); if (typeof body.handle !== "string" || !/^@?[A-Za-z0-9_]{1,30}$/.test(body.handle)) throw new PressError(`"handle" is the account's handle`); if (body.name !== undefined && typeof body.name !== "string") throw new PressError(`"name" is the account's display name`); const handle = body.handle.replace(/^@/, ""); const out = await archiveAccount(ask, { slug: lib, handle, ...(body.name ? { name: body.name } : {}), ...(body.dryRun === true ? { dryRun: true } : {}) }); return { ...out, // The made channel's sentence is the EDITOR's (sync off, nothing asked of X, how to turn sync on and run the // first fetch): nothing is added to it here. sentence: body.dryRun === true ? `Would make the channel "${out.slug}" for @${handle}, on no site, with sync off. Nothing is asked of X.` : String(out.sentence ?? `Made the channel "${out.slug}" for @${handle}, on no site.`), }; }