// POST CARDS FROM PLAY THE CUT (UI notes 2026-10-30, item 13): what the Add // post panel reads -- a channel's posts archive searched, each post's // warnings from its OWN data -- beside postsCli.mjs's addPostFromArchive (the // one write) and the editor's capture-posts (the one capture, paced there). // // The archive is `channels//posts/YYYY-MM.jsonl` (common/lib/posts-server.ts, // read only here) and its captures `channels//posts-media//`. // // THE WARNING is decided from the post's record, never from the picture: a // post that QUOTES another (`quoted`), REPOSTS one (`repostOf`) or carries // MEDIA (`mediaCount`, a forum's `media`) has a screenshot that shows them -- // somebody else's words or footage, or a thumbnail -- below its own words. // The cure is a crop (`shotMaxHeight` on the post) or another post. // // Plain ESM. import { isTrendingLibrary } from "./xTrendingMarker.mjs"; import { readFile, readdir, stat } from "node:fs/promises"; import path from "node:path"; const SLUG_RE = /^[A-Za-z0-9._-]+$/; const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; export const POST_SEARCH_MAX = 40; const who = (ref) => (ref && typeof ref.author === "string" && ref.author ? `@${ref.author.replace(/^@/, "")}` : "another account"); /** * What the post's screenshot carries besides its own words, as sentences * (empty: nothing). From the record only. * * @param {Record | null} row an archive row (common/lib/posts.ts Post) * @returns {string[]} */ export function postWarnings(row) { if (!row || typeof row !== "object") return []; const out = []; if (row.quoted && typeof row.quoted === "object") { out.push(`it quotes a post by ${who(row.quoted)}: the screenshot carries that post (someone else's words, or their video) — crop it to the post's own words, or pick another`); } if (row.repostOf && typeof row.repostOf === "object") { out.push(`it is a repost of ${who(row.repostOf)}: the screenshot is someone else's post`); } const media = Number.isInteger(row.mediaCount) && row.mediaCount > 0 ? row.mediaCount : Array.isArray(row.media) ? row.media.filter((m) => m && m.kind !== "link-card").length : 0; if (media > 0) out.push(`it carries ${media === 1 ? "a picture or video" : `${media} pictures or videos`}: the screenshot shows ${media === 1 ? "its thumbnail" : "their thumbnails"} — crop it if they are not the point`); return out; } /** The date a row was posted, `YYYY-MM-DD…`, or null. */ const dateOf = (row) => typeof row?.createdAt === "string" && row.createdAt ? row.createdAt : /^\d{8}$/.test(String(row?.uploadDate ?? "")) ? `${row.uploadDate.slice(0, 4)}-${row.uploadDate.slice(4, 6)}-${row.uploadDate.slice(6, 8)}` : null; /** * Search channel `slug`'s posts archive: every word of `q` in the post's words * or handle (any case), newest first, at most `limit`; an empty `q` is the * newest posts. Each hit with its warnings, whether its screenshot is captured, * and whether the cut carries it already. * * @param {string} channelsDir * @param {string} slug * @param {string} q * @param {{ limit?: number, manifest?: Record | null }} [o] */ export async function searchPostArchive(channelsDir, slug, q, { limit = POST_SEARCH_MAX, manifest = null } = {}) { if (!SLUG_RE.test(slug)) throw new Error(`not a channel slug: ${slug}`); // An X trending library is private: it has no archive to search here. if (await isTrendingLibrary(channelsDir, slug)) return { slug, archive: false, hits: [], total: 0 }; const dir = path.join(/* turbopackIgnore: true */ channelsDir, slug, "posts"); const names = (await readdir(dir).catch(() => null))?.filter((n) => /^\d{4}-\d{2}\.jsonl$/.test(n)).sort().reverse() ?? null; if (names === null) return { slug, archive: false, hits: [], total: 0 }; const words = String(q ?? "").toLowerCase().split(/\s+/).filter(Boolean); const byId = new Map(); for (const name of names) { const text = await readFile(path.join(dir, name), "utf8").catch(() => ""); for (const line of text.split("\n")) { if (!line.trim()) continue; let row; try { row = JSON.parse(line); } catch { continue; } if (!row || !POST_ID_RE.test(String(row.id ?? ""))) continue; byId.set(String(row.id), row); // a re-fetch appends: the last line wins } } const hay = (row) => `${row.text ?? ""} ${row.author ?? ""} ${row.authorName ?? ""}`.toLowerCase(); const matched = [...byId.values()].filter((row) => !row.isDeleted && words.every((w) => hay(row).includes(w))); matched.sort((a, b) => String(dateOf(b) ?? "").localeCompare(String(dateOf(a) ?? ""))); const inCut = new Set( (Array.isArray(manifest?.posts) ? manifest.posts : []).flatMap((p) => [p?.postId, typeof p?.id === "string" ? p.id.replace(/^(x|bsky|post)-/, "") : null]).filter(Boolean), ); const media = path.join(/* turbopackIgnore: true */ channelsDir, slug, "posts-media"); const hits = await Promise.all( matched.slice(0, limit).map(async (row) => { const id = String(row.id); const shot = await stat(path.join(media, id, "shot.png")).then(() => true, () => false); return { id, date: dateOf(row), author: typeof row.author === "string" ? row.author : null, authorName: typeof row.authorName === "string" ? row.authorName : null, text: typeof row.text === "string" ? row.text : "", url: typeof row.url === "string" ? row.url : null, platform: typeof row.platform === "string" ? row.platform : null, quoted: row.quoted && typeof row.quoted === "object" ? { author: row.quoted.author ?? null, url: row.quoted.url ?? null } : null, mediaCount: Number.isInteger(row.mediaCount) ? row.mediaCount : Array.isArray(row.media) ? row.media.length : 0, warnings: postWarnings(row), captured: shot, inCut: inCut.has(id), }; }), ); return { slug, archive: true, hits, total: matched.length }; } /** * The channels with a posts archive, the ones this cut is likeliest to want * first: those its posts already come from (`siteChannel`, a shot's * `posts-media//`), then those named like a channel it cites * (`emberparadox-x` for `emberparadox`), then the rest by name. * * @param {string} channelsDir * @param {Record | null} manifest * @param {string[]} cited the channels the cut's clips cite */ export async function postChannels(channelsDir, manifest, cited = []) { const dirs = await readdir(/* turbopackIgnore: true */ channelsDir, { withFileTypes: true }).catch(() => []); const have = []; for (const d of dirs) { if (!d.isDirectory() || !SLUG_RE.test(d.name)) continue; if (await isTrendingLibrary(channelsDir, d.name)) continue; if (await stat(path.join(/* turbopackIgnore: true */ channelsDir, d.name, "posts")).then((s) => s.isDirectory(), () => false)) have.push(d.name); } const used = new Set( (Array.isArray(manifest?.posts) ? manifest.posts : []).flatMap((p) => [ typeof p?.siteChannel === "string" ? p.siteChannel : null, typeof p?.shot === "string" ? (/^posts-media\/([^/]+)\//.exec(p.shot)?.[1] ?? null) : null, ]), ); const rank = (s) => (used.has(s) ? 0 : cited.some((c) => s.startsWith(`${c}-`) || s === c) ? 1 : 2); return have.sort((a, b) => rank(a) - rank(b) || a.localeCompare(b)).map((slug) => ({ slug, suggested: rank(slug) < 2 })); }