Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit e5db73e9be670296cc9983e591dbd692c3fe2a25
parent ed5f3c58fc76c31f516b72d68b1d67f0a79f5e09
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 11 Oct 2026 13:47:02 -0400

publish: the reports stage over a host — a site's pages or the articles, into any output root

Release 26 A2, the composeReports split. publish/reportHost.ts says whose
reports a run works on: siteReportHost (site.json `reports`, its channels +
citedChannels, its audience, its own corpus links, .export-index/sites/<id>/)
or articlesReportHost (reports/index.json narrowed to the build's audience,
any channel of the corpus — D4 —, the post visibility rule by the build's
audience, archive links only where the caller names a listed site for the
channel, .export-index/articles/, PROJECT_URL as the base).

composeReports.ts: resolveReports({paths, host}) is the resolver and
composeHostReports({paths, host, publicDir}) the writer; resolveSiteReports
and composeReports are the site's, unchanged in behaviour (every existing
compose test green, unedited). reportMedia (loadHostReports, prepare and
missingEvidenceWindows take a host), reportExportFiles and reportHistory gain
store-based twins of their site paths.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mcommon/publish/composeReports.ts | 141++++++++++++++++++++++++++++++++++++++++++++++++-------------------------------
Acommon/publish/composeReportsArticles.test.ts | 251+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/publish/reportExportFiles.ts | 45++++++++++++++++++++++++++++++++++++---------
Mcommon/publish/reportHistory.ts | 7+++++++
Acommon/publish/reportHost.ts | 140+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/publish/reportMedia.ts | 122++++++++++++++++++++++++++++++++++++++++++++++++++-----------------------------
6 files changed, 597 insertions(+), 109 deletions(-)

