Repository Public
1import { mkdir, writeFile } from "node:fs/promises";2import { join } from "node:path";3import { afterAll, beforeEach, describe, expect, it } from "vitest";4import { getCourse, getPreviewCourse, getQuiz, getRedirects, getSession } from "@/lib/content";5import { buildSearchDocs } from "@/lib/search-index";6import { sitemapPaths, structuredData } from "@/lib/seo";7import { buildView, mediaAllowed } from "@/modules/content-schema";8import { listAudit } from "@/server/audit";9import { createCapsule, getCapsule, getCourseRow, getSessionRow, putSection, setSessionState, updateCapsule, updateCourse, updateSession, writeCapsule } from "@/server/content";10import { dbExists } from "@/server/db";11import { ApiError } from "@/server/http";12import { cancelScheduled, history, liveEntry, planDirty, planPublication, publicManifest, publishPlan, publishSession, retireSession, rollbackSession, scheduledEntries, sessionStatus } from "@/server/publish";13import { loadManifest } from "./helpers";14import { cleanup, freshDataDir, freshStudio } from "./studio-helpers";1516const S01 = "S01", actor = "ed_test";17const code = async (fn: () => unknown) => { try { await fn(); return "ok"; } catch (e) { return e instanceof ApiError ? e.code : `other:${String(e)}`; } };18let dir: string;1920/** Makes S01 ready for publication: sections public, state « preview ». */21function prepare(keys = ["quiz", "glossary", "lab"]) {22 for (const key of keys) putSection(S01, key, { visibility: "public" }, actor);23 setSessionState(S01, "preview", actor);24}25/** A capsule with (empty but existing) media files, captions and transcript, as the worker would leave it. */26async function readyCapsule(id = "intro", visibility: "public" | "private" = "public") {27 createCapsule(S01, { title: "Introduction", id }, actor);28 const rel = `${S01}/${id}/r1`, files = [`${rel}/master.m3u8`, `${rel}/fallback.mp4`, `${rel}/poster.jpg`, `${rel}/v360/seg_00000.ts`, `${S01}/${id}/captions.fr-CA.abc.vtt`, `${S01}/${id}/transcript.abc.json`];29 for (const f of files) { await mkdir(join(dir, "media", f, ".."), { recursive: true }); await writeFile(join(dir, "media", f), f.endsWith(".json") ? JSON.stringify({ lang: "fr-CA", segments: [{ start: 0, end: 4, text: "Bienvenue dans la capsule sentinelle zythum." }] }) : "x"); }30 const cur = getCapsule(S01, id);31 writeCapsule({ ...cur, status: "ready", data: { ...cur.data, durationSeconds: 60, visibility, media: { hls: files[0], mp4: files[1], poster: files[2], captions: [{ lang: "fr-CA", label: "Français", path: files[4]! }], transcript: files[5] } } }, actor);32 return { rel, files };33}3435beforeEach(async () => { dir = await freshStudio(); });36afterAll(cleanup);3738describe("a studio seeded from the committed snapshot", () => {39 it("shows the public exactly what the snapshot alone showed", async () => {40 const fromStudio = buildView(publicManifest()!, "production"), fromSnapshot = buildView(loadManifest(), "production");41 expect(fromStudio).toEqual(fromSnapshot);42 expect((await getCourse()).counts).toMatchObject({ sessions: 24, open: 0, published: 0, capsules: 0, quizzes: 0 });43 });4445 it("is not consulted at all before it exists, and never when the source is forced to the snapshot", async () => {46 await freshDataDir();47 expect((await getCourse()).counts.sessions).toBe(24);48 expect(dbExists()).toBe(false); // a public read never creates the database49 dir = await freshStudio(); prepare(); publishSession(S01, { confirm: S01 }, actor);50 expect((await getCourse()).counts.published).toBe(1);51 process.env.ATLAS_CONTENT_SOURCE = "seed";52 expect((await getCourse()).counts.published).toBe(0);53 delete process.env.ATLAS_CONTENT_SOURCE;54 });5556 it("starts with nothing public: imported sections are private or preview-only, sessions are drafts", () => {57 expect(getSessionRow(S01).state).toBe("preview");58 expect(getSessionRow("S02").state).toBe("draft");59 expect(getSessionRow("S24").state).toBe("planned");60 expect(planPublication(getSessionRow(S01)).public).toEqual([]);61 });62});6364describe("workflow: draft → preview → published", () => {65 it("refuses to publish without an explicit confirmation, from a draft, or with nothing public", async () => {66 expect(await code(() => publishSession(S01, {}, actor))).toBe("confirmation_required");67 expect(await code(() => publishSession(S01, { confirm: "S02" }, actor))).toBe("confirmation_required");68 expect(await code(() => publishSession(S01, { confirm: S01 }, actor))).toBe("blocked"); // nothing marked public69 putSection("S02", "quiz", { visibility: "public" }, actor);70 expect(await code(() => publishSession("S02", { confirm: "S02" }, actor))).toBe("not_ready"); // still a draft71 expect((await getCourse()).counts.published).toBe(0);72 });7374 it("publishes exactly what is marked public, at once, and records who did it", async () => {75 prepare(["quiz", "glossary"]);76 putSection(S01, "lab", { visibility: "preview" }, actor); // stays in the studio77 const entry = publishSession(S01, { confirm: S01, note: "Première mise en ligne" }, actor);78 expect(entry).toMatchObject({ version: 1, kind: "publish", createdBy: actor });79 const s = (await getSession(getSessionRow(S01).data.slug))!;80 expect(s.access).toBe("open");81 expect(Object.keys(s.sections).sort()).toEqual(["glossary", "quiz"]);82 expect((await getQuiz(s))!.questions.length).toBeGreaterThan(5);83 expect(structuredData(await getCourse()).map((d) => d["@type"])).toEqual(["WebSite", "Course"]);84 const log = listAudit({ action: "publication.published" })[0]!;85 expect(log).toMatchObject({ actor, target: "session:S01" });86 expect(log.after_ref).toBe(entry.payloadSha);87 expect(sessionStatus(getSessionRow(S01))).toMatchObject({ public: "published", dirty: false });88 });8990 it("keeps later edits out of the public site until they are published again", async () => {91 prepare(["quiz"]);92 publishSession(S01, { confirm: S01 }, actor);93 const slug = getSessionRow(S01).data.slug;94 updateSession(S01, { title: "Titre de travail jamais publié" }, getSessionRow(S01).rev, actor);95 putSection(S01, "lab", { body: "# Brouillon\n\nConsigne sentinelle xylophage.", visibility: "public" }, actor);96 const pub = (await getSession(slug))!;97 expect(pub.title).not.toContain("jamais publié");98 expect(pub.sections.lab).toBeUndefined();99 expect(JSON.stringify(await buildSearchDocs())).not.toContain("xylophage");100 expect(sessionStatus(getSessionRow(S01)).dirty).toBe(true);101 // The signed-in editor sees the working copy in the private preview.102 const preview = (await getPreviewCourse()).sessions.find((x) => x.id === S01)!;103 expect(preview.title).toBe("Titre de travail jamais publié");104 expect(preview.sections.lab).toBeDefined();105 publishSession(S01, { confirm: S01 }, actor);106 expect((await getSession(slug))!.title).toBe("Titre de travail jamais publié");107 expect(JSON.stringify(await buildSearchDocs())).toContain("xylophage");108 });109110 it("never opens a draft, even in the private preview, and never shows private items there", async () => {111 setSessionState(S01, "draft", actor);112 const preview = await getPreviewCourse();113 expect(preview.sessions.find((s) => s.id === S01)!.access).toBe("upcoming");114 setSessionState(S01, "preview", actor);115 putSection(S01, "quiz", { visibility: "private" }, actor);116 expect((await getPreviewCourse()).sessions.find((s) => s.id === S01)!.sections.quiz).toBeUndefined();117 });118});119120describe("scheduling", () => {121 it("keeps a scheduled publication invisible until it is due, then shows it without any other action", async () => {122 prepare(["quiz"]);123 const due = new Date(Date.now() + 3_600_000);124 const entry = publishSession(S01, { confirm: S01, liveFrom: due.toISOString() }, actor);125 expect(entry.liveFrom).toBe(due.toISOString());126 expect((await getCourse()).counts.published).toBe(0);127 expect(JSON.stringify(await buildSearchDocs())).not.toContain("transcription");128 expect(sessionStatus(getSessionRow(S01))).toMatchObject({ public: "none" });129 expect(scheduledEntries(S01)).toHaveLength(1);130 expect(buildView(publicManifest(new Date(due.getTime() - 1000))!, "production").counts.published).toBe(0);131 expect(buildView(publicManifest(new Date(due.getTime() + 1000))!, "production").counts.published).toBe(1);132 });133134 it("can cancel a scheduled publication, but not one that is already live", async () => {135 prepare(["quiz"]);136 const scheduled = publishSession(S01, { confirm: S01, liveFrom: new Date(Date.now() + 3_600_000).toISOString() }, actor);137 cancelScheduled(S01, scheduled.id, actor);138 expect(scheduledEntries(S01)).toEqual([]);139 expect(buildView(publicManifest(new Date(Date.now() + 7_200_000))!, "production").counts.published).toBe(0);140 const live = publishSession(S01, { confirm: S01 }, actor);141 expect(await code(() => cancelScheduled(S01, live.id, actor))).toBe("not_scheduled");142 });143144 it("refuses an invalid or absurd date", async () => {145 prepare(["quiz"]);146 expect(await code(() => publishSession(S01, { confirm: S01, liveFrom: "demain" }, actor))).toBe("invalid");147 expect(await code(() => publishSession(S01, { confirm: S01, liveFrom: new Date(Date.now() + 400 * 86_400_000).toISOString() }, actor))).toBe("invalid");148 });149});150151describe("history, rollback, withdrawal, archive", () => {152 it("rolls back to an earlier version as a new history entry, and withdraws completely", async () => {153 prepare(["quiz"]);154 publishSession(S01, { confirm: S01 }, actor);155 const slug = getSessionRow(S01).data.slug;156 putSection(S01, "glossary", { visibility: "public" }, actor);157 publishSession(S01, { confirm: S01 }, actor);158 expect(Object.keys((await getSession(slug))!.sections).sort()).toEqual(["glossary", "quiz"]);159160 expect(await code(() => rollbackSession(S01, { toVersion: 1 }, actor))).toBe("confirmation_required");161 const back = rollbackSession(S01, { toVersion: 1, confirm: S01 }, actor);162 expect(back).toMatchObject({ version: 3, kind: "rollback" });163 expect(Object.keys((await getSession(slug))!.sections)).toEqual(["quiz"]);164 expect(history(S01).map((e) => e.kind)).toEqual(["rollback", "publish", "publish"]); // nothing was rewritten165166 retireSession(S01, "withdraw", { confirm: S01 }, actor);167 const gone = (await getSession(slug))!;168 expect(gone.access).toBe("upcoming");169 expect(gone.sections).toEqual({});170 expect(await getQuiz(gone)).toBeNull();171 expect(JSON.stringify(await buildSearchDocs())).not.toMatch(/"type":"(glossaire|ressource)"/);172 expect(sitemapPaths(await getCourse()).some((p) => p.includes("regarder"))).toBe(false);173 expect(await code(() => retireSession(S01, "withdraw", { confirm: S01 }, actor))).toBe("not_published");174 expect(await code(() => rollbackSession(S01, { toVersion: 4, confirm: S01 }, actor))).toBe("not_found"); // a withdrawal has nothing to restore175 rollbackSession(S01, { toVersion: 2, confirm: S01 }, actor);176 expect(Object.keys((await getSession(slug))!.sections).sort()).toEqual(["glossary", "quiz"]);177 });178179 it("archives a session: a notice stays, the content and the index entry go", async () => {180 prepare(["quiz"]);181 publishSession(S01, { confirm: S01 }, actor);182 retireSession(S01, "archive", { confirm: S01 }, actor);183 const s = (await getSession(getSessionRow(S01).data.slug))!;184 expect(s.access).toBe("archived");185 expect(s.sections).toEqual({});186 expect(sitemapPaths(await getCourse())).not.toContain(`/seances/${s.slug}`);187 expect(sessionStatus(getSessionRow(S01)).public).toBe("archived");188 });189});190191describe("media of unpublished capsules", () => {192 it("is refused until the capsule is published, and only the published encode is reachable", async () => {193 prepare(["quiz"]);194 const { rel, files } = await readyCapsule();195 for (const f of files) expect(mediaAllowed(await getCourse(), f), f).toBe(false);196 publishSession(S01, { confirm: S01 }, actor);197 const view = await getCourse();198 for (const f of files) expect(mediaAllowed(view, f), f).toBe(true);199 expect(mediaAllowed(view, `${S01}/intro/r2/master.m3u8`)).toBe(false); // a later encode, not published200 expect(mediaAllowed(view, `${S01}/intro/captions.en.zzz.vtt`)).toBe(false); // a caption file that no publication names201 expect(mediaAllowed(view, `${rel}`)).toBe(false);202 expect(mediaAllowed(view, `${S01}/autre/r1/master.m3u8`)).toBe(false);203 expect(sitemapPaths(view)).toContain(`/seances/${getSessionRow(S01).data.slug}/regarder`);204 expect(JSON.stringify(await buildSearchDocs())).toContain("zythum");205 expect(structuredData(view).map((d) => d["@type"])).toContain("VideoObject");206 retireSession(S01, "withdraw", { confirm: S01 }, actor);207 for (const f of files) expect(mediaAllowed(await getCourse(), f), f).toBe(false);208 expect(JSON.stringify(await buildSearchDocs())).not.toContain("zythum");209 });210211 it("blocks publication of a public capsule without French captions, transcript or files", async () => {212 prepare(["quiz"]);213 await readyCapsule();214 const cur = getCapsule(S01, "intro");215 writeCapsule({ ...cur, data: { ...cur.data, media: { ...cur.data.media, captions: [], transcript: undefined, mp4: `${S01}/intro/r1/absent.mp4` } } }, actor);216 const plan = planPublication(getSessionRow(S01));217 expect(plan.blockers.join(" ")).toMatch(/sous-titres français manquants/);218 expect(plan.blockers.join(" ")).toMatch(/transcription manquante/);219 expect(plan.blockers.join(" ")).toMatch(/fichier absent/);220 expect(await code(() => publishSession(S01, { confirm: S01 }, actor))).toBe("blocked");221 updateCapsule(S01, "intro", { visibility: "private" }, actor); // a private capsule does not block anything222 expect(await code(() => publishSession(S01, { confirm: S01 }, actor))).toBe("ok");223 expect((await getCourse()).sessions.find((s) => s.id === S01)!.capsules).toEqual([]);224 });225});226227describe("addresses", () => {228 it("turns the former slug into a permanent redirect once published, and keeps slugs unique", async () => {229 prepare(["quiz"]);230 publishSession(S01, { confirm: S01 }, actor);231 const old = getSessionRow(S01).data.slug;232 expect(await code(() => updateSession(S01, { slug: getSessionRow("S02").data.slug }, getSessionRow(S01).rev, actor))).toBe("slug_taken");233 updateSession(S01, { slug: "01-nouvelle-adresse" }, getSessionRow(S01).rev, actor);234 expect(getSessionRow(S01).data.aliases).toContain(old);235 expect((await getRedirects()).aliases.get(old)).toBeUndefined(); // not public yet: the old address still is the page236 publishSession(S01, { confirm: S01 }, actor);237 expect((await getRedirects()).aliases.get(old)).toBe("01-nouvelle-adresse");238 expect(await getSession(old)).toBeNull();239 expect((await getSession("01-nouvelle-adresse"))!.access).toBe("open");240 });241242 it("refuses a stale or replayed edit (optimistic concurrency)", async () => {243 const rev = getSessionRow(S01).rev;244 updateSession(S01, { title: "Un" }, rev, actor);245 expect(await code(() => updateSession(S01, { title: "Deux" }, rev, actor))).toBe("stale");246 expect(await code(() => updateSession(S01, { title: "Deux" }, undefined, actor))).toBe("stale");247 expect(getSessionRow(S01).data.title).toBe("Un");248 });249});250251describe("the public plan", () => {252 it("changes only when the plan is published, and can be rolled back", async () => {253 const before = (await getCourse()).sessions.find((s) => s.id === "S05")!.title;254 updateSession("S05", { title: "Titre de plan modifié" }, getSessionRow("S05").rev, actor);255 updateCourse({ license: "CC BY-NC-SA 4.0", exposeTags: false }, getCourseRow().rev, actor);256 expect((await getCourse()).sessions.find((s) => s.id === "S05")!.title).toBe(before);257 expect((await getCourse()).course.license).toBeNull();258 expect(planDirty()).toBe(true);259 expect(await code(() => publishPlan({}, actor))).toBe("confirmation_required");260 publishPlan({ confirm: "course" }, actor);261 const after = await getCourse();262 expect(after.sessions.find((s) => s.id === "S05")!.title).toBe("Titre de plan modifié");263 expect(after.course.license).toBe("CC BY-NC-SA 4.0");264 expect(after.sessions.find((s) => s.id === "S05")!.tags).toEqual([]);265 expect(planDirty()).toBe(false);266 rollbackSession("course", { toVersion: 1, confirm: "course" }, actor);267 expect((await getCourse()).sessions.find((s) => s.id === "S05")!.title).toBe(before);268 expect(liveEntry("course")!.kind).toBe("rollback");269 });270});271