SPB Git

Repository Public

import-zip-plan.test.ts 7.3 KB 119 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Note SPBoucher AI8 * File             : tests/unit/import-zip-plan.test.ts9 * Module           : tests10 * Repository       : https://git.spboucher.ai/note-spboucher-ai11 * Project Website  : https://note.spboucher.ai12 * Created          : 2026-11-1713 * Last Modified    : 2026-11-1714 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243/**44 * Pure-logic tests of the ZIP planner, the preview helpers and the job state helpers. No database is opened: the modules under test are45 * imported, but nothing here runs a query (the pg client connects lazily). Run: npx tsx --test tests/unit/import-zip-plan.test.ts46 */47import { test } from "node:test";48import assert from "node:assert/strict";49import JSZip from "jszip";50import { openZip, pageEntries, findOther, readText, readEntry, noExt } from "../../src/lib/import/zip";51import { previewText, relativeRefs, readMarkdown } from "../../src/lib/import/markdown";52import { csvPlan } from "../../src/lib/import/csv";53import { bibDuplicates, parseBibtexSafe } from "../../src/lib/import/bibtex";54import { contentKey, ImportError } from "../../src/lib/import/validate";55import { isStalled, publicJob } from "../../src/lib/import/job";5657const ID = (n: number) => String(n).repeat(32).slice(0, 32);58async function notionZip() {59  const z = new JSZip(); const root = `Export/Projects ${ID(1)}`;60  z.file(`${root}.md`, `# Projects\n\nSee [[Alpha]] and ![fig](Projects%20${ID(1)}/fig.png) ![gone](missing.png)`);61  z.file(`${root}/Alpha ${ID(2)}.md`, "# Alpha\n\nStatus: open\n\nBody *text*.");62  z.file(`${root}/fig.png`, Buffer.from([1, 2, 3]));63  z.file(`${root}/unused.pdf`, Buffer.from("%PDF-1.4"));64  z.file(`${root}/Tasks ${ID(3)}.csv`, "Name,Done\nA,Yes\nB,No\n");65  z.file(`${root}/Tasks ${ID(3)}/A ${ID(4)}.md`, "# A\n\nrow body");66  z.file("Export/.obsidian/app.json", "{}");67  z.file("Export/workspace.json", "{}");68  z.file("Export/refs.bib", "@article{a, title={T}, year={2020}, doi={10.1000/x}}\n@article{b, title={U}}\n@article{a, title={again}}");69  return z.generateAsync({ type: "nodebuffer", compression: "DEFLATE" });70}7172test("a Notion-style archive is classified: ids stripped, top folder removed, CSV → database, row files apart, settings ignored", async () => {73  const plan = await openZip(await notionZip());74  assert.equal(plan.notion, true); assert.equal(plan.obsidian, true); assert.equal(plan.ownExport, true); assert.equal(plan.strip, "Export/");75  assert.deepEqual(pageEntries(plan).map((e) => noExt(e.norm)), ["Projects", "Projects/Alpha"]);76  assert.deepEqual([...plan.csvKeys.keys()], ["Projects/Tasks"]);77  assert.deepEqual(plan.md.map((e) => e.norm).filter((n) => n.startsWith("Projects/Tasks/")), ["Projects/Tasks/A.md"]);78  assert.deepEqual(plan.bibs.map((b) => b.norm), ["refs.bib"]);79  assert.deepEqual(plan.others.map((o) => o.norm).sort(), ["Projects/fig.png", "Projects/unused.pdf"]);80  assert.ok(plan.ignored.some((i) => i.includes(".obsidian")) && plan.ignored.includes("workspace.json"));81});8283test("relative images are resolved inside the archive only; text for duplicate detection ignores images and link syntax", async () => {84  const plan = await openZip(await notionZip()); const first = pageEntries(plan)[0];85  const r = readMarkdown(await readText(first), "Projects.md"); const rel = relativeRefs(r.body);86  assert.equal(r.title, "Projects"); assert.equal(rel.images.length, 2);87  assert.deepEqual(rel.images.map((i) => findOther(plan, noExt(first.norm), i)?.norm ?? null), ["Projects/fig.png", null]);88  assert.equal(findOther(plan, "Projects/Alpha", "../../../etc/passwd"), null);89  assert.equal(contentKey("Projects", previewText(r.body)), contentKey(" projects ", "See Alpha and"));90  assert.notEqual(contentKey("Projects", previewText(r.body)), contentKey("Projects", "See Beta and"));91});9293test("a member that inflates beyond its declared size is refused while reading", async () => {94  const plan = await openZip(await notionZip()); const e = plan.others.find((o) => o.norm === "Projects/unused.pdf")!;95  assert.equal((await readEntry(e)).toString(), "%PDF-1.4");96  await assert.rejects(() => readEntry({ ...e, size: -2000 }), (err) => err instanceof ImportError && err.code === "zip_bomb");97});9899test("CSV plan and BibTeX duplicates (DOI first, then cite key, then repeats inside the file)", async () => {100  assert.deepEqual(csvPlan("Name,Done,N\nA,Yes,1\nB,No,2\n").columns, [{ name: "Done", type: "checkbox" }, { name: "N", type: "number" }]);101  const plan = await openZip(await notionZip());102  const d = bibDuplicates(parseBibtexSafe(await readText(plan.bibs[0])), [{ citeKey: "stored2020", doi: "10.1000/x" }, { citeKey: "B", doi: null }]);103  assert.deepEqual(d.fresh.map((f) => f.citeKey), []);104  assert.deepEqual(d.duplicates.map((x) => [x.citeKey, x.inFile, x.existingKey ?? null]), [["a", false, "stored2020"], ["b", false, "B"], ["a", true, null]]);105  assert.throws(() => parseBibtexSafe("@article{x, title = {unterminated"), (e) => e instanceof ImportError && e.code === "bibtex_parse");106});107108test("job state: stalled after 10 minutes without progress; internal fields never reach the browser", () => {109  const now = new Date().toISOString(); const old = new Date(Date.now() - 11 * 60_000).toISOString();110  assert.equal(isStalled({ status: "running", progress: 0.2, createdAt: old, updatedAt: now, progressAt: old }), true);111  assert.equal(isStalled({ status: "running", progress: 0.2, createdAt: old, updatedAt: now, progressAt: now }), false);112  assert.equal(isStalled({ status: "queued", progress: 0, createdAt: old, updatedAt: old }), true);113  assert.equal(isStalled({ status: "done", progress: 1, createdAt: old, updatedAt: old }), false);114  const pub = publicJob("j", { status: "error", progress: 0, createdAt: now, updatedAt: now, staged: "j-file.zip", workspaceId: "w", userId: "u", runId: "r" }) as Record<string, unknown>;115  assert.equal(pub.canRetry, true); assert.equal(pub.stalled, false);116  for (const k of ["staged", "workspaceId", "userId", "runId"]) assert.ok(!(k in pub), k);117  assert.equal(publicJob("j", { status: "error", progress: 0, createdAt: now, updatedAt: now, staged: null }).canRetry, false);118});119
Files main
Menu

Theme