Repository Public
1import { execFileSync } from "node:child_process";2import { createHash } from "node:crypto";3import { existsSync, readFileSync, readdirSync, writeFileSync } from "node:fs";4import { mkdtemp, readFile, rm } from "node:fs/promises";5import { tmpdir } from "node:os";6import { join } from "node:path";7import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";8import { getCourse, getDeck, getPreviewCourse } from "@/lib/content";9import { accessLabel, offerOf } from "@/lib/labels";10import { buildSearchDocs } from "@/lib/search-index";11import { sitemapPaths } from "@/lib/seo";12import { Deck } from "@/modules/content-schema/schema";13import { emptyState, mergeStates, parseImport, exportState, setSlide } from "@/modules/learning-engine/state";14import { listAudit } from "@/server/audit";15import { getSection, getSessionRow, putSection } from "@/server/content";16import { all } from "@/server/db";17import { ApiError } from "@/server/http";18import { history, publishSession } from "@/server/publish";19import { buildDeck, cleanPageText, deckAsset, importDeck, mapSlides, packDeck, parseDeckSource, popplerStatus, publishSlides, unpublishSlides, type BuiltDeck } from "@/server/slides";20import { NOTE_SENTINELS, SLIDE_WORD, fixtureDeck, writeDeckRepo } from "./fixtures/deck-fixture";21import { cleanup, freshStudio } from "./studio-helpers";2223const HAS_POPPLER = (() => { try { for (const c of ["pdfinfo", "pdftotext", "pdftocairo"]) execFileSync(c, ["-v"], { stdio: "ignore" }); return true; } catch { return false; } })();24const REAL = process.env.ATLAS_COURSE_REPO ?? "/Users/simon-pierreboucher/Desktop/UQO/Enseignement/atlas-ai-mooc";25const HAS_REAL = HAS_POPPLER && existsSync(join(REAL, "dist/slides/S01-web.pdf")) && existsSync(join(REAL, "dist/slides/S01-web-light.pdf"));26const code = async (fn: () => unknown) => { try { await fn(); return "ok"; } catch (e) { return e instanceof ApiError ? e.code : `other:${String(e)}`; } };2728describe("deck structure from the sources (pure)", () => {29 const files: Record<string, string> = {30 "sections/a.tex": "\\begin{frame}{Un {\\bfseries titre} simple}\n\\label{S01-D02}\nCorps \\note{secret \\AtlasSection{Piège}{x} \\begin{frame}{Faux}}\n\\end{frame}\n\\AtlasSection{Première section}{sous-titre}\n\\begin{frame}[fragile,t]{Deuxième}\\label{S01-D03}\\end{frame}\n% \\begin{frame}{Commentée}\\label{S01-D99}\\end{frame}\n\\begin{frame}{Sans étiquette}\\end{frame}",31 "sections/b.tex": "\\AtlasReferences\n\\AtlasClosingSlide{Merci}",32 };33 const events = parseDeckSource("\\AtlasTitleSlide\n\\input{sections/a}\n\\input{sections/b.tex}\n\\input{../../etc/passwd}\n\\input{sections/absent}", (rel) => files[rel] ?? null);3435 it("reads the order of pages: title, frames with their labels, dividers, references, closing — and nothing inside a frame", () => {36 expect(events).toEqual([{ kind: "title" }, { kind: "content", id: "S01-D02", title: "Un titre simple" }, { kind: "section", title: "Première section" }, { kind: "content", id: "S01-D03", title: "Deuxième" }, { kind: "content", id: null, title: "Sans étiquette" }, { kind: "references" }, { kind: "closing" }]);37 expect(JSON.stringify(events)).not.toMatch(/secret|Piège|Faux|Commentée|D99/);38 });3940 const page = (kicker: string, title: string, body = "") => cleanPageText(`${kicker}\n\n${title}\n${body}\n\nProf Essai · UQO\nATLAS IA\nS01 • 3 / 9\n\f`, "S01");41 const pages = [cleanPageText("ATLAS IA\nCours\n\nS01 • PARTIE I\n\nTitre de la séance\n", "S01"), page("S01 • Partie I : X", "Un titre simple", "Corps"), cleanPageText("1\n\nS01 • SECTION 1\n\nPremière section\nsous-titre\n\nProf Essai · UQO\n", "S01"), page("S01 • Partie I : X", "Deuxième"), page("S01 • Partie I : X", "Sans étiquette"), page("S01 • Synthèse", "Références I", "[1] A"), page("S01 • Synthèse", "Références II", "[2] B"), page("S01 • Synthèse", "Références III"), cleanPageText("ATLAS IA\nS01 • Titre\n\nMerci\n\nProf Essai\n", "S01")];4243 it("strips the header and footer strips from the text of a page", () => {44 expect(pages[1]).toEqual({ kicker: "S01 • Partie I : X", title: "Un titre simple", text: "Un titre simple\nCorps" });45 expect(pages[2]).toMatchObject({ kicker: "S01 • SECTION 1", title: "Première section" });46 expect(pages.map((p) => p.text).join("\n")).not.toMatch(/· UQO|3 \/ 9|^ATLAS IA$/m);47 });4849 it("maps pages to slides: one slide per page, references taking the pages that are left", () => {50 const { slides, warnings } = mapSlides(events, pages);51 expect(warnings).toEqual([]);52 expect(slides).toHaveLength(pages.length);53 expect(slides.map((s) => s.kind)).toEqual(["title", "content", "section", "content", "content", "references", "references", "references", "closing"]);54 expect(slides.map((s) => s.id)).toEqual([null, "S01-D02", null, "S01-D03", null, null, null, null, null]);55 expect(slides.map((s) => s.n)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]);56 expect(slides[3]).toMatchObject({ title: "Deuxième", section: "Première section" });57 expect(slides[1]!.section).toBeNull();58 });5960 it("never guesses identifiers when the sources do not account for the pages: kinds come from the pages, with a warning", () => {61 const { slides, warnings } = mapSlides(events.slice(0, 3), pages); // sources out of date62 expect(warnings[0]).toMatch(/ne correspond pas aux 9 pages/);63 expect(slides.every((s) => s.id === null)).toBe(true);64 expect(slides.map((s) => s.kind)).toEqual(["title", "content", "section", "content", "content", "references", "references", "references", "closing"]);65 // A divider where the sources announce a frame is a mismatch too.66 const swapped = [...pages]; [swapped[2], swapped[3]] = [swapped[3]!, swapped[2]!];67 expect(mapSlides(events, swapped).warnings).toHaveLength(1);68 const twice = mapSlides([{ kind: "title" }, { kind: "content", id: "S01-D02", title: "A" }, { kind: "content", id: "S01-D02", title: "B" }], [pages[0]!, pages[1]!, pages[3]!]);69 expect(twice.slides.map((s) => s.id)).toEqual([null, "S01-D02", null]);70 expect(twice.warnings[0]).toMatch(/utilisé deux fois/);71 });72});7374describe("local resume of the last slide", () => {75 it("is part of the local state: saved, exported, imported, merged — and absent from older states without breaking them", () => {76 const s = setSlide(emptyState(), "S01", 12, new Date("2026-11-22T10:00:00Z"));77 expect(s.slides.S01).toEqual({ n: 12, updatedAt: "2026-11-22T10:00:00.000Z" });78 expect(setSlide(s, "S01", 12)).toBe(s);79 const back = parseImport(exportState(s));80 expect(back.ok && back.state.slides.S01!.n).toBe(12);81 const old = JSON.parse(exportState(emptyState())) as { state: Record<string, unknown> }; delete old.state.slides; // a file exported before the viewer existed82 const parsed = parseImport(JSON.stringify(old));83 expect(parsed.ok && parsed.state.slides).toEqual({});84 const merged = mergeStates(s, setSlide(emptyState(), "S01", 3, new Date("2026-11-23T10:00:00Z")));85 expect(merged.slides.S01!.n).toBe(3); // the most recent wins86 });87});8889describe.skipIf(!HAS_POPPLER)("build → pack → import → publish (poppler, hand-made PDFs)", () => {90 let repo: string, out: string, built: BuiltDeck, dir: string;91 beforeAll(async () => {92 repo = await mkdtemp(join(tmpdir(), "atlas-deck-repo-")); out = await mkdtemp(join(tmpdir(), "atlas-deck-out-"));93 writeDeckRepo(repo, ["S01", "S02"]);94 built = await buildDeck(repo, "S01", out) as BuiltDeck;95 await buildDeck(repo, "S02", out);96 });97 beforeEach(async () => { dir = await freshStudio(); });98 afterAll(async () => { await cleanup(); await rm(repo, { recursive: true, force: true }); await rm(out, { recursive: true, force: true }); });99100 it("reports the toolchain, and converts every page of both exports", async () => {101 expect((await popplerStatus()).ok).toBe(true);102 const { deck } = built, expected = fixtureDeck("S01");103 expect(deck.count).toBe(expected.length);104 expect(deck.slides.map((s) => s.kind)).toEqual(expected.map((s) => s.kind));105 expect(deck.slides.map((s) => s.id)).toEqual(expected.map((s) => s.id ?? null));106 expect(deck.slides.map((s) => s.title).slice(1, 8)).toEqual(expected.map((s) => s.title).slice(1, 8));107 expect(deck.warnings).toEqual([]);108 expect(deck.slides[3]!.figures).toEqual([{ id: "S01-F01", alt: "Trois rectangles emboîtés, décrits pour qui ne voit pas la figure." }]);109 expect(deck.slides[4]!.text).toContain(SLIDE_WORD);110 expect(deck.slides[4]!.section).toBe("Définir les mots");111 expect(Math.round((deck.width / deck.height) * 100)).toBe(178); // 16:9112 for (const s of deck.slides) {113 const dark = readFileSync(join(built.dir, s.files.dark.path), "utf8"), light = readFileSync(join(built.dir, s.files.light.path), "utf8");114 expect(dark.startsWith("<?xml") && dark.includes("<svg")).toBe(true);115 expect(dark).not.toBe(light); // two real variants116 expect(dark).not.toMatch(/<script|<foreignObject|\son\w+=/i);117 expect(readFileSync(join(built.dir, s.files.thumbDark.path)).subarray(8, 12).toString()).toBe("WEBP");118 }119 expect(Deck.parse(JSON.parse(await readFile(join(built.dir, "deck.json"), "utf8"))).hash).toBe(deck.hash);120 });121122 it("is deterministic: the same sources give the same deck, a changed PDF gives another", async () => {123 const again = await buildDeck(repo, "S01", await mkdtemp(join(tmpdir(), "atlas-deck-again-"))) as BuiltDeck;124 expect(again.deck.hash).toBe(built.deck.hash);125 expect(again.deck.slides.map((s) => s.files.dark.sha256)).toEqual(built.deck.slides.map((s) => s.files.dark.sha256));126 await rm(again.dir, { recursive: true, force: true });127 });128129 it("skips, with the reason, a session without a complete pair of exports — and refuses unsafe identifiers", async () => {130 const other = await mkdtemp(join(tmpdir(), "atlas-deck-bad-"));131 writeDeckRepo(other, ["S03"], { lightPages: 4 });132 expect(await buildDeck(other, "S03", out)).toEqual({ skipped: expect.stringContaining("même nombre de pages") });133 expect(await buildDeck(other, "S09", out)).toEqual({ skipped: expect.stringContaining("exports web absents") });134 writeFileSync(join(other, "dist/slides/S04-web.pdf"), "pas un pdf"); writeFileSync(join(other, "dist/slides/S04-web-light.pdf"), "pas un pdf");135 expect(await buildDeck(other, "S04", out)).toEqual({ skipped: expect.stringContaining("n'est pas un PDF") });136 await expect(buildDeck(other, "../S01", out)).rejects.toThrow(/invalide/);137 await rm(other, { recursive: true, force: true });138 });139140 it("never lets a speaker note into a deck, a pack, the database or the public output", async () => {141 const pack = join(out, "S01-slides.tar.gz");142 await packDeck(built.dir, pack);143 await importDeck(pack, "ed");144 publishSlides("S01", "ed");145 const everywhere = [146 readFileSync(join(built.dir, "deck.json"), "utf8"), JSON.stringify(await buildSearchDocs()), JSON.stringify(await getCourse()),147 JSON.stringify(all("SELECT * FROM audit")), ...all<{ body: Uint8Array }>("SELECT body FROM blobs").map((b) => Buffer.from(b.body).toString("utf8")),148 ...readdirSync(join(dir, "slides", built.deck.dir), { recursive: true }).map(String).filter((f) => /\.(svg|json)$/.test(f)).map((f) => readFileSync(join(dir, "slides", built.deck.dir, f), "utf8")),149 ].join("\n");150 for (const note of NOTE_SENTINELS) expect(everywhere).not.toContain(note.slice(0, 18));151 expect(everywhere).not.toContain("Piège dans une note");152 expect(everywhere).toContain(SLIDE_WORD); // the detector does see slide text153 });154155 it("imports a pack as a private section, verifies every file, and installs it where it is never rewritten", async () => {156 const r = await importDeck(built.dir, "ed");157 expect(r.changed).toBe(true);158 expect(getSection("S01", "slides")).toMatchObject({ visibility: "private", count: 10 });159 expect(existsSync(join(dir, "slides", built.deck.dir, "dark/001.svg"))).toBe(true);160 expect((await importDeck(built.dir, "ed")).changed).toBe(false); // idempotent161 expect(listAudit({ action: "slides." }).map((a) => a.action)).toEqual(["slides.imported"]);162 expect((await getCourse()).sessions[0]!.sections).toEqual({}); // nothing public163 expect(await code(() => importDeck(built.dir, "ed", "S02"))).toBe("bad_pack"); // a pack of another session164 expect(await code(() => putSection("S01", "slides", { body: "{}" }, "ed"))).toBe("invalid"); // not editable by hand165166 // Tampered packs: an altered image, a script in an SVG, a file outside the expected names, a broken deck.json.167 const tamper = async (fn: (d: string, deck: Deck) => void) => { const d = await mkdtemp(join(tmpdir(), "atlas-pack-")); execFileSync("cp", ["-R", `${built.dir}/.`, d]); const deck = JSON.parse(readFileSync(join(d, "deck.json"), "utf8")) as Deck; fn(d, deck); const c = await code(() => importDeck(d, "ed")); await rm(d, { recursive: true, force: true }); return c; };168 expect(await tamper((d) => writeFileSync(join(d, "dark/002.svg"), "<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>"))).toBe("bad_pack");169 expect(await tamper((d, deck) => { const evil = Buffer.from("<svg xmlns='http://www.w3.org/2000/svg' onload='x()'></svg>"); writeFileSync(join(d, "dark/002.svg"), evil); deck.slides[1]!.files.dark = { path: "dark/002.svg", bytes: evil.length, sha256: createHash("sha256").update(evil).digest("hex") }; deck.hash = "f".repeat(64); deck.dir = `S01/${"f".repeat(12)}`; writeFileSync(join(d, "deck.json"), JSON.stringify(deck)); })).toBe("bad_pack");170 expect(await tamper((d, deck) => { deck.slides[0]!.files.dark.path = "../../atlas.db"; writeFileSync(join(d, "deck.json"), JSON.stringify(deck)); })).toBe("bad_pack");171 expect(await tamper((d, deck) => { deck.dir = "S01/ailleurs"; writeFileSync(join(d, "deck.json"), JSON.stringify(deck)); })).toBe("bad_pack");172 expect(await tamper((d) => writeFileSync(join(d, "deck.json"), "{"))).toBe("other:SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)");173 });174175 it("publishes the slides alone — honest state, counts, search, deep links — and takes them back", async () => {176 await importDeck(built.dir, "ed"); await importDeck(join(out, "S02"), "ed");177 const slug = getSessionRow("S01").data.slug;178 // Unpublished: unreachable by the view, the search and the sitemap; the working copy shows them in private preview only once marked.179 expect(await getDeck((await getCourse()).sessions[0]!)).toBeNull();180 expect(JSON.stringify(await buildSearchDocs())).not.toContain(SLIDE_WORD);181 putSection("S01", "slides", { visibility: "preview" }, "ed");182 expect((await getDeck((await getPreviewCourse()).sessions[0]!))!.count).toBe(10);183 expect(await getDeck((await getCourse()).sessions[0]!)).toBeNull();184185 const entry = publishSlides("S01", "ed");186 expect(entry).toMatchObject({ kind: "publish", note: "Diapositives mises en ligne" });187 const view = await getCourse(), s01 = view.sessions[0]!;188 expect(Object.keys(s01.sections)).toEqual(["slides"]); // nothing else went out: no quiz, lab, glossary, script189 expect(s01).toMatchObject({ access: "open", slidesOnly: true });190 expect(accessLabel(s01)).toBe("Diapositives en ligne");191 expect(offerOf(s01).map((o) => o.label)).toEqual(["Diapositives en ligne", "Vidéos à venir", "Quiz à venir", "Laboratoire à venir"]);192 expect(view.counts).toMatchObject({ slideDecks: 1, published: 0, capsules: 0, quizzes: 0 }); // not counted as a published session193 const deck = (await getDeck(s01))!;194 expect(deckAsset(deck, "dark/001.svg")).toMatchObject({ type: "image/svg+xml" });195 expect(deckAsset(deck, "thumbs/light/010.webp")!.type).toBe("image/webp");196 for (const bad of ["deck.json", "dark/011.svg", "../../atlas.db", "dark/001.svg.gz", "dark/../deck.json"]) expect(deckAsset(deck, bad), bad).toBeNull();197 const docs = await buildSearchDocs(), hit = docs.find((d) => d.type === "diapositive" && d.text.includes(SLIDE_WORD))!;198 expect(hit).toMatchObject({ title: "Un animal minuscule", url: `/seances/${slug}#diapositive-5`, session: "S01" });199 expect(docs.filter((d) => d.type === "diapositive")).toHaveLength(6); // content and dividers; not the title, references or closing pages200 expect(docs.filter((d) => d.type === "diapositive" && d.session === "S02")).toEqual([]); // S02 was imported, not published201 expect(sitemapPaths(view)).toContain(`/seances/${slug}`);202203 // A session where something else is marked public is refused, not half-published.204 putSection("S02", "quiz", { visibility: "public" }, "ed");205 expect(await code(() => publishSlides("S02", "ed"))).toBe("would_publish_more");206 expect(history("S02")).toEqual([]);207 expect(await code(() => publishSlides("S09", "ed"))).toBe("no_slides");208209 // Reversible.210 expect(unpublishSlides("S01", "ed")).toMatchObject({ kind: "withdraw" });211 const after = await getCourse();212 expect(after.sessions[0]).toMatchObject({ access: "upcoming", sections: {} });213 expect(await getDeck(after.sessions[0]!)).toBeNull();214 expect(JSON.stringify(await buildSearchDocs())).not.toContain(SLIDE_WORD);215 expect(after.counts.slideDecks).toBe(0);216 expect(unpublishSlides("S01", "ed")).toBeNull();217 // With other content online, unpublishing the slides keeps the rest.218 publishSlides("S01", "ed"); putSection("S01", "quiz", { visibility: "public" }, "ed"); publishSession("S01", { confirm: "S01" }, "ed");219 expect((await getCourse()).sessions[0]).toMatchObject({ slidesOnly: false });220 expect((await getCourse()).counts).toMatchObject({ published: 1, slideDecks: 1 });221 expect(unpublishSlides("S01", "ed")).toMatchObject({ kind: "publish" });222 expect(Object.keys((await getCourse()).sessions[0]!.sections)).toEqual(["quiz"]);223 });224225 it("keeps the published deck when a new one is imported: old files stay, the public does not move until republished", async () => {226 await importDeck(built.dir, "ed"); publishSlides("S01", "ed");227 const other = await mkdtemp(join(tmpdir(), "atlas-deck-v2-"));228 writeDeckRepo(other, ["S01"]);229 writeFileSync(join(other, "sessions/S01-essai/figures/manifest.yaml"), "session: S01\nfigures: []\n"); // a change in the sources → another deck230 const v2 = await buildDeck(other, "S01", join(other, "out")) as BuiltDeck;231 expect(v2.deck.hash).not.toBe(built.deck.hash);232 expect((await importDeck(v2.dir, "ed")).changed).toBe(true);233 expect(getSection("S01", "slides")!.visibility).toBe("public"); // the setting survives234 const pub = (await getDeck((await getCourse()).sessions[0]!))!;235 expect(pub.hash).toBe(built.deck.hash);236 expect(deckAsset(pub, "dark/001.svg")).not.toBeNull();237 expect(existsSync(join(dir, "slides", v2.deck.dir, "deck.json"))).toBe(true);238 await rm(other, { recursive: true, force: true });239 });240});241242describe.skipIf(!HAS_REAL)("the real course repository (read-only), when it is on this machine", () => {243 it("S01: one slide per PDF page, every content frame identified, no speaker note in the result", async () => {244 const out = await mkdtemp(join(tmpdir(), "atlas-deck-real-"));245 const r = await buildDeck(REAL, "S01", out) as BuiltDeck;246 const pages = Number(/Pages:\s+(\d+)/.exec(execFileSync("pdfinfo", [join(REAL, "dist/slides/S01-web.pdf")], { encoding: "utf8" }))![1]);247 expect(r.deck.count).toBe(pages);248 expect(r.deck.slides).toHaveLength(pages);249 expect(r.deck.warnings).toEqual([]);250 expect(r.deck.slides[0]!.kind).toBe("title");251 expect(r.deck.slides[pages - 1]!.kind).toBe("closing");252 const content = r.deck.slides.filter((s) => s.kind === "content");253 expect(content.every((s) => /^S01-D\d{2}$/.test(s.id ?? ""))).toBe(true);254 expect(new Set(content.map((s) => s.id)).size).toBe(content.length);255 expect(r.deck.slides.filter((s) => s.kind === "section").length).toBeGreaterThanOrEqual(3);256 expect(r.deck.slides.some((s) => s.kind === "references")).toBe(true);257 expect(r.deck.slides.some((s) => s.figures.length > 0)).toBe(true);258 // Phrases of the instructor's private notes must be nowhere in the deck (unless the slide itself says the same words).259 const notes = readFileSync(join(REAL, readdirSync(join(REAL, "sessions")).filter((d) => d.startsWith("S01-")).map((d) => `sessions/${d}/slides/speaker-notes.md`)[0]!), "utf8");260 const json = JSON.stringify(r.deck), publicText = execFileSync("pdftotext", [join(REAL, "dist/slides/S01-web.pdf"), "-"], { encoding: "utf8" }).replace(/\s+/g, " ");261 const phrases = (notes.match(/[A-Za-zàâçéèêëîïôûùüÿœ’' ]{45,}/g) ?? []).map((p) => p.trim()).filter((p) => !publicText.includes(p));262 expect(phrases.length).toBeGreaterThan(5);263 for (const p of phrases) expect(json, p).not.toContain(p);264 await rm(out, { recursive: true, force: true });265 }, 60_000);266});267