diff --git a/common/publish/composeReports.ts b/common/publish/composeReports.ts @@ -7,6 +7,15 @@ // earlier compose — of this site or another, public/ is shared — left under // `reports/`, `m/` and `media/`, so a site with no reports ships none. // +// ONE STAGE, TWO HOSTS (release 26, plans/reports-on-homepage.md): the stage +// is a resolver over a HOST (./reportHost.ts — whose reports, what they may +// cite, where the record links go) and a writer into an OUTPUT ROOT. +// `composeReports` / `resolveSiteReports` are the site's (its `reports`, its +// `channels` + `citedChannels`, export/public); `composeHostReports` / +// `resolveReports` take any host — the articles (`articlesReportHost`: the +// whole corpus is citable, D4; the post visibility rule by the build's +// audience) into the homepage's public dir. +// // What it reads: // - the site's `reports` (site.json, in order), each report.json parsed and // validated by the document's own checker (./reportMedia.ts @@ -66,13 +75,7 @@ import { publishFileSizeProblem } from "../lib/builtExport"; import type { Paths } from "../lib/paths"; import { resolveVideoDir } from "../lib/videoDir-server.mjs"; import { type Site } from "../lib/site"; -import { - isCitedOnlyChannel, - isCitedSite, - notInSiteMessage, - parseSiteUrl, - siteCitableChannelSlugs, -} from "../lib/siteSchema"; +import { storeReportDir } from "../lib/report/store"; import { getSettings } from "../lib/settings"; import { postsVisibleTo } from "../lib/postsVisibility"; import { assertChannelTextReadable } from "../lib/channelMedia"; @@ -137,14 +140,14 @@ import { import { citedEvidenceSpan, isAudioOnlyPlatform, type EvidenceSpan } from "../lib/evidenceClip-server"; import { citedMoments, - loadSiteReports, - readReportMediaIndex, - reportMediaDir, - siteReportDir, + loadHostReports, + readStoreMediaIndex, + storeMediaDir, type ReportMediaEntry, } from "./reportMedia"; -import { publishableReportExports, reportFileSha256, type PublishableReportExports } from "./reportExportFiles"; -import { publishReportHistory, readReportHistoryView, reportHistoryGitDir, reportHistoryRef } from "./reportHistory"; +import { publishableStoreExports, storeReportFileSha256, type PublishableReportExports } from "./reportExportFiles"; +import { publishReportHistory, readReportHistoryView, reportHistoryRef, storeHistoryGitDir } from "./reportHistory"; +import { hostCorpusLink, siteReportHost, type ReportHost } from "./reportHost"; import type { ReportHistoryRef, ReportHistoryView } from "../lib/report/revisions"; // The public dir's entries this stage owns. Every compose removes them first. @@ -223,6 +226,10 @@ export type ComposeReportsOptions = { site: Site; // Default: paths.exportPublicDir. publicDir?: string; +} & ComposeStageOptions; + +// What the stage takes besides whose reports and where they go. +type ComposeStageOptions = { // Let a citation without prepared media through (`--allow-missing-media`). allowMissingMedia?: boolean; // `social.x.visibility` and friends; default the live settings. @@ -365,10 +372,6 @@ const isoDay = (uploadDate: string | undefined): string | undefined => ? `${uploadDate.slice(0, 4)}-${uploadDate.slice(4, 6)}-${uploadDate.slice(6, 8)}` : undefined; -// A record in this site's corpus — the viewer's `?v=` link (a FULL site only). -function corpusLink(slug: string, params: Record<string, string>): string { - return `/?${new URLSearchParams({ v: slug, ...params }).toString()}`; -} const cueLine = (text: string) => text.replace(/\s+/g, " ").trim(); @@ -454,7 +457,7 @@ const sameSpan = (a: EvidenceSpan, b: EvidenceSpan) => // ─── Resolving: the reports as views, nothing written ─── -export type ResolveSiteReportsOptions = Omit<ComposeReportsOptions, "publicDir"> & { +type ResolveViewOptions = { // Each report's downloads, as its view carries them. downloads?: (reportId: string) => ReportDownloads | undefined; // Each report's newest revision, as its view carries it. @@ -463,6 +466,11 @@ export type ResolveSiteReportsOptions = Omit<ComposeReportsOptions, "publicDir"> feeds?: (reportId: string) => ReportFeeds | undefined; }; +export type ResolveSiteReportsOptions = Omit<ComposeReportsOptions, "publicDir"> & ResolveViewOptions; + +// Any host's reports (./reportHost.ts). +export type ResolveReportsOptions = { paths: Paths; host: ReportHost } & ComposeStageOptions & ResolveViewOptions; + // The site's reports resolved against the corpus — verified, their views and // moment pages built, their prepared media matched — and nothing written. // compose writes what this answers; publish/reportExports.ts renders the same @@ -480,16 +488,23 @@ export type ResolvedSiteReports = { }; export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promise<ResolvedSiteReports> { - const { paths, site } = opts; + const { site, ...rest } = opts; + return resolveReports({ ...rest, host: siteReportHost(opts.paths, site) }); +} + +export async function resolveReports(opts: ResolveReportsOptions): Promise<ResolvedSiteReports> { + const { paths, host } = opts; const log = opts.log ?? (() => {}); const now = (opts.now?.() ?? new Date()).toISOString(); - const citedSite = isCitedSite(site); - // No corpus page to link a moment to: a cited site publishes none, and a - // cited-only channel (`citedChannels`) is not in the site's corpus. - const noCorpus = (slug: string) => citedSite || isCitedOnlyChannel(site, slug); + // A record's link into an archive (the host's corpus base), or none: a + // cited site and a cited-only channel have no corpus page to link to. + const corpusLink = (channel: string, slug: string, params: Record<string, string>) => + hostCorpusLink(host, channel, { v: slug, ...params }); + // How a refusal names who may not carry a post. + const carrier = host.kind === "site" ? "this site" : "the articles"; const problems: ComposeReportsProblem[] = []; - const loaded = await loadSiteReports(paths, site); + const loaded = await loadHostReports(host); for (const p of loaded.problems) { problems.push({ kind: p.kind === "missing-report" ? "missing-report" : "invalid-report", @@ -504,9 +519,6 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi const momentCues = new Map<string, Cue[]>(); const settings = opts.settings ?? getSettings(); - // What a report on this site may cite: the pool plus its cited-only - // channels. Never a publish set — only the cited moments publish. - const citable = siteCitableChannelSlugs(site); const configs = new Map<string, ChannelConfig | null>(); const configOf = async (slug: string) => { if (!configs.has(slug)) configs.set(slug, await readChannelConfig(paths, slug).catch(() => null)); @@ -542,13 +554,14 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi }; // Resolve and verify every citation the reports cite. A channel outside the - // site's citable set (`channels` plus `citedChannels`), or a post the site - // may not carry, is refused before its record is read. + // host's citable set (a site's `channels` plus `citedChannels`; for the + // articles the corpus), or a post the host may not carry, is refused before + // its record is read. Never a publish set — only the cited moments publish. const refusedChannel = new Set<string>(); for (const report of reports) { // The report's video and its poster: on disk, and small enough to publish. if (report.video) { - const dir = siteReportDir(paths, site.siteId, report.id); + const dir = storeReportDir(host, report.id); for (const rel of [report.video.src, report.video.poster]) { if (!rel) continue; const st = await stat(path.join(dir, rel)).catch(() => null); @@ -566,15 +579,16 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi if (c.kind === "source" || c.kind === "page") { delete c.verification; if (c.kind === "source" && c.image) { - const src = path.join(siteReportDir(paths, site.siteId, report.id), c.image); + const src = path.join(storeReportDir(host, report.id), c.image); if (!(await isFile(src))) { problems.push({ kind: "missing-still", citation: ref, report: report.id, message: `the still ${c.image} does not exist` }); } } continue; } - if (!citable.has(c.channel)) { - problems.push({ kind: "not-in-site", citation: ref, report: report.id, message: notInSiteMessage(c.channel) }); + const notCitable = host.citableProblem(c.channel); + if (notCitable) { + problems.push({ kind: "not-in-site", citation: ref, report: report.id, message: notCitable }); refusedChannel.add(c.channel); continue; } @@ -584,8 +598,8 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi continue; } if (c.kind === "post") { - if (!postsVisibleTo(site, await configOf(c.channel), settings)) { - problems.push({ kind: "not-visible", citation: ref, report: report.id, message: `this site may not carry posts of "${c.channel}" (the post visibility rule)` }); + if (!postsVisibleTo(host, await configOf(c.channel), settings)) { + problems.push({ kind: "not-visible", citation: ref, report: report.id, message: `${carrier} may not carry posts of "${c.channel}" (the post visibility rule)` }); continue; } const post = await postOf(c.channel, c.id); @@ -621,15 +635,15 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi } // The prepared media, per moment. - const media = await readReportMediaIndex(paths, site.siteId); - const cacheDir = reportMediaDir(paths, site.siteId); + const media = await readStoreMediaIndex(host); + const cacheDir = storeMediaDir(host); const citedIn = buildCitedIn(reports); const momentInfo = new Map(citedMoments(reports).map((m) => [m.key, m])); const mediaOf = new Map<string, ReportMediaEntry>(); for (const key of Object.keys(citedIn)) { const m = momentInfo.get(key); if (!m || refusedChannel.has(m.moment.channel)) continue; - const entry = media?.siteId === site.siteId ? media.moments[key] : undefined; + const entry = media?.siteId === host.id ? media.moments[key] : undefined; const citedBy = citedIn[key].map((e) => `${e.reportId}#${e.citationId}`); const missing = (kind: ComposeReportsProblemKind, message: string) => problems.push({ kind, moment: key, message: `${message} (cited by ${[...new Set(citedBy)].join(", ")})` }); @@ -676,7 +690,7 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi date: post.createdAt.slice(0, 10), platform: post.platform, originalUrl: post.url, - corpusUrl: noCorpus(c.channel) ? undefined : corpusLink(`${c.channel}/${c.id}`, { vm: "post" }), + corpusUrl: corpusLink(c.channel, `${c.channel}/${c.id}`, { vm: "post" }), }); } const { summary, archiveOrg, wayback } = (await recordOf(c.channel, c.id))!; @@ -698,7 +712,7 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi originalUrl: links.original.url, originalLabel: links.original.label, downloads: [links.copy], - corpusUrl: noCorpus(c.channel) ? undefined : corpusLink(summary.slug ?? `${c.channel}/${summary.id}`, seconds > 0 ? { t: String(seconds) } : {}), + corpusUrl: corpusLink(c.channel, summary.slug ?? `${c.channel}/${summary.id}`, seconds > 0 ? { t: String(seconds) } : {}), }); } if (summary.platform === "archiveorg") { @@ -715,7 +729,7 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi originalUrl: links.original?.url ?? (summary.webpageUrl || undefined), originalLabel: links.original?.label, downloads: links.downloads.length > 0 ? links.downloads : undefined, - corpusUrl: noCorpus(c.channel) ? undefined : corpusLink(summary.slug ?? `${c.channel}/${summary.id}`, seconds > 0 ? { t: String(seconds) } : {}), + corpusUrl: corpusLink(c.channel, summary.slug ?? `${c.channel}/${summary.id}`, seconds > 0 ? { t: String(seconds) } : {}), }); } return defined({ @@ -730,7 +744,7 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi : (platformMomentUrl(summary.webpageUrl, summary.platform as Platform, c.start) ?? undefined), // The viewer keys a record by its PUBLISHED slug, which on a platform // with two ids is not the data dir's name. - corpusUrl: noCorpus(c.channel) ? undefined : corpusLink(summary.slug ?? `${c.channel}/${summary.id}`, seconds > 0 ? { t: String(seconds) } : {}), + corpusUrl: corpusLink(c.channel, summary.slug ?? `${c.channel}/${summary.id}`, seconds > 0 ? { t: String(seconds) } : {}), }); }; // buildReportPageView's resolver is synchronous: resolve every cited @@ -840,8 +854,25 @@ export async function resolveSiteReports(opts: ResolveSiteReportsOptions): Promi // ─── The stage ─── export async function composeReports(opts: ComposeReportsOptions): Promise<ComposedReports> { - const { paths, site } = opts; - const publicDir = opts.publicDir ?? paths.exportPublicDir; + const { site, publicDir, ...rest } = opts; + return composeHostReports({ + ...rest, + host: siteReportHost(opts.paths, site), + publicDir: publicDir ?? opts.paths.exportPublicDir, + }); +} + +export type ComposeHostReportsOptions = { + paths: Paths; + host: ReportHost; + // The output root: `reports/`, `m/` and `media/` are written under it (and + // removed from it first). + publicDir: string; +} & ComposeStageOptions; + +// The stage for any host (./reportHost.ts), into any output root. +export async function composeHostReports(opts: ComposeHostReportsOptions): Promise<ComposedReports> { + const { paths, host, publicDir } = opts; const log = opts.log ?? (() => {}); // Whatever an earlier compose left. rm removes a link, never its target (a @@ -849,7 +880,7 @@ export async function composeReports(opts: ComposeReportsOptions): Promise<Compo for (const entry of REPORT_PUBLIC_ENTRIES) { await rm(path.join(publicDir, entry), { recursive: true, force: true }); } - if ((site.reports ?? []).length === 0) { + if (host.published.length === 0) { log("[reports] none published."); return { reports: [], moments: [], allowed: [] }; } @@ -857,8 +888,8 @@ export async function composeReports(opts: ComposeReportsOptions): Promise<Compo // Each report's exports (publish/reportExports.ts), made from the report // as it is now and small enough to publish; the citations as files always. const exportsOf = new Map<string, PublishableReportExports>(); - for (const id of site.reports ?? []) { - const found = await publishableReportExports(paths, site.siteId, id); + for (const id of host.published) { + const found = await publishableStoreExports(host, id); exportsOf.set(id, found); for (const note of found.notes) log(`[reports] ${id}: ${note}`); } @@ -866,12 +897,12 @@ export async function composeReports(opts: ComposeReportsOptions): Promise<Compo // anything is written; a report never exported has none. const histories = new Map<string, { view: ReportHistoryView; ref: ReportHistoryRef; gitDir: string }>(); const historyProblems: ComposeReportsProblem[] = []; - for (const id of site.reports ?? []) { - const gitDir = reportHistoryGitDir(paths, site.siteId, id); + for (const id of host.published) { + const gitDir = storeHistoryGitDir(host, id); try { - const view = await readReportHistoryView(gitDir, { reportId: id, siteUrl: site.siteUrl }); + const view = await readReportHistoryView(gitDir, { reportId: id, siteUrl: host.siteUrl }); if (!view) continue; - const ref = reportHistoryRef(view, await reportFileSha256(paths, site.siteId, id)); + const ref = reportHistoryRef(view, await storeReportFileSha256(host, id)); if (!ref.current) log(`[reports] ${id}: report.json changed since revision ${ref.revision} — export again to commit it`); histories.set(id, { view, ref, gitDir }); } catch (e) { @@ -884,8 +915,8 @@ export async function composeReports(opts: ComposeReportsOptions): Promise<Compo } if (historyProblems.length > 0) throw new ComposeReportsError(historyProblems); // A timeline's feeds link absolutely: a site with no public URL publishes none. - const siteUrl = parseSiteUrl(site.siteUrl); - const { reports, views, index, moments, mediaOf, cacheDir, allowed } = await resolveSiteReports({ + const siteUrl = host.siteUrl; + const { reports, views, index, moments, mediaOf, cacheDir, allowed } = await resolveReports({ ...opts, history: (id) => histories.get(id)?.ref, feeds: siteUrl ? (id) => reportFeedUrls(siteUrl, id) : undefined, @@ -913,7 +944,7 @@ export async function composeReports(opts: ComposeReportsOptions): Promise<Compo log(`[reports] ${report.id}: feeds of ${view.entries?.length ?? 0} timeline entr${view.entries?.length === 1 ? "y" : "ies"}.`); } if (report.video && view.video) { - const dir = siteReportDir(paths, site.siteId, report.id); + const dir = storeReportDir(host, report.id); await copyOut(publicDir, path.join(dir, report.video.src), view.video.src); if (report.video.poster && view.video.poster) { await copyOut(publicDir, path.join(dir, report.video.poster), view.video.poster); @@ -922,7 +953,7 @@ export async function composeReports(opts: ComposeReportsOptions): Promise<Compo for (const c of orderedCitations(view)) { if (c.kind !== "source" || !c.image) continue; const rel = (report.citations![c.id] as { image: string }).image; - await copyOut(publicDir, path.join(siteReportDir(paths, site.siteId, report.id), rel), c.image); + await copyOut(publicDir, path.join(storeReportDir(host, report.id), rel), c.image); } const exported = exportsOf.get(report.id)?.files ?? {}; for (const f of REPORT_EXPORT_FORMATS) { diff --git a/common/publish/composeReportsArticles.test.ts b/common/publish/composeReportsArticles.test.ts @@ -0,0 +1,251 @@ +// The reports stage over the ARTICLES host (release 26 A2): the same resolver +// and writer a site's compose runs, fed the article store +// (transcripts/reports/, index.json, `audience`) and written into another +// output root — the homepage's public dir. A temp corpus only. +// +// - the whole corpus is citable (D4): a channel no site has is cited; +// - a public build carries only `audience: "public"` articles; a private one +// every published article, in index.json's order; +// - the post visibility rule holds by the build's audience; +// - a record links into the archive the host names for its channel, or +// nowhere; +// - export/public is not touched. +// +// Run with: node_modules/.bin/tsx --test publish/composeReportsArticles.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +const ROOT = mkdtempSync(path.join(tmpdir(), "compose-articles-")); +Object.assign(process.env, { + TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"), + SAVED_VIDEOS_DIR: path.join(ROOT, "saved-videos"), + SITES_DIR: path.join(ROOT, "transcripts", "sites"), + SETTINGS_FILE: path.join(ROOT, "settings.json"), + EXPORT_PUBLIC_DIR: path.join(ROOT, "public"), + EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"), + EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"), +}); +after(() => rmSync(ROOT, { recursive: true, force: true })); + +const { getPaths } = await import("../lib/paths"); +const { writePosts } = await import("../lib/posts-server"); +const { setPublished, configureArticle, articleDir } = await import("../lib/report/registry"); +const { articlesReportHost, articleNotInCorpusMessage } = await import("./reportHost"); +const { composeHostReports, ComposeReportsError } = await import("./composeReports"); +const { REPORT_MEDIA_FORMAT, REPORT_MEDIA_VERSION, storeMediaDir, storeMediaIndexFile } = await import("./reportMedia"); + +const paths = getPaths(); +const OUT = path.join(ROOT, "homepage-public"); +const LONE = "lone-channel"; +const X = "x-posts"; +const X_PRIVATE = { social: { x: { visibility: "private" } } }; + +const writeJson = (file: string, value: unknown) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, JSON.stringify(value, null, 2)); +}; +const readJson = <T = Record<string, unknown>>(file: string): T => JSON.parse(readFileSync(file, "utf8")) as T; + +function filesUnder(dir: string): string[] { + const out: string[] = []; + const walk = (d: string, rel: string) => { + for (const e of readdirSync(d, { withFileTypes: true })) { + const r = rel ? `${rel}/${e.name}` : e.name; + if (e.isDirectory()) walk(path.join(d, e.name), r); + else out.push(r); + } + }; + if (existsSync(dir)) walk(dir, ""); + return out.sort(); +} + +const ts = (s: number) => new Date(s * 1000).toISOString().slice(11, 23); +const vtt = (cues: [number, number, string][]) => + "WEBVTT\nKind: captions\nLanguage: en\n\n" + + cues.map(([a, b, text]) => `${ts(a)} --> ${ts(b)} align:start position:0%\n${text}<${ts(a)}><c></c>\n`).join("\n"); + +const SPAN = { kind: "video", channel: LONE, id: "abc123", start: 10, end: 20, quote: "The bridge opened in the spring, I was there for it." }; +const POST = { kind: "post", channel: X, id: "1800", quote: "Posted to settle it" }; + +function article(id: string, citations: Record<string, unknown>, over: Record<string, unknown> = {}) { + const cited = Object.keys(citations).map((c) => `[${c}](cite:${c})`).join(", "); + return { + format: "archilyzer-report", + version: 1, + id, + kind: "sweep", + title: `Article ${id}`, + sections: [{ id: "s1", title: "What was said", body: `It was said: ${cited}.` }], + citations, + ...over, + }; +} + +function seedArticle(id: string, citations: Record<string, unknown>, over: Record<string, unknown> = {}) { + writeJson(path.join(articleDir(paths, id), "report.json"), article(id, citations, over)); +} + +async function seed() { + writeJson(paths.settingsFile, {}); + // A channel no site has: an article may cite it (D4). + writeJson(path.join(paths.channelsDir, LONE, "config.json"), { + handling: "youtube", + name: "Lone Channel", + url: "https://www.youtube.com/@lone/videos", + }); + const abc = path.join(paths.channelsDir, LONE, "data", "abc123"); + writeJson(path.join(abc, "metadata.info.json"), { + id: "abc123", + title: "A lone stream", + channel: LONE, + upload_date: "20260110", + duration: 600, + webpage_url: "https://www.youtube.com/watch?v=abc123", + extractor_key: "Youtube", + }); + writeFileSync( + path.join(abc, "transcript.en.vtt"), + vtt([ + [6, 10, "Let me be clear about this one."], + [10, 15, "The bridge opened in the spring,"], + [15, 20, "I was there for it."], + [20, 30, "Anyway, back to the mail."], + ]), + ); + // An X channel: its posts are private while `social.x.visibility` is. + writeJson(path.join(paths.channelsDir, X, "config.json"), { + handling: "youtube", + name: "Some X account", + url: "https://x.com/someone", + sourceKind: "social", + platform: "twitter", + socialHandle: "someone", + }); + await writePosts(path.join(paths.channelsDir, X), [ + { + id: "1800", + slug: `${X}/1800`, + channelSlug: X, + author: "someone", + authorName: "Someone", + createdAt: "2025-03-14T12:00:00.000Z", + uploadDate: "20250314", + text: "Posted to settle it. The bridge was open before I got there.", + url: "https://x.com/someone/status/1800", + platform: "twitter", + isReply: false, + isRepost: false, + links: [], + }, + ]); + + seedArticle("art-pub", { c01: SPAN }); + seedArticle("art-priv", { p01: POST }); + seedArticle("art-draft", { c01: SPAN }); + await setPublished("art-priv", true, {}, paths); + await configureArticle("art-pub", { published: true, audience: "public" }, paths); + + // What `archilyzer reports prepare --article` leaves. + const media = storeMediaDir({ stagingDir: path.join(paths.exportIndexDir, "articles") }); + const hash = "0".repeat(31) + "1"; + writeFileSync(path.join((mkdirSync(media, { recursive: true }), media), `${hash}.mp4`), "video-bytes"); + writeJson(path.join(media, `${hash}.json`), { span: { from: 10, to: 20 } }); + mkdirSync(path.join(media, "posts", X, "1800"), { recursive: true }); + writeFileSync(path.join(media, "posts", X, "1800", "shot.png"), "shot"); + writeJson(storeMediaIndexFile({ stagingDir: path.join(paths.exportIndexDir, "articles") }), { + format: REPORT_MEDIA_FORMAT, + version: REPORT_MEDIA_VERSION, + siteId: "articles", + preparedAt: "2026-10-11T00:00:00.000Z", + moments: { + [`${LONE}/abc123/10.00-20.00`]: { kind: "video", file: `${hash}.mp4`, bytes: 11, sha256: "f".repeat(64), width: null, height: null, durationSec: 15 }, + [`${X}/1800`]: { kind: "post", file: `posts/${X}/1800/shot.png`, bytes: 4, sha256: "e".repeat(64), width: null, height: null, durationSec: null, media: [] }, + }, + problems: [], + }); +} + +await seed(); + +const quiet = { log: () => {} }; + +test("a private build: every published article in index.json's order, any corpus channel, posts by its audience", async () => { + const host = await articlesReportHost(paths, { audience: "private" }); + assert.deepEqual(host.published, ["art-priv", "art-pub"]); + const composed = await composeHostReports({ paths, host, publicDir: OUT, settings: X_PRIVATE, ...quiet }); + assert.deepEqual(composed.reports.map((r) => r.id), ["art-priv", "art-pub"]); + assert.deepEqual(composed.moments, [`${LONE}/abc123/10.00-20.00`, `${X}/1800`]); + const index = readJson<{ reports: { id: string }[] }>(path.join(OUT, "reports", "index.json")); + assert.deepEqual(index.reports.map((r) => r.id), ["art-priv", "art-pub"]); + assert.ok(existsSync(path.join(OUT, "media", "clips", LONE, "abc123", "10.00-20.00.mp4"))); + assert.ok(existsSync(path.join(OUT, "media", "posts", X, "1800", "shot.png"))); + // The draft is not published. + assert.equal(existsSync(path.join(OUT, "reports", "art-draft")), false); + // No archive named for the channel: the record links nowhere. + const moment = readJson<{ record: { corpusUrl?: string } }>(path.join(OUT, "m", LONE, "abc123", "10.00-20.00", "moment.json")); + assert.equal(moment.record.corpusUrl, undefined); + // Feeds and history use the homepage's base (PROJECT_URL by default). + assert.equal(host.siteUrl, "https://archilyzer.pages.dev"); + // export/public is not this stage's output root here. + assert.equal(existsSync(path.join(paths.exportPublicDir, "reports")), false); +}); + +test("a public build: only public articles; a record links into the listed site that publishes its channel", async () => { + const host = await articlesReportHost(paths, { + audience: "public", + channelSiteUrl: (slug) => (slug === LONE ? "https://lone.example.test/" : undefined), + }); + assert.deepEqual(host.published, ["art-pub"]); + const composed = await composeHostReports({ paths, host, publicDir: OUT, settings: X_PRIVATE, ...quiet }); + assert.deepEqual(composed.reports.map((r) => r.id), ["art-pub"]); + // The earlier build's output is gone, the private article's post with it. + assert.deepEqual( + filesUnder(OUT).filter((f) => !f.startsWith("reports/art-pub/")), + ["m/index.json", `m/${LONE}/abc123/10.00-20.00/moment.json`, `media/clips/${LONE}/abc123/10.00-20.00.mp4`, "reports/index.json"], + ); + const moment = readJson<{ record: { corpusUrl?: string } }>(path.join(OUT, "m", LONE, "abc123", "10.00-20.00", "moment.json")); + assert.equal(moment.record.corpusUrl, `https://lone.example.test/?v=${encodeURIComponent(`${LONE}/abc123`)}&t=10`); +}); + +test("refused: an X post in a public build, a channel the corpus does not have", async () => { + seedArticle("art-pub", { c01: SPAN, p01: POST }, { audience: "public" }); + seedArticle("art-priv", { p01: POST, c09: { ...SPAN, channel: "no-such-channel" } }); + try { + const pub = await articlesReportHost(paths, { audience: "public" }); + await assert.rejects(composeHostReports({ paths, host: pub, publicDir: OUT, settings: X_PRIVATE, ...quiet }), (e: unknown) => { + assert.ok(e instanceof ComposeReportsError); + assert.deepEqual( + e.problems.map((p) => [p.kind, p.citation, p.message]), + [["not-visible", "art-pub#p01", `the articles may not carry posts of "${X}" (the post visibility rule)`]], + ); + return true; + }); + // With X posts public, the same build carries the post. + await composeHostReports({ paths, host: pub, publicDir: OUT, settings: {}, ...quiet }); + assert.ok(existsSync(path.join(OUT, "m", X, "1800", "moment.json"))); + + const priv = await articlesReportHost(paths, { audience: "private" }); + await assert.rejects(composeHostReports({ paths, host: priv, publicDir: OUT, settings: X_PRIVATE, ...quiet }), (e: unknown) => { + assert.ok(e instanceof ComposeReportsError); + assert.deepEqual( + e.problems.map((p) => [p.kind, p.citation, p.message]), + [["not-in-site", "art-priv#c09", articleNotInCorpusMessage("no-such-channel")]], + ); + return true; + }); + } finally { + seedArticle("art-pub", { c01: SPAN }, { audience: "public" }); + seedArticle("art-priv", { p01: POST }); + } +}); + +test("nothing published: the stage writes nothing and clears the output root's reports", async () => { + const host = await articlesReportHost(paths, { audience: "public", published: [] }); + const composed = await composeHostReports({ paths, host, publicDir: OUT, ...quiet }); + assert.deepEqual(composed, { reports: [], moments: [], allowed: [] }); + assert.deepEqual(filesUnder(OUT), []); +}); diff --git a/common/publish/reportExportFiles.ts b/common/publish/reportExportFiles.ts @@ -22,22 +22,31 @@ import { readJsonFile } from "../lib/jsonFile-server"; import type { Paths } from "../lib/paths"; import type { ReportExportFooter } from "../lib/report/exportHtml"; import { REPORT_EXPORT_FILENAMES, REPORT_EXPORT_FORMATS, type ReportExportFormat } from "../lib/report/views"; -import { siteIndexDir } from "../lib/site"; -import { siteReportFile } from "./reportMedia"; +import { siteReportStore, storeReportFile, type ReportStore } from "../lib/report/store"; export const REPORT_EXPORTS_DIRNAME = "report-exports"; export const REPORT_EXPORT_MANIFEST_FILENAME = "export.json"; export const REPORT_EXPORT_MANIFEST_FORMAT = "archilyzer-report-export"; export const REPORT_EXPORT_MANIFEST_VERSION = 1; +// `<staging>/report-exports/` of any store (lib/report/store.ts): a site's +// `.export-index/sites/<siteId>/`, the articles' `.export-index/articles/`. +export function storeExportsDir(store: Pick<ReportStore, "stagingDir">): string { + return path.join(store.stagingDir, REPORT_EXPORTS_DIRNAME); +} + +export function storeExportDir(store: Pick<ReportStore, "stagingDir">, reportId: string): string { + return path.join(storeExportsDir(store), reportId); +} + // `.export-index/sites/<siteId>/report-exports/`. export function reportExportsDir(paths: Paths, siteId: string): string { - return path.join(siteIndexDir(paths, siteId), REPORT_EXPORTS_DIRNAME); + return storeExportsDir(siteReportStore(paths, siteId)); } // `.export-index/sites/<siteId>/report-exports/<reportId>/`. export function reportExportDir(paths: Paths, siteId: string, reportId: string): string { - return path.join(reportExportsDir(paths, siteId), reportId); + return storeExportDir(siteReportStore(paths, siteId), reportId); } export type ReportExportFileEntry = { @@ -79,8 +88,12 @@ export function sha256Hex(data: string | Uint8Array): string { // The sha256 of a report.json as it is on disk, or null when it is unreadable. export async function reportFileSha256(paths: Paths, siteId: string, reportId: string): Promise<string | null> { + return storeReportFileSha256(siteReportStore(paths, siteId), reportId); +} + +export async function storeReportFileSha256(store: Pick<ReportStore, "reportsDir">, reportId: string): Promise<string | null> { try { - return sha256Hex(await readFile(siteReportFile(paths, siteId, reportId))); + return sha256Hex(await readFile(storeReportFile(store, reportId))); } catch { return null; } @@ -91,7 +104,14 @@ export async function readReportExportManifest( siteId: string, reportId: string, ): Promise<ReportExportManifest | null> { - const read = await readJsonFile(path.join(reportExportDir(paths, siteId, reportId), REPORT_EXPORT_MANIFEST_FILENAME)); + return readStoreExportManifest(siteReportStore(paths, siteId), reportId); +} + +export async function readStoreExportManifest( + store: Pick<ReportStore, "stagingDir">, + reportId: string, +): Promise<ReportExportManifest | null> { + const read = await readJsonFile(path.join(storeExportDir(store, reportId), REPORT_EXPORT_MANIFEST_FILENAME)); if (!read.ok) return null; const v = read.value as Partial<ReportExportManifest> | null; if (!v || v.format !== REPORT_EXPORT_MANIFEST_FORMAT || v.version !== REPORT_EXPORT_MANIFEST_VERSION) return null; @@ -113,16 +133,23 @@ export async function publishableReportExports( siteId: string, reportId: string, ): Promise<PublishableReportExports> { - const manifest = await readReportExportManifest(paths, siteId, reportId); + return publishableStoreExports(siteReportStore(paths, siteId), reportId); +} + +export async function publishableStoreExports( + store: Pick<ReportStore, "stagingDir" | "reportsDir">, + reportId: string, +): Promise<PublishableReportExports> { + const manifest = await readStoreExportManifest(store, reportId); if (!manifest) return { files: {}, notes: [] }; - const current = await reportFileSha256(paths, siteId, reportId); + const current = await storeReportFileSha256(store, reportId); if (current !== manifest.reportSha256) { return { files: {}, notes: ["its exports were made from another version of report.json — export again; none are published"], }; } - const dir = reportExportDir(paths, siteId, reportId); + const dir = storeExportDir(store, reportId); const files: PublishableReportExports["files"] = {}; const notes: string[] = []; for (const f of REPORT_EXPORT_FORMATS) { diff --git a/common/publish/reportHistory.ts b/common/publish/reportHistory.ts @@ -72,6 +72,7 @@ import { cleanGitEnv } from "./sourceAudit"; export { REPORT_HISTORY_REPO_FILE_RE }; import { siteReportDir } from "./reportMedia"; +import { storeReportDir, type ReportStore } from "../lib/report/store"; export const REPORT_HISTORY_GIT_DIRNAME = "history-git"; export const REVISION_EXPORTS_FILENAME = "exports.json"; @@ -88,6 +89,12 @@ export function reportHistoryGitDir(paths: Paths, siteId: string, reportId: stri return path.join(siteReportDir(paths, siteId, reportId), REPORT_HISTORY_GIT_DIRNAME); } +// `<report dir>/history-git/` in any store (lib/report/store.ts): an article's +// is `reports/<reportId>/history-git/`. +export function storeHistoryGitDir(store: Pick<ReportStore, "reportsDir">, reportId: string): string { + return path.join(storeReportDir(store, reportId), REPORT_HISTORY_GIT_DIRNAME); +} + // ─── git, with nothing of the operator's ─── export type HistoryIdentity = { name: string; email: string }; diff --git a/common/publish/reportHost.ts b/common/publish/reportHost.ts @@ -0,0 +1,140 @@ +// WHO PUBLISHES A SET OF REPORTS — the one thing the reports stage +// (./composeReports.ts), prepare (./reportMedia.ts), export +// (./reportExports.ts) and check (bin/reports-check.ts) need to know about +// whoever publishes the reports they work on (release 26, +// plans/reports-on-homepage.md, "The model"): +// +// a SITE (its pages) the ARTICLES (the homepage) +// files sites/<id>/reports/<r>/ reports/<r>/ +// published site.json `reports` reports/index.json, narrowed +// to `audience: "public"` for a +// public build +// may cite its `channels` + `citedChannels` any channel in the corpus (D4) +// posts the visibility rule, by the the same rule, by the +// site's audience build's audience +// corpus link its own corpus, relative (none the listed public site that +// on a cited site or for a publishes the channel, +// cited-only channel) absolute; none without one +// staging .export-index/sites/<id>/ .export-index/articles/ +// history identity the site's title, PROJECT_NAME, +// noreply@<id>.invalid noreply@articles.invalid +// +// A host is built once per run and carries no I/O of its own but the +// articles' corpus check (a channel directory exists). + +import { statSync } from "node:fs"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { PROJECT_NAME, PROJECT_URL } from "../lib/project"; +import { + isCitedOnlyChannel, + isCitedSite, + isPrivateSite, + notInSiteMessage, + parseSiteUrl, + siteCitableChannelSlugs, + type Site, +} from "../lib/siteSchema"; +import { publishedArticleIds } from "../lib/report/registry"; +import type { ReportAudience } from "../lib/report/schema"; +import { articleReportStore, siteReportStore, type ReportStore } from "../lib/report/store"; + +export type ReportHost = ReportStore & { + // A history commit's author (./reportHistory.ts) and an export's heading. + title: string; + // The public base a feed, an export's links and the history clone use + // (absolute, no trailing slash), or undefined: none. + siteUrl?: string; + // The site's accent (slides), when it has one. + accent?: unknown; + // Whose post-visibility rule applies (lib/postsVisibility.ts). + audience: ReportAudience; + // The published reports, in order. + published: readonly string[]; + // How a message names the list: `the site lists report "x"`. + listedBy: (reportId: string) => string; + // Why a channel may not be cited here, or null when it may. + citableProblem: (slug: string) => string | null; + // Where a moment's record opens in an archive: "" (this site's own corpus, + // a site-root link), an absolute archive base, or null (no link). + corpusBase: (slug: string) => string | null; + // The site, for a site host. + site?: Site; +}; + +// A site's pages. +export function siteReportHost(paths: Pick<Paths, "sitesDir" | "exportSitesIndexDir">, site: Site): ReportHost { + const citable = siteCitableChannelSlugs(site); + const cited = isCitedSite(site); + return { + ...siteReportStore(paths, site.siteId), + title: site.siteTitle?.trim() || site.siteId, + siteUrl: parseSiteUrl(site.siteUrl), + accent: site.accent, + audience: isPrivateSite(site) ? "private" : "public", + published: site.reports ?? [], + listedBy: (id) => `the site lists report "${id}"`, + citableProblem: (slug) => (citable.has(slug) ? null : notInSiteMessage(slug)), + // No corpus page to link a moment to: a cited site publishes none, and a + // cited-only channel (`citedChannels`) is not in the site's corpus. + corpusBase: (slug) => (cited || isCitedOnlyChannel(site, slug) ? null : ""), + site, + }; +} + +export type ArticlesHostOptions = { + // The build's audience: "public" carries only `audience: "public"` articles, + // "private" every published one. Default "private". + audience?: ReportAudience; + // The homepage's public base. Default PROJECT_URL; null = none. + siteUrl?: string | null; + // channel slug → the base URL of the listed public site that publishes it + // (the homepage's `channel-sites.json` with each site's `siteUrl`); a + // moment of a channel it does not answer for gets no archive link. + channelSiteUrl?: (slug: string) => string | undefined; + // The published ids, when the caller has them (a check of named drafts); + // default index.json narrowed to the audience. + published?: readonly string[]; +}; + +export function articleNotInCorpusMessage(slug: string): string { + return `channel "${slug}" is not a channel of the corpus (no channels/${slug}/)`; +} + +// The articles, as the homepage publishes them. +export async function articlesReportHost( + paths: Pick<Paths, "articlesDir" | "exportIndexDir" | "channelsDir">, + opts: ArticlesHostOptions = {}, +): Promise<ReportHost> { + const audience = opts.audience ?? "private"; + const isChannel = new Map<string, boolean>(); + return { + ...articleReportStore(paths), + title: PROJECT_NAME, + siteUrl: opts.siteUrl === null ? undefined : (parseSiteUrl(opts.siteUrl ?? PROJECT_URL) ?? undefined), + audience, + published: opts.published ?? (await publishedArticleIds(audience, paths)), + listedBy: (id) => `reports/index.json lists article "${id}"`, + citableProblem: (slug) => { + if (!isChannel.has(slug)) { + let dir = false; + try { + dir = /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(slug) && statSync(path.join(paths.channelsDir, slug)).isDirectory(); + } catch { + dir = false; + } + isChannel.set(slug, dir); + } + return isChannel.get(slug) ? null : articleNotInCorpusMessage(slug); + }, + corpusBase: (slug) => parseSiteUrl(opts.channelSiteUrl?.(slug)) ?? null, + }; +} + +// A record's link into an archive: `<base>/?v=<slug>&…`, or undefined when +// the host has none for the channel. +export function hostCorpusLink(host: ReportHost, channel: string, params: Record<string, string>): string | undefined { + const base = host.corpusBase(channel); + if (base === null) return undefined; + return `${base}/?${new URLSearchParams(params).toString()}`; +} diff --git a/common/publish/reportMedia.ts b/common/publish/reportMedia.ts @@ -48,15 +48,15 @@ import path from "node:path"; import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server"; import { getPaths, type Paths } from "../lib/paths"; import { getSettings } from "../lib/settings"; +import { getSite, listSiteIds, type Site } from "../lib/site"; import { - getSite, - listSiteIds, - notInSiteMessage, - siteCitableChannelSlugs, - siteDir, - siteIndexDir, - type Site, -} from "../lib/site"; + siteReportStore, + storeReportDir, + storeReportFile, + storeReportLabel, + type ReportStore, +} from "../lib/report/store"; +import { siteReportHost, type ReportHost } from "./reportHost"; import { postsVisibleTo } from "../lib/postsVisibility"; import { inspectChannelMedia } from "../lib/channelMedia"; import type { ChannelConfig } from "../lib/channelConfig"; @@ -85,22 +85,33 @@ export const REPORT_MEDIA_VERSION = 1; export const REPORT_MEDIA_DIRNAME = "report-media"; export const REPORT_MEDIA_INDEX_FILENAME = "index.json"; -// `.export-index/sites/<siteId>/report-media/`: the prepared media, not served. +// `<staging>/report-media/`: the prepared media, not served — +// `.export-index/sites/<siteId>/` for a site, `.export-index/articles/` for +// the articles (lib/report/store.ts). +export function storeMediaDir(store: Pick<ReportStore, "stagingDir">): string { + return path.join(store.stagingDir, REPORT_MEDIA_DIRNAME); +} + +export function storeMediaIndexFile(store: Pick<ReportStore, "stagingDir">): string { + return path.join(storeMediaDir(store), REPORT_MEDIA_INDEX_FILENAME); +} + +// `.export-index/sites/<siteId>/report-media/`: a site's prepared media. export function reportMediaDir(paths: Paths, siteId: string): string { - return path.join(siteIndexDir(paths, siteId), REPORT_MEDIA_DIRNAME); + return storeMediaDir(siteReportStore(paths, siteId)); } export function reportMediaIndexFile(paths: Paths, siteId: string): string { - return path.join(reportMediaDir(paths, siteId), REPORT_MEDIA_INDEX_FILENAME); + return storeMediaIndexFile(siteReportStore(paths, siteId)); } // `sites/<siteId>/reports/<reportId>/`: a report's directory. export function siteReportDir(paths: Paths, siteId: string, reportId: string): string { - return path.join(siteDir(paths, siteId), "reports", reportId); + return storeReportDir(siteReportStore(paths, siteId), reportId); } export function siteReportFile(paths: Paths, siteId: string, reportId: string): string { - return path.join(siteReportDir(paths, siteId, reportId), "report.json"); + return storeReportFile(siteReportStore(paths, siteId), reportId); } // Every report directory of a site, published or draft: a directory under @@ -108,9 +119,14 @@ export function siteReportFile(paths: Paths, siteId: string, reportId: string): // stray file, a bad name) is not a report. Sorted. Whether one is PUBLISHED is // the site's `reports` list (site.json), not anything on disk. export async function listReportDirs(paths: Paths, siteId: string): Promise<string[]> { + return listStoreReportDirs(siteReportStore(paths, siteId)); +} + +// The same over any store (the articles: lib/report/registry.ts listArticleDirs). +export async function listStoreReportDirs(store: Pick<ReportStore, "reportsDir">): Promise<string[]> { let entries: Dirent[]; try { - entries = await readdir(path.join(siteDir(paths, siteId), "reports"), { withFileTypes: true }); + entries = await readdir(store.reportsDir, { withFileTypes: true }); } catch { return []; } @@ -159,6 +175,7 @@ export type ReportMediaProblem = { export type ReportMediaIndex = { format: typeof REPORT_MEDIA_FORMAT; version: typeof REPORT_MEDIA_VERSION; + // The site's id, or "articles" (the store's id, lib/report/store.ts). siteId: string; preparedAt: string; moments: Record<string, ReportMediaEntry>; @@ -183,10 +200,17 @@ export async function loadSiteReports( paths: Paths, site: Site, ): Promise<{ reports: Report[]; problems: ReportMediaProblem[] }> { + return loadHostReports(siteReportHost(paths, site)); +} + +// The same for any host (./reportHost.ts): its published reports, in order. +export async function loadHostReports( + host: Pick<ReportHost, "published" | "listedBy" | "reportsDir" | "label">, +): Promise<{ reports: Report[]; problems: ReportMediaProblem[] }> { const reports: Report[] = []; const problems: ReportMediaProblem[] = []; - for (const id of site.reports ?? []) { - const file = siteReportFile(paths, site.siteId, id); + for (const id of host.published) { + const file = storeReportFile(host, id); const read = await readJsonFile(file); if (!read.ok) { problems.push({ @@ -194,8 +218,8 @@ export async function loadSiteReports( report: id, message: read.reason === "absent" - ? `the site lists report "${id}", but sites/${site.siteId}/reports/${id}/report.json does not exist` - : `sites/${site.siteId}/reports/${id}/report.json is not readable JSON`, + ? `${host.listedBy(id)}, but ${storeReportLabel(host, id)} does not exist` + : `${storeReportLabel(host, id)} is not readable JSON`, }); continue; } @@ -233,7 +257,10 @@ export function citedMoments(reports: readonly Report[]): CitedMoment[] { } export type PrepareReportMediaOptions = { - siteId: string; + // The site whose pages to prepare, or `host` (./reportHost.ts) — the + // articles: articlesReportHost. + siteId?: string; + host?: ReportHost; paths?: Paths; onLog?: (line: string) => void; signal?: AbortSignal; @@ -247,20 +274,14 @@ const mib = (n: number) => `${(n / 1024 / 1024).toFixed(1)} MiB`; export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promise<ReportMediaIndex> { const paths = opts.paths ?? getPaths(); const log = opts.onLog ?? (() => {}); - const { siteId } = opts; - if (!listSiteIds(paths).includes(siteId)) { - throw new Error(`no site "${siteId}" (no sites/${siteId}/site.json)`); - } - const site = getSite(siteId, paths); + const host = opts.host ?? siteHostFor(paths, opts.siteId); const settings = opts.settings ?? getSettings(); - const cacheDir = reportMediaDir(paths, siteId); + const cacheDir = storeMediaDir(host); - const { reports, problems } = await loadSiteReports(paths, site); - log(`${siteId}: ${site.reports?.length ?? 0} published report(s), ${reports.length} readable.`); + const { reports, problems } = await loadHostReports(host); + log(`${host.id}: ${host.published.length} published report(s), ${reports.length} readable.`); const moments = citedMoments(reports); log(`${moments.length} cited moment(s) with media.`); - - const citable = siteCitableChannelSlugs(site); const configs = new Map<string, ChannelConfig | null>(); const configOf = async (slug: string) => { if (!configs.has(slug)) configs.set(slug, await readChannelConfig(paths, slug)); @@ -276,13 +297,14 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi for (const m of moments) { if (opts.signal?.aborted) throw new Error("prepare cancelled"); const slug = m.moment.channel; - if (!citable.has(slug)) { - fail(m, "not-in-site", notInSiteMessage(slug)); + const notCitable = host.citableProblem(slug); + if (notCitable) { + fail(m, "not-in-site", notCitable); continue; } const config = await configOf(slug); if (m.kind === "post") { - if (!postsVisibleTo(site, config, settings)) { + if (!postsVisibleTo(host, config, settings)) { fail(m, "not-visible", `this site may not carry posts of "${slug}" (the post visibility rule)`); continue; } @@ -346,12 +368,12 @@ export async function prepareReportMedia(opts: PrepareReportMediaOptions): Promi const index: ReportMediaIndex = { format: REPORT_MEDIA_FORMAT, version: REPORT_MEDIA_VERSION, - siteId, + siteId: host.id, preparedAt: (opts.now?.() ?? new Date()).toISOString(), moments: Object.fromEntries(Object.keys(entries).sort().map((k) => [k, entries[k]])), problems, }; - await writeJsonAtomic(reportMediaIndexFile(paths, siteId), index, { mkdir: true }); + await writeJsonAtomic(storeMediaIndexFile(host), index, { mkdir: true }); const bytes = Object.values(entries).reduce( (n, e) => n + e.bytes + (e.kind === "post" ? e.media.reduce((s, f) => s + f.bytes, 0) : 0), 0, @@ -394,7 +416,11 @@ export function formatReportMediaProblems(problems: readonly ReportMediaProblem[ // Read a prepared manifest, or null when there is none (never prepared, or // unreadable). export async function readReportMediaIndex(paths: Paths, siteId: string): Promise<ReportMediaIndex | null> { - const read = await readJsonFile(reportMediaIndexFile(paths, siteId)); + return readStoreMediaIndex(siteReportStore(paths, siteId)); +} + +export async function readStoreMediaIndex(store: Pick<ReportStore, "stagingDir">): Promise<ReportMediaIndex | null> { + const read = await readJsonFile(storeMediaIndexFile(store)); if (!read.ok) return null; const v = read.value as Partial<ReportMediaIndex> | null; if (!v || v.format !== REPORT_MEDIA_FORMAT || v.version !== REPORT_MEDIA_VERSION) return null; @@ -460,25 +486,21 @@ export type MissingEvidenceWindows = { const floor2 = (n: number) => Math.floor(n * 100 + 1e-6) / 100; const ceil2 = (n: number) => Math.ceil(n * 100 - 1e-6) / 100; -export async function missingEvidenceWindows(paths: Paths, siteId: string): Promise<MissingEvidenceWindows> { - if (!listSiteIds(paths).includes(siteId)) { - throw new Error(`no site "${siteId}" (no sites/${siteId}/site.json)`); - } - const site = getSite(siteId, paths); - const { reports, problems } = await loadSiteReports(paths, site); +export async function missingEvidenceWindows(paths: Paths, siteOrHost: string | ReportHost): Promise<MissingEvidenceWindows> { + const host = typeof siteOrHost === "string" ? siteHostFor(paths, siteOrHost) : siteOrHost; + const { reports, problems } = await loadHostReports(host); const quotes = new Map<string, string>(); for (const report of reports) { for (const [cid, c] of Object.entries(report.citations ?? {})) { if (typeof c.quote === "string" && c.quote.trim()) quotes.set(`${report.id}#${cid}`, c.quote.trim()); } } - const citable = siteCitableChannelSlugs(site); const configs = new Map<string, ChannelConfig | null>(); const configOf = async (slug: string) => { if (!configs.has(slug)) configs.set(slug, await readChannelConfig(paths, slug)); return configs.get(slug) ?? null; }; - const out: MissingEvidenceWindows = { siteId, missing: [], unfetchable: [], onDisk: 0, problems }; + const out: MissingEvidenceWindows = { siteId: host.id, missing: [], unfetchable: [], onDisk: 0, problems }; for (const m of citedMoments(reports)) { if (m.kind === "post" || m.moment.kind !== "span") continue; @@ -499,8 +521,9 @@ export async function missingEvidenceWindows(paths: Paths, siteId: string): Prom const unfetchable = (why: UnfetchableReason, message: string) => out.unfetchable.push({ ...window, why, message }); - if (!citable.has(slug)) { - unfetchable("not-in-site", notInSiteMessage(slug)); + const notCitable = host.citableProblem(slug); + if (notCitable) { + unfetchable("not-in-site", notCitable); continue; } const config = await configOf(slug); @@ -542,3 +565,12 @@ export async function missingEvidenceWindows(paths: Paths, siteId: string): Prom } return out; } + +// A site's host, or the refusal for a site that is not there. +function siteHostFor(paths: Paths, siteId: string | undefined): ReportHost { + if (!siteId) throw new Error("give a site id or a host"); + if (!listSiteIds(paths).includes(siteId)) { + throw new Error(`no site "${siteId}" (no sites/${siteId}/site.json)`); + } + return siteReportHost(paths, getSite(siteId, paths)); +}