forked from r.muellner/velum-raycast
feat: run Velum project jobs in the background and process DOCX locally
This commit is contained in:
@@ -1,7 +1,9 @@
|
||||
import { expect, it } from "bun:test";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { zipSync, unzipSync, strToU8, strFromU8 } from "fflate";
|
||||
import ts from "typescript";
|
||||
import * as xlsxRestoration from "../src/lib/xlsx-restoration";
|
||||
import * as imagePolicy from "../src/lib/image-policy";
|
||||
import * as projectCapabilities from "../src/lib/project-capabilities";
|
||||
import { checkedImagePolicy, checkedImageReport, DEFAULT_IMAGE_POLICY, KEEP_IMAGE_WARNING, sameImagePolicyCoverage, summarizeImages } from "../src/lib/image-policy";
|
||||
@@ -60,6 +62,7 @@ it("übermittelt dieselbe Bildoption in Vorschau, Anwendung und erneutem Abgleic
|
||||
} },
|
||||
"./preferences": { getPreferences: () => ({ velumBaseUrl: "https://velum.test" }) },
|
||||
"./lib/image-policy": imagePolicy,
|
||||
"./lib/xlsx-restoration": xlsxRestoration,
|
||||
"./lib/project-capabilities": projectCapabilities,
|
||||
};
|
||||
const module = { exports: {} as { pseudonymizeDocument: (...args: unknown[]) => Promise<unknown>; requireProjectCapabilities: (images?: boolean) => Promise<void> } };
|
||||
@@ -81,3 +84,32 @@ it("übermittelt dieselbe Bildoption in Vorschau, Anwendung und erneutem Abgleic
|
||||
await expect(api.requireProjectCapabilities(true)).rejects.toThrow();
|
||||
await api.requireProjectCapabilities(false);
|
||||
});
|
||||
|
||||
|
||||
it("restores XLSX locally and keeps the API route for DOCX", async () => {
|
||||
const require = createRequire(import.meta.url);
|
||||
const code = ts.transpileModule(readFileSync(new URL("../src/velum.ts", import.meta.url), "utf8"), {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2023 },
|
||||
}).outputText;
|
||||
let requests = 0;
|
||||
const mocks: Record<string, unknown> = {
|
||||
"./auth": { fetchWithAuth: async () => { requests++; return Response.json({ file_base64: Buffer.from("restored docx").toString("base64") }); } },
|
||||
"./preferences": { getPreferences: () => ({ velumBaseUrl: "https://velum.test" }) },
|
||||
"./lib/image-policy": imagePolicy,
|
||||
"./lib/project-capabilities": projectCapabilities,
|
||||
"./lib/xlsx-restoration": xlsxRestoration,
|
||||
};
|
||||
const module = { exports: {} as { depseudonymizeDocument: (name: string, data: Buffer, mapping: Record<string, { original: string; type: string }>) => Promise<Buffer> } };
|
||||
new Function("require", "module", "exports", code)((id: string) => mocks[id] ?? require(id), module, module.exports);
|
||||
const zip = zipSync({
|
||||
"[Content_Types].xml": strToU8('<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"/>'),
|
||||
"xl/workbook.xml": strToU8('<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheets><sheet name="PERSON_01"/></sheets></workbook>'),
|
||||
});
|
||||
const restored = await module.exports.depseudonymizeDocument("book.XLSX", Buffer.from(zip), {
|
||||
PERSON_01: { original: "Anna", type: "PERSON" },
|
||||
});
|
||||
expect(requests).toBe(0);
|
||||
expect(strFromU8(unzipSync(restored)["xl/workbook.xml"])).toContain('name="Anna"');
|
||||
expect(await module.exports.depseudonymizeDocument("book.docx", Buffer.from("docx"), {})).toEqual(Buffer.from("restored docx"));
|
||||
expect(requests).toBe(1);
|
||||
});
|
||||
|
||||
92
tests/mapping-export.test.ts
Normal file
92
tests/mapping-export.test.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
import { afterEach, expect, it } from "bun:test";
|
||||
import { promises as fs } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { basename, dirname, join } from "node:path";
|
||||
import type { PlaceholderMapping } from "../src/types";
|
||||
import { mappingExport, writeMappingExport } from "../src/lib/mapping-export";
|
||||
|
||||
const mapping: PlaceholderMapping = {
|
||||
PERSON_02: { type: "PERSON", original: "Zweiter Name", merged_into: "PERSON_01" },
|
||||
ORG_01: { type: "ORG", original: "Äpfel GmbH" },
|
||||
PERSON_01: { type: "PERSON", original: "Anna Beispiel" },
|
||||
PERSON_03: { type: "PERSON", original: "Anna Beispiel", merged_into: "PERSON_01" },
|
||||
};
|
||||
const roots: string[] = [];
|
||||
afterEach(async () => { await Promise.all(roots.splice(0).map((path) => fs.rm(path, { recursive: true, force: true }))); });
|
||||
async function temporaryDirectory() {
|
||||
const path = await fs.mkdtemp(join(tmpdir(), "velum-mapping-export-"));
|
||||
roots.push(path);
|
||||
return path;
|
||||
}
|
||||
|
||||
it("exportiert alle Originalbegriffe samt Varianten einmal und ohne Platzhalter", () => {
|
||||
const snapshot = structuredClone(mapping);
|
||||
expect(mappingExport(mapping, "terms")).toEqual({
|
||||
text: "Anna Beispiel\nÄpfel GmbH\nZweiter Name\n", count: 3,
|
||||
});
|
||||
expect(mapping).toEqual(snapshot);
|
||||
});
|
||||
|
||||
it("exportiert jede wirksame Ersetzung und bewahrt unterschiedliche Platzhalter desselben Originals", () => {
|
||||
const result = mappingExport({ ...mapping,
|
||||
BEGRIFF_01: { type: "BEGRIFF", original: "Anna Beispiel" },
|
||||
}, "replacements");
|
||||
expect(result.count).toBe(4);
|
||||
expect(result.text.split("\n").filter(Boolean)).toEqual([
|
||||
"Anna Beispiel → BEGRIFF_01", "Anna Beispiel → PERSON_01",
|
||||
"Äpfel GmbH → ORG_01", "Zweiter Name → PERSON_01",
|
||||
]);
|
||||
expect(result.text).not.toContain("→ PERSON_02");
|
||||
});
|
||||
|
||||
it("erhält Unicode, Klammer-Platzhalter sowie unterscheidbare Tabs und Zeilenumbrüche", () => {
|
||||
const special = { "<PERSON_01>": { type: "PERSON", original: "Jörg\nMüller\r\nA\tB\\n" } };
|
||||
expect(mappingExport(special, "terms").text).toBe("Jörg\\nMüller\\r\\nA\\tB\\\\n\n");
|
||||
expect(mappingExport(special, "replacements").text).toBe("Jörg\\nMüller\\r\\nA\\tB\\\\n → <PERSON_01>\n");
|
||||
});
|
||||
|
||||
it("berücksichtigt den übergebenen aktuellen Stand einschließlich neuer und gelöster Zuordnungen", () => {
|
||||
const current = { ...mapping,
|
||||
PERSON_02: { ...mapping.PERSON_02, merged_into: undefined },
|
||||
EMAIL_01: { type: "EMAIL", original: "neu@example.test" },
|
||||
};
|
||||
const text = mappingExport(current, "replacements").text;
|
||||
expect(text).toContain("Zweiter Name → PERSON_02\n");
|
||||
expect(text).toContain("neu@example.test → EMAIL_01\n");
|
||||
});
|
||||
|
||||
it("schreibt UTF-8 lokal mit privaten Rechten und überschreibt keine vorhandenen Exporte", async () => {
|
||||
const directory = await temporaryDirectory();
|
||||
const first = await writeMappingExport("Projekt", mapping, "terms", directory);
|
||||
const second = await writeMappingExport("Projekt", mapping, "terms", directory);
|
||||
const replacements = await writeMappingExport("Projekt", mapping, "replacements", directory);
|
||||
expect(basename(first.path)).toBe("Projekt-begriffe.txt");
|
||||
expect(basename(second.path)).toBe("Projekt-begriffe (2).txt");
|
||||
expect(basename(replacements.path)).toBe("Projekt-ersetzungen.txt");
|
||||
expect(await fs.readFile(first.path, "utf8")).toBe(mappingExport(mapping, "terms").text);
|
||||
expect(await fs.readFile(replacements.path, "utf8")).toBe(mappingExport(mapping, "replacements").text);
|
||||
for (const file of [first, second, replacements]) expect((await fs.stat(file.path)).mode & 0o777).toBe(0o600);
|
||||
expect((await fs.readdir(directory)).length).toBe(3);
|
||||
});
|
||||
|
||||
it("begrenzt Dateinamen auf das Exportverzeichnis und bewahrt parallele Exporte", async () => {
|
||||
const directory = await temporaryDirectory();
|
||||
const exports = await Promise.all(Array.from({ length: 4 }, () =>
|
||||
writeMappingExport("../../Projekt\\Datei\n" + "漢".repeat(200), mapping, "terms", directory)));
|
||||
expect(new Set(exports.map((file) => file.path)).size).toBe(4);
|
||||
for (const file of exports) {
|
||||
expect(dirname(file.path)).toBe(directory);
|
||||
expect(Buffer.byteLength(basename(file.path))).toBeLessThan(255);
|
||||
expect(await fs.readFile(file.path, "utf8")).toBe(mappingExport(mapping, "terms").text);
|
||||
}
|
||||
expect((await fs.readdir(directory)).length).toBe(4);
|
||||
});
|
||||
|
||||
it("erzeugt bei leerer Tabelle oder defekten Gruppen keine unvollständige Exportdatei", async () => {
|
||||
const directory = await temporaryDirectory();
|
||||
expect(mappingExport({}, "terms")).toEqual({ text: "", count: 0 });
|
||||
await expect(writeMappingExport("Leer", {}, "terms", directory)).rejects.toThrow("keine Begriffe");
|
||||
const broken = { PERSON_01: { type: "PERSON", original: "Name", merged_into: "PERSON_02" } };
|
||||
await expect(writeMappingExport("Defekt", broken, "replacements", directory)).rejects.toThrow("Hauptbegriff");
|
||||
expect(await fs.readdir(directory)).toEqual([]);
|
||||
});
|
||||
73
tests/project-jobs.test.ts
Normal file
73
tests/project-jobs.test.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { execFile, spawn } from "node:child_process";
|
||||
import { once } from "node:events";
|
||||
import { promises as fs } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
const exec = promisify(execFile);
|
||||
|
||||
test("the saved project job survives termination of its launching process", async () => {
|
||||
const temporary = await fs.mkdtemp(join(tmpdir(), "velum-worker-test-"));
|
||||
const launcher = join(temporary, "launcher.cjs");
|
||||
const assets = join(temporary, "assets");
|
||||
const support = join(temporary, "support");
|
||||
const root = join(temporary, "project");
|
||||
await fs.mkdir(assets);
|
||||
const runtime = resolve("src/lib/worker-runtime.ts");
|
||||
const jobs = resolve("src/lib/project-jobs.ts");
|
||||
let parent: ReturnType<typeof spawn> | undefined;
|
||||
try {
|
||||
await fs.writeFile(join(assets, "velum-project-worker.cjs"), `
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
process.stdin.resume();
|
||||
process.stdin.once("end", () => setTimeout(() => {
|
||||
fs.writeFileSync(path.join(process.argv[2], "state.json"), JSON.stringify({ phase: "review" }), { mode: 0o600 });
|
||||
}, 400));
|
||||
`);
|
||||
const entry = join(temporary, "launcher.ts");
|
||||
await fs.writeFile(entry, `
|
||||
import { configureWorker } from ${JSON.stringify(runtime)};
|
||||
import { projectJobDirectory, startProjectAnalysis } from ${JSON.stringify(jobs)};
|
||||
configureWorker({
|
||||
assets: ${JSON.stringify(assets)}, support: ${JSON.stringify(support)},
|
||||
preferences: { velumBaseUrl: "https://example.invalid", authentikTokenUrl: "https://example.invalid/token",
|
||||
clientId: "test", serviceAccountUsername: "test", serviceAccountPassword: "synthetic-secret" },
|
||||
});
|
||||
const root = ${JSON.stringify(root)};
|
||||
startProjectAnalysis({ root, files: [], rules: [], whitelist: [], entityTypes: ["PERSON"], skipped: [],
|
||||
reanalyzeUnchanged: false, imagePolicy: "placeholder", fileSelectionChanged: false }).then(() => {
|
||||
console.log(projectJobDirectory(root));
|
||||
setInterval(() => {}, 1_000);
|
||||
});
|
||||
`);
|
||||
await exec(resolve("node_modules/.bin/esbuild"), [entry, "--bundle", "--platform=node",
|
||||
`--alias:@raycast/api=${runtime}`, `--outfile=${launcher}`]);
|
||||
const child = spawn(process.execPath, [launcher], { stdio: ["ignore", "pipe", "inherit"] });
|
||||
parent = child;
|
||||
const terminated = once(child, "exit");
|
||||
const [pending] = await Promise.race([
|
||||
once(child.stdout, "data"),
|
||||
terminated.then(() => { throw new Error("Projektauftrag konnte nicht gestartet werden."); }),
|
||||
]);
|
||||
const directory = String(pending).trim();
|
||||
child.kill("SIGKILL");
|
||||
await terminated;
|
||||
const state = join(directory, "state.json");
|
||||
let phase: string | undefined;
|
||||
for (let attempt = 0; attempt < 50; attempt++) {
|
||||
phase = JSON.parse(await fs.readFile(state, "utf8")).phase;
|
||||
if (phase === "review") break;
|
||||
await new Promise((done) => setTimeout(done, 40));
|
||||
}
|
||||
expect(phase).toBe("review");
|
||||
const input = join(directory, "input.json");
|
||||
expect(await fs.readFile(input, "utf8")).not.toContain("synthetic-secret");
|
||||
expect((await fs.stat(input)).mode & 0o777).toBe(0o600);
|
||||
} finally {
|
||||
parent?.kill();
|
||||
await fs.rm(temporary, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
78
tests/project-text-large.test.ts
Normal file
78
tests/project-text-large.test.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
import { expect, it } from "bun:test";
|
||||
import { promises as fs } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import { analyzeProjectTextFiles } from "../src/lib/project-analysis";
|
||||
import { projectTextAnalyzer } from "../src/lib/project-text-mapping";
|
||||
import { hashProjectFile, writeReplacedTextFile } from "../src/lib/project-text-stream";
|
||||
|
||||
it("processes 27 MiB with over 50000 occurrences and over 5000 identities without changing unselected bytes", async () => {
|
||||
const root = await fs.mkdtemp(join(tmpdir(), "velum-dense-"));
|
||||
try {
|
||||
const source = join(root, "27MiB.txt"), target = join(root, "masked.txt");
|
||||
const handle = await fs.open(source, "w");
|
||||
let bytes = 0, rows = 0;
|
||||
const expected = createHash("sha256");
|
||||
while (bytes < 27 * 1024 * 1024) {
|
||||
let block = "";
|
||||
for (let i = 0; i < 500; i++, rows++) {
|
||||
const original = `customer${rows % 10_000}@example.invalid`;
|
||||
const row = `😀 Max Mustermann; ${original}; 08.11.2026; ${"Protokolltext ".repeat(14)}\r\n`;
|
||||
block += row;
|
||||
// Only the first name is selected; every other byte must survive.
|
||||
expected.update(row.replace("Max Mustermann", "PERSON_01"));
|
||||
}
|
||||
bytes += Buffer.byteLength(block);
|
||||
await handle.writeFile(block);
|
||||
}
|
||||
await handle.close();
|
||||
const hash = await hashProjectFile(source);
|
||||
let requests = 0, maxRequestMapping = 0;
|
||||
const analyze = projectTextAnalyzer({}, async (text, mapping, types) => {
|
||||
requests++;
|
||||
maxRequestMapping = Math.max(maxRequestMapping, Object.keys(mapping).length);
|
||||
const responseMapping: Record<string, { original: string; type: string }> = {};
|
||||
const local = new Map<string, string>(), counters: Record<string, number> = {};
|
||||
const spans = [];
|
||||
let previous = 0, position = 0;
|
||||
for (const match of text.matchAll(/Max Mustermann|customer\d+@example\.invalid|08\.11\.2026/g)) {
|
||||
const type = match[0] === "Max Mustermann" ? "PERSON" : match[0].includes("@") ? "EMAIL" : "DATUM";
|
||||
let placeholder = local.get(match[0]);
|
||||
if (!placeholder) {
|
||||
counters[type] = (counters[type] ?? 0) + 1;
|
||||
placeholder = `${type}_${String(counters[type]).padStart(2, "0")}`;
|
||||
local.set(match[0], placeholder);
|
||||
responseMapping[placeholder] = { original: match[0], type };
|
||||
}
|
||||
position += Array.from(text.slice(previous, match.index)).length;
|
||||
previous = match.index;
|
||||
const start = position;
|
||||
spans.push({ start, end: start + match[0].length, original: match[0], type, placeholder, score: 1 });
|
||||
}
|
||||
return JSON.parse(JSON.stringify({ pseudonymized_text: text, selected_entity_types: types,
|
||||
mapping: responseMapping, spans, entity_count: local.size }));
|
||||
});
|
||||
const result = await analyzeProjectTextFiles([{ key: "large.txt", path: source }], {},
|
||||
["PERSON", "EMAIL", "DATUM"], {}, analyze, () => undefined);
|
||||
const spans = result.spansByFile.get("large.txt")!;
|
||||
if (spans.length !== rows * 3) throw Error(`Lost hits: ${spans.length}/${rows * 3}`);
|
||||
if (Object.keys(result.mapping).length !== 10_002) throw Error("Lost project mapping");
|
||||
if (maxRequestMapping > 5000) throw Error("API mapping limit exceeded");
|
||||
const accepted = new Set<string>();
|
||||
const selected = spans.filter((span) => span.type === "PERSON").map((span, index) => {
|
||||
const id = String(index); accepted.add(id);
|
||||
if (span.placeholder !== "PERSON_01") throw Error("Unstable person placeholder");
|
||||
return { ...span, id };
|
||||
});
|
||||
const output = await writeReplacedTextFile(source, target, selected, accepted, hash);
|
||||
if (output !== expected.digest("hex")) throw Error("Output bytes do not match approved replacements");
|
||||
if (await hashProjectFile(source) !== hash) throw Error("Original modified");
|
||||
expect(bytes).toBeGreaterThanOrEqual(27 * 1024 * 1024);
|
||||
expect(spans.length).toBeGreaterThan(50_000);
|
||||
expect(maxRequestMapping).toBeLessThanOrEqual(5000);
|
||||
expect(requests).toBeGreaterThan(1000);
|
||||
|
||||
} finally { await fs.rm(root, { recursive: true, force: true }); }
|
||||
|
||||
}, 30_000);
|
||||
82
tests/project-text-mapping.test.ts
Normal file
82
tests/project-text-mapping.test.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import { expect, it } from "bun:test";
|
||||
import { projectTextAnalyzer } from "../src/lib/project-text-mapping";
|
||||
import type { PlaceholderMapping } from "../src/types";
|
||||
|
||||
it("keeps more than 5000 project identities without sending historical NER mappings", async () => {
|
||||
const previous: PlaceholderMapping = {};
|
||||
for (let i = 1; i <= 6000; i++) previous[`PERSON_${i}`] = { original: `Person ${i}`, type: "PERSON" };
|
||||
const analyze = projectTextAnalyzer(previous, async (text, mapping) => {
|
||||
expect(Object.keys(mapping)).toHaveLength(0);
|
||||
return { pseudonymized_text: "PERSON_01", selected_entity_types: ["PERSON"], entity_count: 1,
|
||||
mapping: { PERSON_01: { original: text, type: "PERSON" } },
|
||||
spans: [{ start: 0, end: [...text].length, original: text, placeholder: "PERSON_01", type: "PERSON", score: 1 }] };
|
||||
});
|
||||
const first = await analyze("Anna Berger", previous, ["PERSON"], {});
|
||||
expect(first.spans[0].placeholder).toBe("PERSON_6001");
|
||||
const repeat = await analyze("Anna Berger", first.mapping, ["PERSON"], {});
|
||||
expect(repeat.spans[0].placeholder).toBe("PERSON_6001");
|
||||
const known = await analyze("Person 4321", repeat.mapping, ["PERSON"], {});
|
||||
expect(known.spans[0].placeholder).toBe("PERSON_4321");
|
||||
expect(Object.keys(known.mapping)).toHaveLength(6001);
|
||||
expect(Object.keys(previous)).toHaveLength(6000);
|
||||
});
|
||||
|
||||
it("preserves custom terms and complete manual alias dependencies", async () => {
|
||||
const previous: PlaceholderMapping = {
|
||||
PERSON_90: { original: "Anna Berger", type: "PERSON" },
|
||||
PERSON_91: { original: "Anna", type: "PERSON", merged_into: "PERSON_90" },
|
||||
BEGRIFF_07: { original: "/CLIENT/ABC", type: "BEGRIFF" },
|
||||
BEGRIFF_08: { original: "Other project", type: "BEGRIFF" },
|
||||
};
|
||||
const analyze = projectTextAnalyzer(previous, async (text, mapping, types) => {
|
||||
expect(Object.keys(mapping).sort()).toEqual(["BEGRIFF_07", "PERSON_90", "PERSON_91"]);
|
||||
return { pseudonymized_text: text, selected_entity_types: types, entity_count: 3, mapping,
|
||||
spans: [{ start: 0, end: 4, original: "Anna", placeholder: "PERSON_90", type: "PERSON", score: 1 }] };
|
||||
});
|
||||
const result = await analyze("Anna nutzt /CLIENT/ABC", previous, ["PERSON", "BEGRIFF"], {});
|
||||
expect(result.pseudonymized_text).toBe("PERSON_90 nutzt /CLIENT/ABC");
|
||||
expect(result.mapping.PERSON_91.merged_into).toBe("PERSON_90");
|
||||
});
|
||||
|
||||
it("leaves literal placeholders alone and rebuilds Unicode output from positions", async () => {
|
||||
const previous = { PERSON_12: { original: "Berta", type: "PERSON" } };
|
||||
const text = "😀 PERSON_01 Anna";
|
||||
const analyze = projectTextAnalyzer(previous, async () => ({
|
||||
pseudonymized_text: "😀 PERSON_01 PERSON_01", selected_entity_types: ["PERSON"], entity_count: 1,
|
||||
mapping: { PERSON_01: { original: "Anna", type: "PERSON" } },
|
||||
spans: [{ start: 12, end: 16, original: "Anna", placeholder: "PERSON_01", type: "PERSON", score: 1 }],
|
||||
}));
|
||||
const result = await analyze(text, previous, ["PERSON"], {});
|
||||
expect(result.pseudonymized_text).toBe("😀 PERSON_01 PERSON_13");
|
||||
});
|
||||
|
||||
it("does not retry authentication errors or keep results from a failed API call", async () => {
|
||||
let calls = 0;
|
||||
const analyze = projectTextAnalyzer({}, async () => { calls++; throw Error("HTTP 403"); });
|
||||
await expect(analyze("Anna", {}, ["PERSON"], {})).rejects.toThrow("403");
|
||||
expect(calls).toBe(1);
|
||||
});
|
||||
|
||||
|
||||
it("retains mappings added by another phase between text requests", async () => {
|
||||
const analyze = projectTextAnalyzer({}, async (text) => ({
|
||||
pseudonymized_text: "PERSON_01", selected_entity_types: ["PERSON"], entity_count: 1,
|
||||
mapping: { PERSON_01: { original: text, type: "PERSON" } },
|
||||
spans: [{ start: 0, end: text.length, original: text, placeholder: "PERSON_01", type: "PERSON", score: 1 }],
|
||||
}));
|
||||
const first = await analyze("Anna", {}, ["PERSON"], {});
|
||||
const withDocument = { ...first.mapping, PERSON_02: { original: "Berta", type: "PERSON" } };
|
||||
const next = await analyze("Clara", withDocument, ["PERSON"], {});
|
||||
expect(next.mapping.PERSON_02.original).toBe("Berta");
|
||||
expect(next.spans[0].placeholder).toBe("PERSON_03");
|
||||
});
|
||||
|
||||
|
||||
it("passes known multiword terms across whitespace and line boundaries", async () => {
|
||||
const previous = { BEGRIFF_01: { original: "Private Term", type: "BEGRIFF" } };
|
||||
const analyze = projectTextAnalyzer(previous, async (text, mapping) => {
|
||||
expect(mapping.BEGRIFF_01.original).toBe("Private Term");
|
||||
return { pseudonymized_text: text, mapping, spans: [], entity_count: 1, selected_entity_types: ["BEGRIFF"] };
|
||||
});
|
||||
await analyze("Private\nTerm", previous, ["BEGRIFF"], {});
|
||||
});
|
||||
@@ -19,6 +19,7 @@ mock.module("@raycast/api", () => ({
|
||||
const { applyProjectWhitelist, pseudonymizeInContext, prepareTextInContext, commitPreparedText } = await import("../src/text-context");
|
||||
const project = await import("../src/lib/velum-project");
|
||||
const sessions = await import("../src/sessions");
|
||||
const { relocateProject } = await import("../src/lib/project-relocation");
|
||||
const { normalizePseudonymizeResponse } = await import("../src/velum");
|
||||
const roots: string[] = [];
|
||||
afterEach(async () => {
|
||||
@@ -182,3 +183,72 @@ it("verwendet die bestehende Projekttabelle und bewahrt ihre Verweise für spät
|
||||
expect(runs[0].run.mapping.PERSON_03.original).toBe("Mara Muster");
|
||||
expect(runs[1].run.mapping.PERSON_03).toBeUndefined();
|
||||
});
|
||||
|
||||
it.each(["review", "direct"])("verwendet gespeicherte Projektzuordnungen nach Verschieben des Quellordners (%s)", async (mode) => {
|
||||
const root = await fs.mkdtemp(join(tmpdir(), "velum-text-moved-"));
|
||||
roots.push(root);
|
||||
const folder = join(root, "Quelle");
|
||||
await fs.mkdir(folder);
|
||||
roots.push(project.projectDataRoot(folder));
|
||||
const saved = await project.createRun(folder);
|
||||
saved.run.mapping = { PERSON_01: { type: "PERSON", original: "Max" } };
|
||||
await project.saveRun(saved.directory, saved.run);
|
||||
await fs.rename(folder, join(root, "Verschoben"));
|
||||
const values = { sessionId: `project:${folder}` };
|
||||
let expectedMapping = saved.run.mapping;
|
||||
const request = async (_text: string, mapping: PlaceholderMapping): Promise<PseudonymizeResponse> => {
|
||||
expect(mapping).toEqual(expectedMapping);
|
||||
return {
|
||||
pseudonymized_text: "PERSON_01 und PERSON_02", selected_entity_types: ["PERSON"], entity_count: 2,
|
||||
mapping: { ...mapping, PERSON_02: { type: "PERSON", original: "Mara" } },
|
||||
spans: [
|
||||
{ start: 0, end: 3, type: "PERSON", score: 1, placeholder: "PERSON_01", original: "Max" },
|
||||
{ start: 8, end: 12, type: "PERSON", score: 1, placeholder: "PERSON_02", original: "Mara" },
|
||||
],
|
||||
};
|
||||
};
|
||||
const output = mode === "review"
|
||||
? await commitPreparedText(await prepareTextInContext(values, "Max und Mara", ["PERSON"], request), new Set([0, 1]))
|
||||
: await pseudonymizeInContext(values, "Max und Mara", ["PERSON"], false, request);
|
||||
expect(output.result.pseudonymized_text).toBe("PERSON_01 und PERSON_02");
|
||||
expect(output.session.id).toBe(`project:${folder}`);
|
||||
const runs = await project.listRuns(folder);
|
||||
expect(runs).toHaveLength(2);
|
||||
expect(runs[0].run.mapping.PERSON_02.original).toBe("Mara");
|
||||
expect(runs[1].run.mapping.PERSON_02).toBeUndefined();
|
||||
|
||||
const moved = join(root, "Verschoben");
|
||||
roots.push(project.projectDataRoot(moved));
|
||||
await relocateProject(folder, moved);
|
||||
expect(await project.listRuns(folder)).toHaveLength(0);
|
||||
expectedMapping = runs[0].run.mapping;
|
||||
const movedValues = { sessionId: `project:${moved}` };
|
||||
const next = mode === "review"
|
||||
? await commitPreparedText(await prepareTextInContext(movedValues, "Max und Mara", ["PERSON"], request), new Set([0, 1]))
|
||||
: await pseudonymizeInContext(movedValues, "Max und Mara", ["PERSON"], false, request);
|
||||
expect(next.session.id).toBe(`project:${moved}`);
|
||||
expect(next.result.pseudonymized_text).toBe(output.result.pseudonymized_text);
|
||||
expect((await project.listRuns(moved))[0].run.mapping).toEqual(expectedMapping);
|
||||
});
|
||||
|
||||
it.each(["review", "direct"])("prüft den Ordner weiterhin für neue Projekte und verlangt einen gespeicherten Stand für bestehende (%s)", async (mode) => {
|
||||
const root = await fs.mkdtemp(join(tmpdir(), "velum-text-validation-"));
|
||||
roots.push(root);
|
||||
const missing = join(root, "Fehlt");
|
||||
const file = join(root, "Datei.txt");
|
||||
await fs.writeFile(file, "kein Ordner");
|
||||
let requests = 0;
|
||||
const request = async (): Promise<PseudonymizeResponse> => {
|
||||
requests++;
|
||||
throw new Error("Die API darf bei ungültigem Kontext nicht aufgerufen werden.");
|
||||
};
|
||||
const run = (values: { sessionId: string; newProjectPath?: string[] }) => mode === "review"
|
||||
? prepareTextInContext(values, "Max", ["PERSON"], request)
|
||||
: pseudonymizeInContext(values, "Max", ["PERSON"], false, request);
|
||||
for (const folder of [undefined, missing, file]) {
|
||||
await expect(run({ sessionId: "__new_project__", newProjectPath: folder ? [folder] : undefined }))
|
||||
.rejects.toThrow("Bitte einen vorhandenen Projektordner wählen.");
|
||||
}
|
||||
await expect(run({ sessionId: `project:${missing}` })).rejects.toThrow("Projektstand nicht gefunden.");
|
||||
expect(requests).toBe(0);
|
||||
});
|
||||
|
||||
@@ -508,3 +508,21 @@ it("erfasst große Textdateien weiterhin, behält aber die Office-Uploadgrenze",
|
||||
expect(result.files.map((file) => file.relPath)).toEqual(["large.txt"]);
|
||||
expect(result.skipped).toEqual([{ path: "large.docx", reason: "Datei zu groß (Grenze: 20 MiB)" }]);
|
||||
});
|
||||
|
||||
|
||||
it("offers large XLSX files for local restoration while keeping the upload limit for pseudonymization", async () => {
|
||||
const root = await fs.mkdtemp(join(tmpdir(), "velum-large-xlsx-scan-")); roots.push(root);
|
||||
const source = join(root, "source"); await fs.mkdir(source);
|
||||
for (const name of ["large.xlsx", "large.docx"]) {
|
||||
const handle = await fs.open(join(source, name), "w");
|
||||
await handle.write(Buffer.from([0x50, 0x4b, 0x03, 0x04]));
|
||||
await handle.truncate(21 * 1024 * 1024); await handle.close();
|
||||
}
|
||||
const { run, directory } = await project.createRun(source, join(root, "support"));
|
||||
run.inPlace = true;
|
||||
const upload = await project.scanProjectFiles(source);
|
||||
expect(upload.files).toHaveLength(0);
|
||||
const restore = await project.scanRestorableCopyFiles(run, directory);
|
||||
expect(restore.files.map((file) => file.relPath)).toEqual(["large.xlsx"]);
|
||||
expect(restore.skipped).toBe(1);
|
||||
});
|
||||
|
||||
119
tests/xlsx-restoration.test.ts
Normal file
119
tests/xlsx-restoration.test.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
import { afterEach, expect, it } from "bun:test";
|
||||
import { promises as fs } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { zipSync, unzipSync, strToU8, strFromU8 } from "fflate";
|
||||
import { SaxesParser } from "saxes";
|
||||
import { restoreXlsxFile } from "../src/lib/xlsx-restoration";
|
||||
|
||||
const S = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
|
||||
const roots: string[] = [];
|
||||
afterEach(async () => { for (const root of roots.splice(0)) await fs.rm(root, { recursive: true, force: true }); });
|
||||
async function fixture(parts: Record<string, Uint8Array> = {}) {
|
||||
const root = await fs.mkdtemp(join(tmpdir(), "velum-xlsx-restore-")); roots.push(root);
|
||||
const source = join(root, "source.xlsx"), target = join(root, "restored.xlsx");
|
||||
await fs.writeFile(source, zipSync({
|
||||
"[Content_Types].xml": strToU8('<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"/>'),
|
||||
"xl/workbook.xml": strToU8(`<workbook xmlns="${S}"><sheets><sheet name="PERSON_01" sheetId="1"/></sheets></workbook>`),
|
||||
...parts,
|
||||
}, { level: 0 }));
|
||||
return { source, target };
|
||||
}
|
||||
function xmlTexts(xml: string): string[] {
|
||||
const values: string[] = [];
|
||||
const parser = new SaxesParser();
|
||||
parser.on("text", (text) => values.push(text));
|
||||
parser.write(xml).close();
|
||||
return values;
|
||||
}
|
||||
|
||||
it("restores placeholders across rich-text runs while preserving XML escaping and boundaries", async () => {
|
||||
const { source, target } = await fixture({
|
||||
"xl/sharedStrings.xml": strToU8(`<sst xmlns="${S}" count="2" uniqueCount="2"><si><r><t>PER</t></r><r><rPr><b/></rPr><t>SON_01</t></r></si><si><t>PERSON_010 PERSON_01 xPERSON_01 ÄPERSON_01 UNKNOWN_99</t></si></sst>`),
|
||||
"xl/media/image1.png": Uint8Array.from([0, 42, 255]),
|
||||
});
|
||||
const before = await fs.readFile(source);
|
||||
const result = await restoreXlsxFile(source, target, {
|
||||
PERSON_01: { original: 'A & B <Müller> "😀"', type: "PERSON" },
|
||||
PERSON_010: { original: "Anna", type: "PERSON" },
|
||||
});
|
||||
const parts = unzipSync(await fs.readFile(target));
|
||||
expect(xmlTexts(strFromU8(parts["xl/sharedStrings.xml"]))).toEqual([
|
||||
'A & B <Müller> "😀"', 'Anna A & B <Müller> "😀" xPERSON_01 ÄPERSON_01 UNKNOWN_99',
|
||||
]);
|
||||
expect(strFromU8(parts["xl/sharedStrings.xml"])).toContain("<b></b>");
|
||||
expect(parts["xl/media/image1.png"]).toEqual(Uint8Array.from([0, 42, 255]));
|
||||
expect(strFromU8(parts["xl/workbook.xml"])).toContain('name="A & B <Müller> "😀""');
|
||||
expect(result.replacements).toBe(4);
|
||||
expect(await fs.readFile(source)).toEqual(before);
|
||||
expect((await fs.stat(target)).mode & 0o777).toBe(0o600);
|
||||
});
|
||||
|
||||
it("restores inline strings, formulas, comments, links and UTF-16 XML without changing numbers", async () => {
|
||||
const xml = `<?xml version="1.0" encoding="UTF-16"?><worksheet xmlns="${S}"><sheetData><row><c r="A1" t="inlineStr"><is><t>PERSON_01</t></is></c><c r="B1"><f>"PERSON_01"</f><v>42</v></c></row></sheetData></worksheet>`;
|
||||
const { source, target } = await fixture({
|
||||
"xl/worksheets/sheet1.xml": Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(xml, "utf16le")]),
|
||||
"xl/comments/comment1.xml": strToU8(`<comments xmlns="${S}"><authors><author>PERSON_01</author></authors></comments>`),
|
||||
"xl/_rels/workbook.xml.rels": strToU8('<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="r1" Target="https://example.test/PERSON_01" TargetMode="External"/></Relationships>'),
|
||||
});
|
||||
await restoreXlsxFile(source, target, { PERSON_01: { original: "Anna Berger", type: "PERSON" } });
|
||||
const parts = unzipSync(await fs.readFile(target));
|
||||
expect(xmlTexts(strFromU8(parts["xl/worksheets/sheet1.xml"]))).toEqual(["Anna Berger", '"Anna Berger"', "42"]);
|
||||
expect(xmlTexts(strFromU8(parts["xl/comments/comment1.xml"]))).toEqual(["Anna Berger"]);
|
||||
expect(strFromU8(parts["xl/_rels/workbook.xml.rels"])).toContain('Target="https://example.test/Anna Berger"');
|
||||
});
|
||||
|
||||
it("supports compressed workbooks above the API's 20 MiB upload limit", async () => {
|
||||
const binary = randomBytes(21 * 1024 * 1024);
|
||||
const { source, target } = await fixture({
|
||||
"xl/media/opaque.bin": binary,
|
||||
"xl/sharedStrings.xml": strToU8(`<sst xmlns="${S}">` + '<si><t>PERSON_6001</t></si>'.repeat(170_000) + '</sst>'),
|
||||
});
|
||||
const mapping = Object.fromEntries(Array.from({ length: 6001 }, (_, i) => [`PERSON_${String(i + 1).padStart(2, "0")}`, { original: `Name ${i + 1}`, type: "PERSON" }]));
|
||||
const result = await restoreXlsxFile(source, target, mapping);
|
||||
expect((await fs.stat(source)).size).toBeGreaterThan(20 * 1024 * 1024);
|
||||
expect(result.replacements).toBe(170_001);
|
||||
const parts = unzipSync(await fs.readFile(target));
|
||||
expect(parts["xl/media/opaque.bin"]).toEqual(new Uint8Array(binary));
|
||||
const restored = strFromU8(parts["xl/sharedStrings.xml"]);
|
||||
expect(restored.match(/Name 6001/g)).toHaveLength(170_000);
|
||||
expect(restored).not.toContain("PERSON_6001");
|
||||
}, 60_000);
|
||||
|
||||
it("removes incomplete outputs on malformed XML, DTDs and damaged ZIP payloads", async () => {
|
||||
for (const xml of ['<bad>', '<!DOCTYPE sst [<!ENTITY x "test">]><sst>&x;</sst>']) {
|
||||
const { source, target } = await fixture({ "xl/sharedStrings.xml": strToU8(xml) });
|
||||
await expect(restoreXlsxFile(source, target, {})).rejects.toThrow();
|
||||
expect(await fs.stat(target).catch(() => undefined)).toBeUndefined();
|
||||
}
|
||||
const { source, target } = await fixture({ "xl/data.bin": strToU8("UNIQUE_PAYLOAD") });
|
||||
const data = await fs.readFile(source);
|
||||
data[data.indexOf("UNIQUE_PAYLOAD")] ^= 1;
|
||||
await fs.writeFile(source, data);
|
||||
await expect(restoreXlsxFile(source, target, {})).rejects.toThrow("CRC");
|
||||
expect(await fs.stat(target).catch(() => undefined)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("does not overwrite an existing target or accept a truncated archive", async () => {
|
||||
const { source, target } = await fixture();
|
||||
await fs.writeFile(target, "keep this file");
|
||||
await expect(restoreXlsxFile(source, target, {})).rejects.toThrow();
|
||||
expect(await fs.readFile(target, "utf8")).toBe("keep this file");
|
||||
await fs.rm(target);
|
||||
const data = await fs.readFile(source);
|
||||
await fs.writeFile(source, data.subarray(0, data.length - 30));
|
||||
await expect(restoreXlsxFile(source, target, {})).rejects.toThrow("ZIP");
|
||||
expect(await fs.stat(target).catch(() => undefined)).toBeUndefined();
|
||||
});
|
||||
|
||||
|
||||
it("restores split placeholders in DrawingML text boxes and keeps run formatting", async () => {
|
||||
const { source, target } = await fixture({
|
||||
"xl/drawings/drawing1.xml": strToU8('<a:shape xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:p><a:r><a:rPr b="1"/><a:t>PER</a:t></a:r><a:r><a:t>SON_01</a:t></a:r></a:p></a:shape>'),
|
||||
});
|
||||
await restoreXlsxFile(source, target, { PERSON_01: { original: "Anna Berger", type: "PERSON" } });
|
||||
const drawing = strFromU8(unzipSync(await fs.readFile(target))["xl/drawings/drawing1.xml"]);
|
||||
expect(xmlTexts(drawing)).toEqual(["Anna Berger"]);
|
||||
expect(drawing).toContain('b="1"');
|
||||
});
|
||||
Reference in New Issue
Block a user