Repository Public
1/**2 * Server-side content access. Pages never read a manifest directly: they get the filtered `CourseView`,3 * and section payloads are only readable through references present in that view.4 *5 * Two sources feed `buildView`, and nothing else does:6 * - the studio database, through `publicManifest()` — immutable publications that are due (publish.ts);7 * - the snapshot committed with the application, until the studio holds a published plan8 * (and always in the development preview mode, ATLAS_PREVIEW=1).9 * Signed-in editors get a third view, `getPreviewCourse()`, built from the working copy: it is only ever10 * called by routes under /admin, after the session check.11 */12import "server-only";13import { readFile } from "node:fs/promises";14import { join } from "node:path";15import { cache } from "react";16import { z } from "zod";17import {18 Bibliography, Capsule, Chapters, Deck, Figures, Glossary, Manifest, Quiz, Transcript, buildView,19 type CourseView, type SectionKey, type SessionView,20} from "@/modules/content-schema";21import { FsStorage, type MediaStorage } from "@/modules/storage";22import { getBlob, getBlobText } from "@/server/audit";23import { isBootstrapped, workingManifest } from "@/server/content";24import { dbIfExists } from "@/server/db";25import { publicManifest } from "@/server/publish";26import { env } from "./env";2728const CONTENT = join(/* turbopackIgnore: true */ process.cwd(), "content");2930/** Preview-only additions (the synthetic test capsule, demonstration exercises). Never read in production. */31const PreviewOverlay = z.object({32 capsules: z.record(z.string(), z.array(Capsule)),33 demoQuiz: Quiz,34});35export type PreviewOverlay = z.infer<typeof PreviewOverlay>;3637export const getPreviewOverlay = cache(async (): Promise<PreviewOverlay | null> => {38 if (env.mode !== "preview") return null;39 return PreviewOverlay.parse(JSON.parse(await readFile(join(CONTENT, "preview", "overlay.json"), "utf8")));40});4142type G = typeof globalThis & { __atlasSeed?: Manifest };43/** The snapshot committed with the application. Parsed once per process: it cannot change while the server runs. */44async function seedManifest(): Promise<Manifest> {45 const g = globalThis as G;46 g.__atlasSeed ??= Manifest.parse(JSON.parse(await readFile(join(CONTENT, "course.manifest.json"), "utf8")));47 const manifest = structuredClone(g.__atlasSeed);48 const overlay = await getPreviewOverlay();49 if (overlay) for (const s of manifest.sessions) s.capsules.push(...(overlay.capsules[s.id] ?? []));50 return manifest;51}5253/** True when the public site is served from the studio database rather than from the committed snapshot. */54export function studioIsSource(): boolean {55 return env.contentSource === "auto" && dbIfExists() !== null && isBootstrapped();56}5758/** The manifest the public is entitled to: live publications only. */59const loadPublicManifest = cache(async (): Promise<Manifest> => {60 if (studioIsSource()) { const m = publicManifest(); if (m) return m; }61 return seedManifest();62});6364export const getCourse = cache(async (): Promise<CourseView> => buildView(await loadPublicManifest(), env.mode));6566/** The committed snapshot's view, whatever the studio holds: used where a page must not depend on the database. */67export const getSeedCourse = cache(async (): Promise<CourseView> => buildView(await seedManifest(), env.mode));6869/**70 * The working copy as an editor would see it once published. PRIVATE: call it only after `requireEditor`.71 * Sessions in the « preview » state open; drafts stay closed; private items stay hidden.72 */73export const getPreviewCourse = cache(async (): Promise<CourseView> => buildView(workingManifest(), "preview"));7475export async function getSession(slug: string): Promise<SessionView | null> {76 return (await getCourse()).sessions.find((s) => s.slug === slug) ?? null;77}7879/** Former addresses: session aliases (→ current slug) and the editorial redirect list, from the public manifest. */80export const getRedirects = cache(async () => {81 const m = await loadPublicManifest();82 return { aliases: new Map(m.sessions.flatMap((s) => s.aliases.map((a) => [a, s.slug] as const))), paths: new Map(m.redirects.map((r) => [r.from, r.to] as const)) };83});8485export const mediaStorage = (): MediaStorage => new FsStorage(join(env.dataDir, "media"));86export const importDir = () => join(CONTENT, "import");8788/** A section body by reference: from the blob table when the studio stores it, from the committed files otherwise. */89async function readSection(session: SessionView, key: SectionKey): Promise<string | null> {90 const ref = session.sections[key];91 if (!ref) return null; // not visible in this view: nothing is even looked up92 if (env.contentSource === "auto" && dbIfExists()) { const text = getBlobText(ref.sha256); if (text !== null) return text; }93 return readFile(join(importDir(), ref.path), "utf8").catch(() => null);94}9596const parseJson = <T>(schema: z.ZodType<T>, text: string | null): T | null => {97 if (text === null) return null;98 try { const r = schema.safeParse(JSON.parse(text)); return r.success ? r.data : null; } catch { return null; }99};100101export const getQuiz = async (s: SessionView) => parseJson(Quiz, await readSection(s, "quiz"));102export const getGlossary = async (s: SessionView) => parseJson(Glossary, await readSection(s, "glossary"));103export const getFigures = async (s: SessionView) => parseJson(Figures, await readSection(s, "figures"));104export const getBibliography = async (s: SessionView) => parseJson(Bibliography, await readSection(s, "bibliography"));105/** The slide deck of a session, when its « slides » section is visible in this view; null otherwise. */106export const getDeck = async (s: SessionView) => parseJson(Deck, await readSection(s, "slides"));107export const getLab = (s: SessionView) => readSection(s, "lab");108export const getScript = (s: SessionView) => readSection(s, "script");109110/** Bytes of a figure listed in a visible figures section; null for anything else. */111export async function getFigureFile(session: SessionView, file: string): Promise<{ bytes: Buffer } | { storageKey: string } | null> {112 const figure = (await getFigures(session))?.figures.find((f) => f.file === file);113 if (!figure) return null;114 if (env.contentSource === "auto" && dbIfExists()) { const bytes = getBlob(figure.sha256); if (bytes) return { bytes }; }115 return { storageKey: `${session.id}/${file}` };116}117118/** Every glossary term visible in a view, sorted alphabetically (French collation). */119export async function termsOf(course: CourseView) {120 const lists = await Promise.all(course.sessions.map(async (s) => (await getGlossary(s))?.terms ?? []));121 return lists.flat().sort((a, b) => a.term.localeCompare(b.term, "fr-CA"));122}123export const getAllTerms = cache(async () => termsOf(await getCourse()));124125async function readMediaJson<T>(schema: z.ZodType<T>, key: string | undefined): Promise<T | null> {126 if (!key) return null;127 const stream = await mediaStorage().read(key);128 if (!stream) return null;129 const chunks: Buffer[] = [];130 for await (const c of stream) chunks.push(c as Buffer);131 try { const r = schema.safeParse(JSON.parse(Buffer.concat(chunks).toString("utf8"))); return r.success ? r.data : null; } catch { return null; }132}133134/** Chapters and transcript of a visible capsule (null when the media has not been produced). */135export async function getCapsuleData(capsule: SessionView["capsules"][number]) {136 const [chapters, transcript] = await Promise.all([readMediaJson(Chapters, capsule.media.chapters), readMediaJson(Transcript, capsule.media.transcript)]);137 return { chapters, transcript };138}139