import fs from "node:fs";
import path from "node:path";
import { parseMomentKey } from "../citations/moments";
import { isReportId } from "./schema";
import { REPORT_HISTORY_FORMAT, reportHistoryViewPath, type ReportHistoryView } from "./revisions";
import { SITE_REPORTS_BASE, type ReportBase } from "./routes";
import {
MOMENT_INDEX_FORMAT,
MOMENT_PAGE_FORMAT,
MOMENTS_INDEX_PATH,
REPORT_INDEX_FORMAT,
REPORT_PAGE_FORMAT,
REPORT_FEED_MIME,
momentViewPath,
reportFullTitle,
reportsIndexPath,
reportViewPath,
type MomentIndexView,
type MomentPageView,
type ReportIndexView,
type ReportPageView,
} from "./views";
// THE REPORT READER — the report and moment views compose's reports stage
// writes into a build's public dir (./views.ts names every file), read at
// build time by the pages that render them (common/components/report/). One
// reader for every build that renders reports: a site reads its own under
// SITE_REPORTS_BASE, another build names its base (./routes.ts) and its
// public dir.
//
// Every read is tolerant: a file that is absent, unreadable or of another
// format reads as "none", so a build without reports builds exactly as before
// and one with none renders its empty state. Read synchronously — a static
// export, evaluated once per build.
export type ReportReaderOptions = {
// The build's public dir, or a function returning it (read on every call,
// so a caller's lazily-resolved paths stay lazy).
publicDir: string | (() => string);
// Where this build serves its reports; a site's by default.
base?: ReportBase;
};
export type ReportReader = {
readonly base: ReportBase;
readReportIndex(): ReportIndexView | null;
// Whether the build has a report to link to.
hasReports(): boolean;
// The report ids to build pages for, in index order (only well-formed ids:
// each is a path segment).
reportIds(): string[];
readReportView(reportId: string): ReportPageView | null;
// A report's revision history (`/history/history.json`), or null
// when compose published none for it.
readReportHistory(reportId: string): ReportHistoryView | null;
// The build's one report, when it publishes exactly one.
onlyReportView(): ReportPageView | null;
// The build's first report in index order (a search-off site's home page).
firstReportView(): ReportPageView | null;
// The moment keys to build pages for (only keys exactly as momentKey spells
// them: each segment is a path segment of a page written to disk).
momentKeys(): string[];
readMomentView(key: string): MomentPageView | null;
};
export function createReportReader(opts: ReportReaderOptions): ReportReader {
const base = opts.base ?? SITE_REPORTS_BASE;
const publicDir = () => (typeof opts.publicDir === "function" ? opts.publicDir() : opts.publicDir);
function readView(urlPath: string, format: T["format"]): T | null {
try {
const file = path.join(publicDir(), ...urlPath.split("/").filter(Boolean));
const parsed = JSON.parse(fs.readFileSync(file, "utf8")) as T;
return parsed && parsed.format === format ? parsed : null;
} catch {
return null;
}
}
const reader: ReportReader = {
base,
readReportIndex() {
const v = readView(reportsIndexPath(base), REPORT_INDEX_FORMAT);
return v && Array.isArray(v.reports) ? v : null;
},
hasReports() {
return (reader.readReportIndex()?.reports.length ?? 0) > 0;
},
reportIds() {
return (reader.readReportIndex()?.reports ?? []).map((r) => r.id).filter(isReportId);
},
readReportView(reportId) {
if (!isReportId(reportId)) return null;
const v = readView(reportViewPath(reportId, base), REPORT_PAGE_FORMAT);
return v && v.id === reportId && Array.isArray(v.sections) ? v : null;
},
readReportHistory(reportId) {
if (!isReportId(reportId)) return null;
const v = readView(reportHistoryViewPath(reportId, base), REPORT_HISTORY_FORMAT);
return v && v.reportId === reportId && Array.isArray(v.revisions) && v.revisions.length > 0 ? v : null;
},
onlyReportView() {
const ids = reader.reportIds();
return ids.length === 1 ? reader.readReportView(ids[0]) : null;
},
firstReportView() {
const ids = reader.reportIds();
return ids.length > 0 ? reader.readReportView(ids[0]) : null;
},
momentKeys() {
const v = readView(MOMENTS_INDEX_PATH, MOMENT_INDEX_FORMAT);
return (Array.isArray(v?.moments) ? v.moments : []).filter((k) => parseMomentKey(k) !== null);
},
readMomentView(key) {
if (!parseMomentKey(key)) return null;
const v = readView(momentViewPath(key), MOMENT_PAGE_FORMAT);
return v && v.key === key ? v : null;
},
};
return reader;
}
// A report's page metadata: the title as one line names it (`:
// `, the layout's template adds the build's name), the subtitle as the
// description, and its timeline's feeds when it publishes them (a
// `` each, by absolute URL: the layouts set no
// metadataBase). Shaped as Next's `Metadata` without importing it (its types
// would bring Next's globals into every package that imports common/lib).
export type ReportPageMetadata = {
title: string;
description?: string;
alternates?: { types: Record };
};
export function reportMetadata(view: ReportPageView): ReportPageMetadata {
const title = reportFullTitle(view);
return {
title,
...(view.subtitle ? { description: view.subtitle } : {}),
...(view.feeds
? {
alternates: {
types: {
[REPORT_FEED_MIME.rss]: [{ url: view.feeds.rss, title }],
[REPORT_FEED_MIME.json]: [{ url: view.feeds.json, title }],
},
},
}
: {}),
};
}