Repository Public
1import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";2import { tmpdir } from "node:os";3import { join } from "node:path";4import { afterAll, beforeEach, describe, expect, it } from "vitest";5import { getCourse } from "@/lib/content";6import { buildView } from "@/modules/content-schema";7import { listAudit } from "@/server/audit";8import { getSection, getSessionRow, listSessions, putSection, sectionBody, setSessionState, updateSession, workingManifest } from "@/server/content";9import { ApiError } from "@/server/http";10import { importCourse } from "@/server/importer";11import { history, publicManifest, publishPlan, publishSession } from "@/server/publish";12import { applyImport, bootstrap, diffIsEmpty, discardImport, getImport, importDiff, listImports, prepareImport, type ImportDiff } from "@/server/sync";13import { cleanup, freshDataDir } from "./studio-helpers";1415/** A small course repository on disk, rewritten between imports to simulate work going on in it. */16const SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><rect width="10" height="10"/></svg>';17interface Spec { titles?: Record<string, string>; outcomes?: Record<string, string[]>; quizAnswer?: string; lab?: string | null; extra?: boolean; drop?: string[]; s2?: "missing" | "broken" | "implemented"; parts?: string }18let repo: string, seed: string;1920async function writeRepo(spec: Spec = {}) {21 await rm(repo, { recursive: true, force: true });22 const sessions = [["S01", "first", "Première", "débutant", "[]"], ["S02", "second", "Deuxième", "avancé", "[S01]"], ["S03", "third", "Troisième", "avancé", "[S01]"], ...(spec.extra ? [["S04", "fourth", "Quatrième", "avancé", "[]"]] : [])].filter(([id]) => !spec.drop?.includes(id!));23 const s1 = join(repo, "sessions/S01-first"), s2 = join(repo, "sessions/S02-second");24 for (const d of ["quizzes", "labs/solution", "figures/rendered", "video", "slides"]) await mkdir(join(s1, d), { recursive: true });25 await writeFile(join(repo, "course.yaml"), `26course: {id: t, title: "Cours test", short_title: "Test", tagline: "t", subtitle: "s", language: fr-CA, version: 0.1.0, endorsement_notice: "Avis."}27author: {name: "Prof", role: "Professeur", institution: "Université", institution_short: "U", department: "Département"}28parts: ${spec.parts ?? '[{id: I, short: "Un", title: "Partie un"}]'}29sessions:30${sessions.map(([id, slug, title, level, deps]) => ` - {id: ${id}, slug: ${slug}, part: I, level: ${level}, title: "${spec.titles?.[id!] ?? title}", short: "${title} séance", depends_on: ${deps}, tags: [a], outcomes: ${JSON.stringify(spec.outcomes?.[id!] ?? [`Faire ${id}.`])}}`).join("\n")}31`);32 await writeFile(join(s1, "metadata.yaml"), "id: S01\nstatus: implemented\neffort_minutes: {lab: [45, 60]}\n");33 await writeFile(join(s1, "README.md"), "# S01\n\n## Glossaire de la séance\n\n| Terme français | Terme anglais | Définition courte |\n|---|---|---|\n| jeton | *token* | unité de texte |\n");34 await writeFile(join(s1, "quizzes/questions.yaml"), `session: S01\ntitle: Quiz\nquestions:\n- {id: Q1, type: choix-unique, prompt: "P ?", options: [{id: A, text: "a"}, {id: B, text: "b"}], answer: ${spec.quizAnswer ?? "B"}, explanation: "Parce que."}\n`);35 if (spec.lab !== null) await writeFile(join(s1, "labs/instructions.md"), spec.lab ?? "# Labo\n\nConsignes d'origine.");36 await writeFile(join(s1, "labs/solution/corrige.py"), "CORRIGE_SECRET = 42");37 await writeFile(join(s1, "figures/manifest.yaml"), "figures:\n - {id: F1, rendered: [rendered/ok.svg], caption: 'Une figure', alt: 'Un carré.'}\n");38 await writeFile(join(s1, "figures/rendered/ok.svg"), SVG);39 if (spec.s2 !== "missing") { await mkdir(s2, { recursive: true }); await writeFile(join(s2, "metadata.yaml"), spec.s2 === "implemented" ? "id: S02\nstatus: implemented\n" : "id: S02\nstatus: impl"); }40}4142const code = async (fn: () => unknown) => { try { await fn(); return "ok"; } catch (e) { return e instanceof ApiError ? e.code : `other:${String(e)}`; } };43const change = (d: ImportDiff, key: string) => [...d.course, ...d.sessions.flatMap((s) => s.changes)].find((c) => c.key === key);4445beforeEach(async () => {46 await freshDataDir();47 repo = await mkdtemp(join(tmpdir(), "atlas-sync-repo-")); seed = await mkdtemp(join(tmpdir(), "atlas-sync-seed-"));48 // The « committed snapshot » of this test: what the importer makes of the repository in its first state.49 await writeRepo();50 await importCourse({ repo, out: seed, publication: {} });51 await bootstrap("test", seed);52});53afterAll(async () => { await cleanup(); });5455describe("first import (bootstrap)", () => {56 it("brings the plan and the material in as drafts, private, with a public plan and nothing else", async () => {57 expect(listSessions().map((s) => [s.id, s.state])).toEqual([["S01", "draft"], ["S02", "planned"], ["S03", "planned"]]);58 expect(getSection("S01", "quiz")).toMatchObject({ visibility: "private", count: 1 });59 expect(history("course")).toHaveLength(1);60 const view = await getCourse();61 expect(view.counts).toMatchObject({ sessions: 3, published: 0, open: 0 });62 expect(view.sessions[0]!.sections).toEqual({});63 expect(await bootstrap("test", seed)).toBe(false); // once only64 });65});6667describe("diff", () => {68 it("is empty when the repository did not change, however often it is read (idempotent)", async () => {69 for (let i = 0; i < 2; i++) {70 const { diff, record } = await prepareImport(repo, "essai", "ed");71 expect(diffIsEmpty(diff)).toBe(true);72 expect(diff.counts).toMatchObject({ added: 0, removed: 0, changed: 0, conflicts: 0, unchanged: 3 });73 expect(applyImport(record.id, {}, "ed")).toMatchObject({ applied: 0, kept: 0, added: 0 });74 }75 expect(listSessions().map((s) => s.rev)).toEqual([1, 1, 1]); // nothing was rewritten76 });7778 it("is not triggered by local edits alone: the repository did not ask for anything", async () => {79 updateSession("S01", { title: "Titre local" }, getSessionRow("S01").rev, "ed");80 putSection("S01", "lab", { body: "# Labo local" }, "ed");81 const { diff } = await prepareImport(repo, "essai", "ed");82 expect(diffIsEmpty(diff)).toBe(true);83 });8485 it("classifies every change: update, conflict, addition, removal", async () => {86 updateSession("S01", { title: "Titre local", outcomes: ["Résultat local."] }, getSessionRow("S01").rev, "ed"); // edited here…87 putSection("S01", "lab", { body: "# Labo local" }, "ed");88 await writeRepo({ titles: { S01: "Première (révisée)", S02: "Deuxième (révisée)" }, quizAnswer: "A", lab: "# Labo du dépôt, modifié", extra: true, drop: ["S03"] }); // …and there89 const { diff, record } = await prepareImport(repo, "essai", "ed");90 expect(change(diff, "S01.title")).toMatchObject({ kind: "conflict", base: "Première", local: "Titre local", incoming: "Première (révisée)" });91 expect(change(diff, "S01.section.lab")).toMatchObject({ kind: "conflict" });92 expect(change(diff, "S01.section.quiz")).toMatchObject({ kind: "update" }); // untouched here → plain update93 expect(change(diff, "S02.title")).toMatchObject({ kind: "update", incoming: "Deuxième (révisée)" });94 expect(change(diff, "S01.outcomes")).toBeUndefined(); // edited here only: nothing to decide95 expect(diff.sessions.find((s) => s.id === "S04")).toMatchObject({ kind: "added" });96 expect(diff.sessions.find((s) => s.id === "S03")).toMatchObject({ kind: "removed" });97 expect(diff.counts).toMatchObject({ added: 1, removed: 1, changed: 2, conflicts: 2 });98 expect(importDiff(record.id)).toEqual(diff);99 expect(getSessionRow("S01").data.title).toBe("Titre local"); // preparing an import changes nothing100 });101});102103describe("apply", () => {104 it("keeps the local value in a conflict unless told otherwise, and never overwrites silently", async () => {105 updateSession("S01", { title: "Titre local" }, getSessionRow("S01").rev, "ed");106 putSection("S01", "lab", { body: "# Labo local" }, "ed");107 await writeRepo({ titles: { S01: "Première (révisée)" }, lab: "# Labo du dépôt, modifié", quizAnswer: "A" });108 const { record } = await prepareImport(repo, "essai", "ed");109 const r = applyImport(record.id, { "S01.section.lab": "incoming" }, "ed"); // one conflict decided for the repository, the other left to the default110 expect(r).toMatchObject({ kept: 1 });111 expect(getSessionRow("S01").data.title).toBe("Titre local");112 expect(sectionBody(getSection("S01", "lab")!)).toContain("Labo du dépôt, modifié");113 expect(sectionBody(getSection("S01", "quiz")!)).toContain('"answer": "A"');114 expect(getImport(record.id)).toMatchObject({ status: "applied" });115 expect(listAudit({ action: "import.applied" })[0]!.detail).toContain('"S01.section.lab":"incoming"');116 // The kept conflict does not come back while the repository stays as it is…117 const again = await prepareImport(repo, "essai", "ed");118 expect(diffIsEmpty(again.diff)).toBe(true);119 // …and reappears as a conflict only when the repository changes that field again.120 await writeRepo({ titles: { S01: "Première (révisée encore)" }, lab: "# Labo du dépôt, modifié", quizAnswer: "A" });121 expect(change((await prepareImport(repo, "essai", "ed")).diff, "S01.title")).toMatchObject({ kind: "conflict", local: "Titre local" });122 expect(await code(() => applyImport(record.id, {}, "ed"))).toBe("not_pending"); // an import is applied once123 });124125 it("adds new sessions as drafts, flags sessions gone from the repository without deleting them", async () => {126 await writeRepo({ extra: true, drop: ["S03"] });127 const { record } = await prepareImport(repo, "essai", "ed");128 expect(applyImport(record.id, {}, "ed")).toMatchObject({ added: 1 });129 expect(getSessionRow("S04")).toMatchObject({ state: "planned", inSource: true });130 expect(getSessionRow("S03")).toMatchObject({ inSource: false }); // still there, flagged131 expect(listSessions()).toHaveLength(4);132 expect(diffIsEmpty((await prepareImport(repo, "essai", "ed")).diff)).toBe(true);133 });134135 it("never publishes and never touches what is online", async () => {136 putSection("S01", "quiz", { visibility: "public" }, "ed"); setSessionState("S01", "preview", "ed");137 publishSession("S01", { confirm: "S01" }, "ed");138 const before = JSON.stringify(buildView(publicManifest()!, "production"));139 await writeRepo({ titles: { S01: "Première (révisée)", S02: "Deuxième (révisée)" }, quizAnswer: "A", extra: true });140 const { record } = await prepareImport(repo, "essai", "ed");141 applyImport(record.id, {}, "ed");142 expect(getSessionRow("S01").data.title).toBe("Première (révisée)"); // the working copy moved…143 expect(JSON.stringify(buildView(publicManifest()!, "production"))).toBe(before); // …the public site did not144 expect(history("S01")).toHaveLength(1);145 expect((await getCourse()).sessions.map((s) => s.id)).toEqual(["S01", "S02", "S03"]); // S04 is not in the public plan146 expect(getSection("S01", "quiz")!.visibility).toBe("public"); // editorial settings survive an import147 publishPlan({ confirm: "course" }, "ed");148 expect((await getCourse()).sessions.map((s) => s.id)).toEqual(["S01", "S02", "S03", "S04"]);149 });150151 it("keeps a local section when the repository stops providing it", async () => {152 await writeRepo({ lab: null });153 const { record, diff } = await prepareImport(repo, "essai", "ed");154 expect(change(diff, "S01.section.lab")).toMatchObject({ kind: "remove" });155 applyImport(record.id, {}, "ed");156 expect(sectionBody(getSection("S01", "lab")!)).toContain("Consignes d'origine");157 expect(diffIsEmpty((await prepareImport(repo, "essai", "ed")).diff)).toBe(true);158 });159160 it("refuses an import that would leave the course inconsistent, and changes nothing", async () => {161 await writeRepo({ parts: '[{id: Z, short: "Autre", title: "Autre partie"}]' }); // the sessions still say part I162 expect(await code(async () => prepareImport(repo, "essai", "ed"))).toBe("unreadable_source"); // the adapter already refuses it163 expect(listImports().filter((i) => i.status === "pending")).toEqual([]);164 expect(() => workingManifest()).not.toThrow();165 });166167 it("can be abandoned", async () => {168 await writeRepo({ titles: { S02: "Deuxième (révisée)" } });169 const { record } = await prepareImport(repo, "essai", "ed");170 discardImport(record.id, "ed");171 expect(getImport(record.id).status).toBe("discarded");172 expect(await code(() => applyImport(record.id, {}, "ed"))).toBe("not_pending");173 expect(getSessionRow("S02").data.title).toBe("Deuxième");174 });175});176177describe("a repository other people are writing in", () => {178 it("tolerates half-written and missing session files: warnings, not failures", async () => {179 await writeRepo({ s2: "broken" });180 const a = await prepareImport(repo, "essai", "ed");181 expect(a.record.warnings.join("\n")).toMatch(/S02 — metadata\.yaml (incomplet|n'est pas du YAML valide)/);182 expect(a.record.warnings.join("\n")).toMatch(/S03 — metadata\.yaml absent/);183 expect(diffIsEmpty(a.diff)).toBe(true);184 await writeRepo({ s2: "implemented" }); // finished later, but with no material yet185 const b = await prepareImport(repo, "essai", "ed");186 expect(b.record.warnings.join("\n")).toMatch(/S02 — quiz/);187 expect(await code(() => applyImport(b.record.id, {}, "ed"))).toBe("ok");188 });189190 it("treats the repository as data: solutions are never read, links to the outside are not followed", async () => {191 const outside = await mkdtemp(join(tmpdir(), "atlas-outside-"));192 await writeFile(join(outside, "secret.md"), "SECRET-HORS-DEPOT");193 await writeRepo();194 await rm(join(repo, "sessions/S01-first/labs/instructions.md"));195 await symlink(join(outside, "secret.md"), join(repo, "sessions/S01-first/labs/instructions.md"));196 const { record } = await prepareImport(repo, "essai", "ed");197 applyImport(record.id, {}, "ed");198 const everything = JSON.stringify(workingManifest()) + ["quiz", "glossary", "lab", "figures"].map((k) => { const s = getSection("S01", k as never); return s ? sectionBody(s) : ""; }).join("");199 expect(everything).not.toContain("CORRIGE_SECRET");200 expect(everything).not.toContain("SECRET-HORS-DEPOT");201 await rm(outside, { recursive: true, force: true });202 });203204 it("reports a source that is not a course repository", async () => {205 const empty = await mkdtemp(join(tmpdir(), "atlas-empty-"));206 expect(await code(async () => prepareImport(empty, "vide", "ed"))).toBe("unreadable_source");207 await rm(empty, { recursive: true, force: true });208 });209});210