SPB Git

Repository Public

importer.ts 12.2 KB 207 lines typescript

1/**2 * Curriculum repository → platform content snapshot. Read-only on the source side.3 *4 * Guarantees: idempotent (same input → byte-identical output, no timestamps), every source file hashed,5 * every path confined to the repository (no "..", no symlink escape), size-limited reads, nothing from6 * the repository is executed, a session's material is imported only when its own metadata.yaml says7 * `implemented` or `validated`, and nothing is ever published by the import itself.8 */9import { createHash } from "node:crypto";10import { lstat, mkdir, readFile, readdir, realpath, rm, writeFile } from "node:fs/promises";11import { dirname, join, relative, resolve, sep } from "node:path";12import { parse as parseYaml } from "yaml";13import { z } from "zod";14import { SourceCourse, SourceMetadata, assembleManifest, checkSvg, convertQuiz, parseBibtex, parseGlossary, type ImportedSession } from "../modules/content-schema/adapter";15import { Bibliography, Figures, Glossary, Manifest, Publication, Quiz, isSafeRelPath, type SectionKey, type SectionRef } from "../modules/content-schema/schema";1617const MAX_TEXT = 2_000_000, MAX_SVG = 1_500_000;18const sha256 = (data: string | Buffer) => createHash("sha256").update(data).digest("hex");19const json = (value: unknown) => `${JSON.stringify(value, null, 2)}\n`;2021export interface ImportReport {22  sourceHash: string;23  sessions: { id: string; dir: string | null; status: string; imported: string[]; warnings: string[]; sourceFiles: Record<string, string> }[];24  warnings: string[];25}26export interface ImportOutcome { manifest: Manifest; report: ImportReport; written: string[]; removed: string[]; unchanged: number }2728class Repo {29  private constructor(readonly root: string) {}30  static async open(dir: string): Promise<Repo> { return new Repo(await realpath(resolve(dir))); }3132  /** Reads a file of the repository. Returns null (never throws) when it is absent, unsafe, a non-file or too large. */33  async read(rel: string, max = MAX_TEXT): Promise<Buffer | null> {34    if (!isSafeRelPath(rel)) return null;35    const target = resolve(this.root, rel);36    if (!target.startsWith(this.root + sep)) return null;37    try {38      const real = await realpath(target);39      if (!real.startsWith(this.root + sep)) return null; // symlink pointing outside the repository40      const st = await lstat(real);41      if (!st.isFile() || st.size > max) return null;42      return await readFile(real);43    } catch { return null; }44  }45  async text(rel: string, max = MAX_TEXT): Promise<string | null> { return (await this.read(rel, max))?.toString("utf8") ?? null; }46}4748function yaml(text: string): unknown {49  // Plain data only: the core schema has no custom tags, and alias expansion is capped.50  return parseYaml(text, { schema: "core", maxAliasCount: 50 });51}5253const FigureManifest = z.object({54  figures: z.array(z.object({55    id: z.string(), rendered: z.array(z.string()).default([]), status: z.string().optional(),56    caption: z.string().default(""), alt: z.string().default(""), purpose: z.string().optional(),57  }).loose()),58}).loose();5960export async function importCourse(opts: { repo: string; out: string; publication: unknown; dryRun?: boolean }): Promise<ImportOutcome> {61  const repo = await Repo.open(opts.repo);62  const publication = Publication.parse(opts.publication);63  const outputs = new Map<string, string | Buffer>(); // path relative to `out`64  const report: ImportReport = { sourceHash: "", sessions: [], warnings: [] };6566  const courseText = await repo.text("course.yaml");67  if (courseText === null) throw new Error("course.yaml introuvable ou illisible dans le dépôt du cours");68  const course = SourceCourse.parse(yaml(courseText));69  const allHashes: [string, string][] = [["course.yaml", sha256(courseText)]];70  const imported: ImportedSession[] = [];7172  for (const src of course.sessions) {73    const dir = `sessions/${src.id}-${src.slug}`;74    const entry: ImportReport["sessions"][number] = { id: src.id, dir: null, status: "unknown", imported: [], warnings: [], sourceFiles: {} };75    report.sessions.push(entry);76    const track = (rel: string, data: string | Buffer) => { const h = sha256(data); entry.sourceFiles[rel] = h; allHashes.push([rel, h]); return h; };7778    const metaText = await repo.text(`${dir}/metadata.yaml`);79    let meta: SourceMetadata | null = null;80    if (metaText !== null) {81      entry.dir = dir;82      try {83        const parsed = SourceMetadata.safeParse(yaml(metaText));84        if (parsed.success && parsed.data.id === src.id) { meta = parsed.data; track(`${dir}/metadata.yaml`, metaText); }85        else entry.warnings.push(parsed.success ? `metadata.yaml porte l'identifiant ${parsed.data.id}` : "metadata.yaml incomplet (séance en cours d'écriture ?)");86      } catch { entry.warnings.push("metadata.yaml n'est pas du YAML valide (séance en cours d'écriture ?)"); }87    } else entry.warnings.push("metadata.yaml absent");88    entry.status = meta?.status ?? "unknown";8990    const sections: Partial<Record<SectionKey, SectionRef>> = {};91    const emit = (key: SectionKey, file: string, body: string, count?: number) => {92      const path = `sessions/${src.id}/${file}`;93      outputs.set(path, body);94      sections[key] = { path, sha256: sha256(body), visibility: "private", ...(count !== undefined ? { count } : {}) };95      entry.imported.push(key);96    };9798    // Material is read only when the session's own metadata declares it complete. Anything else is in flux.99    if (meta && (meta.status === "implemented" || meta.status === "validated")) {100      const attempt = async (key: SectionKey, fn: () => Promise<void>) => {101        try { await fn(); } catch (e) { entry.warnings.push(`${key} : ${e instanceof Error ? e.message : "erreur inattendue"}`); }102      };103104      await attempt("quiz", async () => {105        const text = await repo.text(`${dir}/quizzes/questions.yaml`);106        if (text === null) { entry.warnings.push("quiz : quizzes/questions.yaml absent"); return; }107        track(`${dir}/quizzes/questions.yaml`, text);108        const { value, warnings } = convertQuiz(yaml(text));109        entry.warnings.push(...warnings.map((w) => `quiz : ${w}`));110        if (value) emit("quiz", "quiz.json", json(Quiz.parse(value)), value.questions.length);111      });112113      await attempt("glossary", async () => {114        const text = await repo.text(`${dir}/README.md`);115        if (text === null) { entry.warnings.push("glossaire : README.md absent"); return; }116        track(`${dir}/README.md`, text);117        const { value, warnings } = parseGlossary(text, src.id);118        entry.warnings.push(...warnings.map((w) => `glossaire : ${w}`));119        if (value) emit("glossary", "glossary.json", json(Glossary.parse(value)), value.terms.length);120      });121122      await attempt("figures", async () => {123        const text = await repo.text(`${dir}/figures/manifest.yaml`);124        if (text === null) { entry.warnings.push("figures : figures/manifest.yaml absent"); return; }125        track(`${dir}/figures/manifest.yaml`, text);126        const fm = FigureManifest.parse(yaml(text));127        const figures: Figures["figures"] = [];128        for (const fig of fm.figures) {129          const svgRel = fig.rendered.find((r) => r.endsWith(".svg"));130          if (!svgRel) { entry.warnings.push(`figures : ${fig.id} n'a pas de rendu SVG, figure ignorée`); continue; }131          // A figure must live inside its own session directory; "../" references are refused, not followed.132          const rel = `${dir}/figures/${svgRel}`;133          if (!isSafeRelPath(rel)) { entry.warnings.push(`figures : ${fig.id} désigne un chemin hors de la séance, figure ignorée`); continue; }134          if (!fig.alt.trim()) { entry.warnings.push(`figures : ${fig.id} n'a pas de texte de remplacement, figure ignorée`); continue; }135          const svg = await repo.text(rel, MAX_SVG);136          if (svg === null) { entry.warnings.push(`figures : ${svgRel} absent ou trop volumineux, figure ignorée`); continue; }137          const check = checkSvg(svg);138          if (!check.ok) { entry.warnings.push(`figures : ${fig.id} refusée (${check.reason})`); continue; }139          track(rel, svg);140          const file = `figures/${svgRel.split("/").pop()!}`;141          outputs.set(`sessions/${src.id}/${file}`, svg);142          figures.push({ id: fig.id, file, sha256: sha256(svg), caption: fig.caption, alt: fig.alt, ...(fig.purpose ? { purpose: fig.purpose } : {}), ...(check.width ? { width: check.width, height: check.height } : {}) });143        }144        if (figures.length) emit("figures", "figures.json", json(Figures.parse({ figures })), figures.length);145      });146147      // Lab: the instructions only. The solution directory is deliberately never read.148      await attempt("lab", async () => {149        const text = await repo.text(`${dir}/labs/instructions.md`);150        if (text === null) { entry.warnings.push("laboratoire : labs/instructions.md absent"); return; }151        track(`${dir}/labs/instructions.md`, text);152        emit("lab", "lab.md", text);153      });154155      await attempt("script", async () => {156        const text = await repo.text(`${dir}/video/script.md`);157        if (text === null) { entry.warnings.push("scénario : video/script.md absent"); return; }158        track(`${dir}/video/script.md`, text);159        emit("script", "script.md", text);160      });161162      await attempt("bibliography", async () => {163        const text = await repo.text(`${dir}/slides/references.bib`);164        if (text === null) { entry.warnings.push("bibliographie : slides/references.bib absent"); return; }165        track(`${dir}/slides/references.bib`, text);166        const bib = Bibliography.parse(parseBibtex(text));167        if (bib.entries.length) emit("bibliography", "bibliography.json", json(bib), bib.entries.length);168      });169    }170171    const hash = sha256(Object.entries(entry.sourceFiles).sort(([a], [b]) => a.localeCompare(b)).map(([p, h]) => `${p}:${h}`).join("\n"));172    imported.push({173      id: src.id, status: entry.status as ImportedSession["status"], lastReviewed: meta?.last_reviewed ?? null,174      videoRecorded: meta?.deliverables?.video_recorded === true, effortMinutes: meta?.effort_minutes ?? null, hash, sections,175    });176  }177178  report.sourceHash = sha256(allHashes.sort(([a], [b]) => a.localeCompare(b)).map(([p, h]) => `${p}:${h}`).join("\n"));179  for (const [id, ed] of Object.entries(publication.sessions)) {180    const imp = imported.find((s) => s.id === id);181    if (!imp) { report.warnings.push(`publication.json mentionne ${id}, absente du cours`); continue; }182    for (const key of Object.keys(ed.sections ?? {})) if (!imp.sections[key as SectionKey]) report.warnings.push(`publication.json règle la visibilité de ${id}.${key}, qui n'a pas été importée`);183    if ((ed.publication === "published" || ed.publication === "preview") && !Object.keys(imp.sections).length) report.warnings.push(`${id} est marquée « ${ed.publication} » sans aucun contenu importé`);184  }185186  const manifest = assembleManifest(course, imported, publication, { sourceHash: report.sourceHash, files: allHashes.length });187  outputs.set("report.json", json(report));188189  // Write only what changed; remove what this run no longer produces (inside the import directory only).190  const importDir = join(resolve(opts.out), "import"), manifestPath = join(resolve(opts.out), "course.manifest.json");191  const written: string[] = [], removed: string[] = [];192  let unchanged = 0;193  const put = async (path: string, body: string | Buffer) => {194    const current = await readFile(path).catch(() => null);195    if (current && Buffer.compare(current, Buffer.from(body)) === 0) { unchanged++; return; }196    written.push(path);197    if (!opts.dryRun) { await mkdir(dirname(path), { recursive: true }); await writeFile(path, body); }198  };199  for (const [rel, body] of outputs) await put(join(importDir, rel), body);200  await put(manifestPath, json(manifest));201  const walk = async (d: string): Promise<string[]> => (await readdir(d, { withFileTypes: true }).catch(() => [])).flatMap((e) => (e.isDirectory() ? [] : [join(d, e.name)])).concat(...(await Promise.all((await readdir(d, { withFileTypes: true }).catch(() => [])).filter((e) => e.isDirectory()).map((e) => walk(join(d, e.name))))));202  for (const file of await walk(importDir)) {203    if (!outputs.has(relative(importDir, file).split(sep).join("/"))) { removed.push(file); if (!opts.dryRun) await rm(file); }204  }205  return { manifest, report, written, removed, unchanged };206}207
Files main
Menu

Theme