forked from r.muellner/velum-raycast
Show exact matches in red and add categorized custom terms to hit review. Move session administration into the translation tables command.
780 lines
35 KiB
TypeScript
780 lines
35 KiB
TypeScript
import { hashProjectFile, inspectTextFile } from "./project-text-stream";
|
|
import { createHash, randomUUID } from "node:crypto";
|
|
import { constants as fsConstants, promises as fs } from "node:fs";
|
|
import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
|
|
import { environment } from "@raycast/api";
|
|
import type { CustomTerm, EntityType, MappingEntry, PlaceholderMapping } from "../types";
|
|
import { whitelistKey } from "./project-whitelist";
|
|
import type { DocumentImageReport, ImagePolicy } from "./image-policy";
|
|
import type { ProjectWhitelistEntry } from "./project-whitelist";
|
|
import { restoreOriginalCase } from "./restore-case";
|
|
import { mappingForRestoration } from "./mapping-groups";
|
|
|
|
export { whitelistKey } from "./project-whitelist";
|
|
export type { ProjectWhitelistEntry } from "./project-whitelist";
|
|
|
|
export type ProjectRule = CustomTerm;
|
|
export type ProjectFile = { relPath: string; absPath: string; kind: "text" | "document"; size: number };
|
|
export type SkippedProjectFile = { path: string; reason: string };
|
|
export type RunFile = { source: string; output: string; kind: ProjectFile["kind"]; imageReport?: DocumentImageReport; localDocx?: true };
|
|
export type ProjectRun = {
|
|
version: 2;
|
|
origin?: "direct" | "imported";
|
|
id: string;
|
|
projectPath: string;
|
|
projectName: string;
|
|
createdAt: string;
|
|
mapping: PlaceholderMapping;
|
|
/** Categories actually used to analyze the files in this snapshot. */
|
|
entityTypes?: EntityType[];
|
|
customTermCoverage?: string;
|
|
/** Explicit image handling applied to documents in this snapshot. Unknown means reprocess. */
|
|
imagePolicy?: ImagePolicy;
|
|
/** Hash of each live project file and its immutable output in this run. */
|
|
sourceState?: Record<string, { hash: string; output: string }>;
|
|
/** Generic replacement mode for placeholders embedded in code identifiers. */
|
|
matchModes?: Record<string, "token" | "anywhere">;
|
|
files: RunFile[];
|
|
inPlace?: boolean;
|
|
/** The project source already contains outputs of an earlier in-place run. */
|
|
sourceInPlace?: boolean;
|
|
/** Previous immutable snapshot when a project run was revised after creation. */
|
|
revisedFrom?: string;
|
|
/** Word comment authors were reviewed with the explicit author recognizer. */
|
|
commentAuthorCoverage?: boolean;
|
|
/** Word tracked-change authors and deleted text were reviewed. */
|
|
reviewAuthorCoverage?: boolean;
|
|
/** Visible copy next to the source project; immutable snapshots remain in Raycast support. */
|
|
copyPath?: string;
|
|
};
|
|
|
|
const DOCUMENTS = new Set([".docx", ".xlsx", ".pptx", ".pdf"]);
|
|
const RESTORABLE_DOCUMENTS = new Set([".docx", ".xlsx", ".pptx"]);
|
|
const MARKDOWN_EXTENSIONS = new Set([".md", ".markdown", ".mdx"]);
|
|
const SECRET_EXTENSIONS = new Set([".pem", ".key", ".p12", ".pfx"]);
|
|
const EXCLUDES = new Set([".git", "node_modules", "dist", "build", "out", ".next", ".nuxt",
|
|
".venv", "venv", "__pycache__", "target", "vendor", "coverage", ".cache", ".turbo",
|
|
".idea", ".vscode", "Pods", "DerivedData"]);
|
|
|
|
export function canonicalProjectPath(path: string): string {
|
|
return resolve(path);
|
|
}
|
|
|
|
function projectIdFor(path: string): string {
|
|
return createHash("sha1").update(canonicalProjectPath(path)).digest("hex").slice(0, 16);
|
|
}
|
|
|
|
async function isBinary(path: string): Promise<boolean> {
|
|
const file = await fs.open(path, "r");
|
|
try {
|
|
const buffer = Buffer.alloc(8192);
|
|
const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
|
|
return buffer.subarray(0, bytesRead).includes(0);
|
|
} finally { await file.close(); }
|
|
}
|
|
|
|
async function isOfficeArchive(path: string): Promise<boolean> {
|
|
const file = await fs.open(path, "r");
|
|
try {
|
|
const header = Buffer.alloc(4);
|
|
const { bytesRead } = await file.read(header, 0, header.length, 0);
|
|
return bytesRead === 4 && header.equals(Buffer.from([0x50, 0x4b, 0x03, 0x04]));
|
|
} finally { await file.close(); }
|
|
}
|
|
|
|
export function projectDataRoot(projectPath: string, support = environment.supportPath): string {
|
|
return join(support, "velum-projects", projectIdFor(projectPath));
|
|
}
|
|
|
|
export function rulesPath(projectPath: string, support = environment.supportPath): string {
|
|
return join(projectDataRoot(projectPath, support), "rules.json");
|
|
}
|
|
|
|
export function whitelistPath(projectPath: string, support = environment.supportPath): string {
|
|
return join(projectDataRoot(projectPath, support), "whitelist.json");
|
|
}
|
|
|
|
export function entityTypesPath(projectPath: string, support = environment.supportPath): string {
|
|
return join(projectDataRoot(projectPath, support), "entity-types.json");
|
|
}
|
|
|
|
export function fileExclusionsPath(projectPath: string, support = environment.supportPath): string {
|
|
return join(projectDataRoot(projectPath, support), "excluded-files.json");
|
|
}
|
|
|
|
function checkedFileExclusions(value: unknown): string[] {
|
|
if (!Array.isArray(value) || value.some((path) => typeof path !== "string")) {
|
|
throw new Error("Ungültige Dateiauswahl für dieses Projekt.");
|
|
}
|
|
try { return [...new Set(value.map((path: string) => safeRelativePath(path)))]; }
|
|
catch { throw new Error("Ungültiger Dateipfad in der Projektauswahl."); }
|
|
}
|
|
|
|
export async function loadProjectFileExclusions(projectPath: string, support?: string): Promise<string[]> {
|
|
try {
|
|
return checkedFileExclusions(JSON.parse(await fs.readFile(fileExclusionsPath(projectPath, support), "utf8")));
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function saveProjectFileExclusions(projectPath: string, paths: string[], support?: string): Promise<void> {
|
|
const unique = checkedFileExclusions(paths);
|
|
const path = fileExclusionsPath(projectPath, support);
|
|
await fs.mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
const temp = `${path}.${randomUUID()}.tmp`;
|
|
try {
|
|
await fs.writeFile(temp, JSON.stringify(unique), { encoding: "utf8", mode: 0o600 });
|
|
await fs.rename(temp, path);
|
|
} catch (error) {
|
|
await fs.rm(temp, { force: true });
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export function withoutExcludedProjectFiles(files: ProjectFile[], excluded: readonly string[]): ProjectFile[] {
|
|
const paths = new Set(excluded);
|
|
return files.filter((file) => !paths.has(file.relPath));
|
|
}
|
|
|
|
export async function loadProjectEntityTypes(projectPath: string, support?: string): Promise<EntityType[] | null> {
|
|
try {
|
|
const value = JSON.parse(await fs.readFile(entityTypesPath(projectPath, support), "utf8")) as unknown;
|
|
if (!Array.isArray(value) || value.some((type) => typeof type !== "string" || !type)) {
|
|
throw new Error("Ungültige Kategorienauswahl für dieses Projekt.");
|
|
}
|
|
return [...new Set(value)];
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function saveProjectEntityTypes(projectPath: string, types: EntityType[], support?: string): Promise<void> {
|
|
const path = entityTypesPath(projectPath, support);
|
|
await fs.mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
const temp = `${path}.${randomUUID()}.tmp`;
|
|
try {
|
|
await fs.writeFile(temp, JSON.stringify([...new Set(types)]), { encoding: "utf8", mode: 0o600 });
|
|
await fs.rename(temp, path);
|
|
} catch (error) {
|
|
await fs.rm(temp, { force: true });
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function loadProjectWhitelist(projectPath: string, support?: string): Promise<ProjectWhitelistEntry[]> {
|
|
try {
|
|
const value = JSON.parse(await fs.readFile(whitelistPath(projectPath, support), "utf8")) as unknown;
|
|
if (!Array.isArray(value)) throw new Error("Ungültige Projekt-Whitelist.");
|
|
return value.filter((entry): entry is ProjectWhitelistEntry => Boolean(entry) && typeof entry === "object"
|
|
&& typeof entry.type === "string" && typeof entry.original === "string"
|
|
&& entry.type.length > 0 && entry.original.trim().length > 0);
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function saveProjectWhitelist(projectPath: string, entries: ProjectWhitelistEntry[], support?: string): Promise<void> {
|
|
const unique = [...new Map(entries.map((entry) => [whitelistKey(entry),
|
|
{ type: entry.type.toUpperCase(), original: entry.original.trim() }])).values()];
|
|
const path = whitelistPath(projectPath, support);
|
|
await fs.mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
const temp = `${path}.${randomUUID()}.tmp`;
|
|
try {
|
|
await fs.writeFile(temp, JSON.stringify(unique), { encoding: "utf8", mode: 0o600 });
|
|
await fs.rename(temp, path);
|
|
} catch (error) {
|
|
await fs.rm(temp, { force: true });
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function loadProjectRules(projectPath: string, support?: string): Promise<ProjectRule[]> {
|
|
try {
|
|
const value = JSON.parse(await fs.readFile(rulesPath(projectPath, support), "utf8")) as unknown;
|
|
return Array.isArray(value) ? value.filter(isProjectRule) : [];
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
function isProjectRule(value: unknown): value is ProjectRule {
|
|
if (!value || typeof value !== "object") return false;
|
|
const rule = value as Record<string, unknown>;
|
|
return typeof rule.type === "string" && /^[A-Z][A-Z0-9_]*$/.test(rule.type)
|
|
&& typeof rule.value === "string" && rule.value.trim().length >= 2;
|
|
}
|
|
|
|
export function parseProjectRules(input: string,
|
|
entityTypes: readonly string[] = ["BEGRIFF", "PERSON", "ORG", "ORT", "FIRMA", "KUNDE"]): ProjectRule[] {
|
|
const allowed = new Set(entityTypes);
|
|
const rules = input.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).map((line) => {
|
|
const match = /^([A-Z][A-Z0-9_]*):\s*(.+)$/i.exec(line);
|
|
const type = match?.[1].toUpperCase();
|
|
return match && type && allowed.has(type)
|
|
? { type, value: match[2].trim() }
|
|
: { type: "BEGRIFF" as const, value: line };
|
|
});
|
|
if (rules.length > 500 || rules.some((rule) => !validCustomTerm(rule.value))) {
|
|
throw new Error("Maximal 500 Begriffe mit jeweils 2 bis 200 Zeichen sind erlaubt.");
|
|
}
|
|
return rules.filter((rule, index) => rules.findIndex(
|
|
(other) => other.type === rule.type && other.value.toLocaleLowerCase() === rule.value.toLocaleLowerCase(),
|
|
) === index);
|
|
}
|
|
|
|
export function validCustomTerm(value: string): boolean {
|
|
const length = Array.from(value.trim()).length;
|
|
return length >= 2 && length <= 200;
|
|
}
|
|
|
|
export async function saveProjectRules(projectPath: string, rules: ProjectRule[], support?: string): Promise<void> {
|
|
const path = rulesPath(projectPath, support);
|
|
await fs.mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
const temp = `${path}.${randomUUID()}.tmp`;
|
|
try {
|
|
await fs.writeFile(temp, JSON.stringify(rules), { encoding: "utf8", mode: 0o600 });
|
|
await fs.rename(temp, path);
|
|
} finally {
|
|
await fs.rm(temp, { force: true });
|
|
}
|
|
}
|
|
|
|
export function forceMasks(rules: ProjectRule[]): Record<string, string[]> {
|
|
const result: Record<string, string[]> = {};
|
|
for (const rule of rules) (result[rule.type] ??= []).push(rule.value);
|
|
return result;
|
|
}
|
|
|
|
export async function scanProjectFiles(root: string, maxSize?: number,
|
|
validateText = true, documentLimits: Readonly<Record<string, number>> = {}): Promise<{
|
|
files: ProjectFile[]; skipped: SkippedProjectFile[];
|
|
}> {
|
|
const files: ProjectFile[] = [];
|
|
const skipped: SkippedProjectFile[] = [];
|
|
const skip = (path: string, reason: string) => skipped.push({ path, reason });
|
|
async function walk(directory: string): Promise<void> {
|
|
for (const entry of await fs.readdir(directory, { withFileTypes: true })) {
|
|
const path = join(directory, entry.name);
|
|
const relPath = relative(root, path).split(sep).join("/");
|
|
if (entry.isSymbolicLink()) { skip(relPath, "Symbolischer Link"); continue; }
|
|
if (entry.isDirectory()) {
|
|
if (EXCLUDES.has(entry.name)) { skip(relPath, "Ausgeschlossener Ordner"); continue; }
|
|
await walk(path);
|
|
continue;
|
|
}
|
|
if (!entry.isFile()) continue;
|
|
if (entry.name.startsWith("~$") || entry.name.startsWith("._")) {
|
|
skip(relPath, "Temporäre Office-/macOS-Datei");
|
|
continue;
|
|
}
|
|
if (entry.name === ".env" || entry.name.startsWith(".env.") || SECRET_EXTENSIONS.has(extname(entry.name).toLowerCase())) {
|
|
skip(relPath, "Vertraulicher Dateityp");
|
|
continue;
|
|
}
|
|
const stat = await fs.stat(path);
|
|
const kind = DOCUMENTS.has(extname(path).toLowerCase()) ? "document" : "text";
|
|
const limit = maxSize ?? (kind === "document"
|
|
? documentLimits[extname(path).toLowerCase()] ?? 20 * 1024 * 1024 : Number.POSITIVE_INFINITY);
|
|
if (stat.size > limit) { skip(relPath, `Datei zu groß (Grenze: ${limit / 1024 / 1024} MiB)`); continue; }
|
|
if (kind === "document" && extname(path).toLowerCase() !== ".pdf" && !(await isOfficeArchive(path))) {
|
|
skip(relPath, "Kein lesbares Office-ZIP-Archiv (beschädigt, verschlüsselt oder falsche Endung)");
|
|
continue;
|
|
}
|
|
if (kind === "text" && validateText) {
|
|
if (await isBinary(path)) { skip(relPath, "Binärdatei"); continue; }
|
|
try { await inspectTextFile(path); }
|
|
catch { skip(relPath, "Keine gültige UTF-8-Textdatei"); continue; }
|
|
}
|
|
files.push({ relPath, absPath: path, kind, size: stat.size });
|
|
}
|
|
}
|
|
await walk(root);
|
|
files.sort((a, b) => a.relPath.localeCompare(b.relPath));
|
|
return { files, skipped };
|
|
}
|
|
|
|
export function digest(data: Buffer): string {
|
|
return createHash("sha256").update(data).digest("hex");
|
|
}
|
|
|
|
/** Python API spans count Unicode code points; JavaScript strings use UTF-16 offsets. */
|
|
export function toUtf16Offsets<T extends { start: number; end: number }>(text: string, spans: T[]): T[] {
|
|
const positions = [0];
|
|
let offset = 0;
|
|
for (const character of text) {
|
|
offset += character.length;
|
|
positions.push(offset);
|
|
}
|
|
return spans.map((span) => {
|
|
if (!Number.isInteger(span.start) || !Number.isInteger(span.end)
|
|
|| span.start < 0 || span.end > positions.length - 1 || span.start >= span.end) {
|
|
throw new Error("Ungültige Trefferposition der Velum-API.");
|
|
}
|
|
return { ...span, start: positions[span.start], end: positions[span.end] };
|
|
});
|
|
}
|
|
|
|
export function replaceSpans(
|
|
source: string,
|
|
spans: Array<{ start: number; end: number; placeholder: string; id: string }>,
|
|
accepted: Set<string>,
|
|
): string {
|
|
let output = source;
|
|
for (const span of [...spans].filter((item) => accepted.has(item.id)).sort((a, b) => b.start - a.start)) {
|
|
if (span.start < 0 || span.end > source.length || span.start >= span.end) throw new Error("Ungültige Trefferposition.");
|
|
output = output.slice(0, span.start) + span.placeholder + output.slice(span.end);
|
|
}
|
|
return output;
|
|
}
|
|
|
|
function restorePattern(mapping: PlaceholderMapping, matchModes: ProjectRun["matchModes"], allowEmbedded = false): {
|
|
pattern: RegExp; originalFor: (match: string) => string | undefined;
|
|
} | undefined {
|
|
const keys = Object.keys(mapping).sort((a, b) => b.length - a.length);
|
|
if (!keys.length) return undefined;
|
|
const foldedKeys = new Map<string, string | null>();
|
|
for (const key of keys) {
|
|
const folded = key.toUpperCase();
|
|
if (foldedKeys.has(folded)) foldedKeys.set(folded, null);
|
|
else foldedKeys.set(folded, key);
|
|
}
|
|
const parts = keys.map((key) => {
|
|
const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
return allowEmbedded || matchModes?.[key] === "anywhere"
|
|
? `${escaped}(?!\\d)` : `(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`;
|
|
});
|
|
return {
|
|
pattern: new RegExp(parts.join("|"), "giu"),
|
|
originalFor: (match) => {
|
|
const key = Object.prototype.hasOwnProperty.call(mapping, match)
|
|
? match : foldedKeys.get(match.toUpperCase());
|
|
return key ? restoreOriginalCase(match, key, mapping[key].original) : undefined;
|
|
},
|
|
};
|
|
}
|
|
|
|
export function restoreTextWithCount(source: string, mapping: PlaceholderMapping,
|
|
matchModes?: ProjectRun["matchModes"], allowEmbedded = false): { text: string; replacements: number } {
|
|
const pattern = restorePattern(mapping, matchModes, allowEmbedded);
|
|
let replacements = 0;
|
|
const text = pattern ? source.replace(pattern.pattern, (match) => {
|
|
const original = pattern.originalFor(match);
|
|
if (original === undefined) return match;
|
|
replacements++;
|
|
return original;
|
|
}) : source;
|
|
return { text, replacements };
|
|
}
|
|
|
|
export function restoreText(source: string, mapping: PlaceholderMapping,
|
|
matchModes?: ProjectRun["matchModes"], allowEmbedded = false): string {
|
|
return restoreTextWithCount(source, mapping, matchModes, allowEmbedded).text;
|
|
}
|
|
|
|
/** Older snapshots can supply a missing key only when its meaning never changed. */
|
|
export function withUnambiguousHistoricalMappings(current: PlaceholderMapping,
|
|
earlier: PlaceholderMapping[]): PlaceholderMapping {
|
|
const result = { ...current };
|
|
const candidates = new Map<string, PlaceholderMapping[string] | null>();
|
|
for (const mapping of earlier) {
|
|
for (const [key, entry] of Object.entries(mapping)) {
|
|
if (Object.prototype.hasOwnProperty.call(current, key)) continue;
|
|
const previous = candidates.get(key);
|
|
if (previous === null) continue;
|
|
if (previous && (previous.original !== entry.original || previous.type !== entry.type)) {
|
|
candidates.set(key, null);
|
|
} else if (!previous) candidates.set(key, entry);
|
|
}
|
|
}
|
|
for (const [key, entry] of candidates) if (entry) result[key] = entry;
|
|
return result;
|
|
}
|
|
|
|
/** Report recognizable Velum IDs that remain after a Markdown restore. */
|
|
export function unresolvedPlaceholderIds(source: string, mappings: PlaceholderMapping[]): string[] {
|
|
const prefixes = new Set(mappings.flatMap((mapping) => Object.keys(mapping)
|
|
.map((key) => /^([\p{L}]+)_\d+$/u.exec(key)?.[1]).filter((value): value is string => Boolean(value))));
|
|
if (!prefixes.size) return [];
|
|
const alternatives = [...prefixes].sort((a, b) => b.length - a.length)
|
|
.map((prefix) => prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
|
|
const pattern = new RegExp(`(?<![\\p{L}\\p{N}])(?:${alternatives.join("|")})_\\d+(?!\\d)`, "giu");
|
|
return [...new Set(source.match(pattern) ?? [])];
|
|
}
|
|
|
|
export function restorePath(relPath: string, mapping: PlaceholderMapping, matchModes?: ProjectRun["matchModes"]): string {
|
|
// Filenames can join a placeholder directly to another identifier fragment.
|
|
// Restricting replacements to word boundaries would leave those names masked.
|
|
const pattern = restorePattern(mapping, matchModes, true);
|
|
const segments = safeRelativePath(relPath).split("/").map((segment) => {
|
|
const restored = pattern ? segment.replace(pattern.pattern, (match) => pattern.originalFor(match) ?? match) : segment;
|
|
if (restored.includes("/") || restored.includes("\\") || restored === "." || restored === "..") {
|
|
throw new Error("Rückübersetzter Dateiname enthält einen ungültigen Pfadteil.");
|
|
}
|
|
return restored;
|
|
});
|
|
return safeRelativePath(segments.join("/"));
|
|
}
|
|
|
|
export function safeRelativePath(path: string): string {
|
|
const normalized = path.split("\\").join("/");
|
|
if (!normalized || normalized.startsWith("/") || normalized.split("/").some((part) => part === ".." || part === "." || !part)) {
|
|
throw new Error("Ungültiger Ausgabepfad.");
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
export async function createRun(projectPath: string, support = environment.supportPath): Promise<{
|
|
run: ProjectRun; directory: string;
|
|
}> {
|
|
projectPath = canonicalProjectPath(projectPath);
|
|
const id = `${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID().slice(0, 8)}`;
|
|
const directory = join(projectDataRoot(projectPath, support), "runs", id);
|
|
await fs.mkdir(join(directory, "files"), { recursive: true, mode: 0o700 });
|
|
return {
|
|
directory,
|
|
run: { version: 2, origin: "direct", id, projectPath, projectName: basename(projectPath),
|
|
createdAt: new Date().toISOString(), mapping: {}, files: [] },
|
|
};
|
|
}
|
|
|
|
export async function saveRun(directory: string, run: ProjectRun): Promise<void> {
|
|
const dest = join(directory, "run.json");
|
|
const tmp = `${dest}.tmp`;
|
|
await fs.writeFile(tmp, JSON.stringify(run), { encoding: "utf8", mode: 0o600 });
|
|
await fs.rename(tmp, dest);
|
|
}
|
|
|
|
export function prepareManualMappingEntry(current: PlaceholderMapping, earlier: PlaceholderMapping[],
|
|
input: { original: string; type: string; placeholder?: string }): { placeholder: string; entry: MappingEntry } {
|
|
const original = input.original.trim();
|
|
const type = input.type.trim().toUpperCase();
|
|
if (!original) throw new Error("Bitte einen Klartext-Begriff eingeben.");
|
|
if (!/^[A-ZÄÖÜ][A-ZÄÖÜ0-9_]*$/u.test(type)) throw new Error("Ungültige Kategorie.");
|
|
if (Object.values(current).some((entry) => entry.type === type
|
|
&& entry.original.toLocaleLowerCase("de") === original.toLocaleLowerCase("de"))) {
|
|
throw new Error("Dieser Begriff ist in der Kategorie bereits vorhanden.");
|
|
}
|
|
const known = [current, ...earlier];
|
|
const keys = known.flatMap((mapping) => Object.keys(mapping));
|
|
const placeholderPattern = new RegExp(`^${type}_(\\d+)$`, "u");
|
|
const placeholder = input.placeholder?.trim().toUpperCase() || (() => {
|
|
const max = keys.reduce((currentMax, key) => Math.max(currentMax,
|
|
Number(placeholderPattern.exec(key)?.[1] ?? 0)), 0);
|
|
return `${type}_${String(max + 1).padStart(2, "0")}`;
|
|
})();
|
|
if (!placeholderPattern.test(placeholder)) {
|
|
throw new Error("Platzhalter muss zur Kategorie passen, z. B. PERSON_61.");
|
|
}
|
|
if (Object.keys(current).some((key) => key.toUpperCase() === placeholder)) {
|
|
throw new Error("Dieser Platzhalter ist im aktuellen Stand bereits belegt.");
|
|
}
|
|
for (const mapping of earlier) for (const [key, entry] of Object.entries(mapping)) {
|
|
if (key.toUpperCase() === placeholder && (entry.type !== type || entry.original !== original)) {
|
|
throw new Error("Dieser Platzhalter hatte früher eine andere Bedeutung. Bitte die betroffene Datei einzeln zuordnen.");
|
|
}
|
|
}
|
|
return { placeholder, entry: { original, type } };
|
|
}
|
|
|
|
/** Save a mapping correction as a new immutable project stand without rewriting project files. */
|
|
export async function updateProjectMapping(projectPath: string,
|
|
change: (current: PlaceholderMapping, earlier: PlaceholderMapping[]) => PlaceholderMapping,
|
|
support = environment.supportPath): Promise<ProjectRun> {
|
|
const entries = await listRuns(projectPath, support);
|
|
const latest = entries[0];
|
|
if (!latest) throw new Error("Für dieses Projekt gibt es noch keinen gespeicherten Stand.");
|
|
const mapping = change(latest.run.mapping, entries.slice(1).map((saved) => saved.run.mapping));
|
|
const created = await createRun(projectPath, support);
|
|
const { run, directory } = created;
|
|
run.createdAt = new Date(Math.max(Date.now(), Date.parse(latest.run.createdAt) + 1)).toISOString();
|
|
run.origin = latest.run.origin;
|
|
run.revisedFrom = latest.run.id;
|
|
run.mapping = mapping;
|
|
run.entityTypes = latest.run.entityTypes ? [...latest.run.entityTypes] : undefined;
|
|
run.customTermCoverage = latest.run.customTermCoverage;
|
|
run.matchModes = { ...latest.run.matchModes };
|
|
run.files = latest.run.files.map((file) => ({ ...file }));
|
|
run.sourceState = latest.run.sourceState ? { ...latest.run.sourceState } : undefined;
|
|
run.inPlace = latest.run.inPlace;
|
|
run.sourceInPlace = latest.run.sourceInPlace;
|
|
run.commentAuthorCoverage = latest.run.commentAuthorCoverage;
|
|
run.reviewAuthorCoverage = latest.run.reviewAuthorCoverage;
|
|
run.copyPath = latest.run.copyPath;
|
|
try {
|
|
for (const file of run.files) {
|
|
const source = resolveWithin(join(latest.directory, "files"), file.output);
|
|
const target = resolveWithin(join(directory, "files"), file.output);
|
|
await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
|
await fs.copyFile(source, target, fsConstants.COPYFILE_EXCL | fsConstants.COPYFILE_FICLONE);
|
|
await fs.chmod(target, 0o600);
|
|
}
|
|
if ((await listRuns(projectPath, support))[0]?.run.id !== latest.run.id) {
|
|
throw new Error("Es gibt bereits einen neueren Projektstand. Bitte die Liste aktualisieren.");
|
|
}
|
|
await saveRun(directory, run);
|
|
} catch (error) {
|
|
await fs.rm(directory, { recursive: true, force: true });
|
|
throw error;
|
|
}
|
|
return run;
|
|
}
|
|
|
|
export async function addProjectMappingEntry(projectPath: string,
|
|
input: { original: string; type: string; placeholder?: string }, support = environment.supportPath): Promise<ProjectRun> {
|
|
return updateProjectMapping(projectPath, (current, earlier) => {
|
|
const { placeholder, entry } = prepareManualMappingEntry(current, earlier, input);
|
|
return { ...current, [placeholder]: entry };
|
|
}, support);
|
|
}
|
|
|
|
export function runCopiesPath(run: ProjectRun, directory: string): string {
|
|
return run.copyPath ?? join(directory, "files");
|
|
}
|
|
|
|
export async function scanRestorableCopyFiles(run: ProjectRun, directory: string, current = true): Promise<{
|
|
root: string; files: ProjectFile[]; skipped: number;
|
|
}> {
|
|
const inPlace = Boolean(run.inPlace || run.sourceInPlace);
|
|
let root = current && inPlace ? canonicalProjectPath(run.projectPath)
|
|
: current ? runCopiesPath(run, directory) : join(directory, "files");
|
|
if (current && !inPlace && run.copyPath) {
|
|
try {
|
|
if (!(await fs.lstat(root)).isDirectory()) throw new Error("Kopienpfad ist kein regulärer Ordner.");
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
root = join(directory, "files");
|
|
}
|
|
}
|
|
// XLSX restoration runs locally as a stream and does not upload the file.
|
|
const scan = await scanProjectFiles(root, undefined, true, { ".xlsx": Number.POSITIVE_INFINITY });
|
|
const files = scan.files.filter((file) => file.kind === "text" || isRestorableDocument(file.relPath));
|
|
return { root, files, skipped: scan.skipped.length + scan.files.length - files.length };
|
|
}
|
|
|
|
/** Publish only output files next to the project, without the private mapping. */
|
|
export async function publishProjectCopies(run: ProjectRun, directory: string): Promise<string> {
|
|
const projectPath = canonicalProjectPath(run.projectPath);
|
|
const parent = dirname(projectPath);
|
|
const target = join(parent, `${basename(projectPath)}-Velum-${run.id}`);
|
|
try {
|
|
await fs.lstat(target);
|
|
throw new Error(`Kopienordner bereits vorhanden: ${target}`);
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
}
|
|
const staging = await fs.mkdtemp(join(parent, `.${basename(projectPath)}-Velum-`));
|
|
try {
|
|
for (const file of run.files) {
|
|
const source = resolveWithin(join(directory, "files"), file.output);
|
|
if (!(await fs.lstat(source)).isFile()) throw new Error(`Keine reguläre Ausgabedatei: ${file.output}`);
|
|
const destination = resolveWithin(staging, file.output);
|
|
await fs.mkdir(dirname(destination), { recursive: true, mode: 0o700 });
|
|
await fs.copyFile(source, destination, fsConstants.COPYFILE_EXCL);
|
|
await fs.chmod(destination, 0o600);
|
|
}
|
|
await fs.rename(staging, target);
|
|
return target;
|
|
} catch (error) {
|
|
await fs.rm(staging, { recursive: true, force: true });
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function listRuns(projectPath: string, support = environment.supportPath): Promise<Array<{
|
|
run: ProjectRun; directory: string;
|
|
}>> {
|
|
const root = join(projectDataRoot(projectPath, support), "runs");
|
|
let entries;
|
|
try { entries = await fs.readdir(root, { withFileTypes: true }); }
|
|
catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
|
|
throw error;
|
|
}
|
|
const runs = [];
|
|
for (const entry of entries) {
|
|
if (!entry.isDirectory()) continue;
|
|
const directory = join(root, entry.name);
|
|
try {
|
|
const run = JSON.parse(await fs.readFile(join(directory, "run.json"), "utf8")) as ProjectRun;
|
|
if (run.version === 2 && canonicalProjectPath(run.projectPath) === canonicalProjectPath(projectPath)) {
|
|
runs.push({ run, directory });
|
|
}
|
|
} catch { /* incomplete run: not offered for restoration */ }
|
|
}
|
|
return runs.sort((a, b) => b.run.createdAt.localeCompare(a.run.createdAt));
|
|
}
|
|
|
|
/** An unchanged output from an in-place run can be carried into the next snapshot. */
|
|
export async function matchesPreviousOutput(directory: string, relPath: string, currentHash: string): Promise<boolean> {
|
|
try {
|
|
return await hashProjectFile(resolveWithin(join(directory, "files"), relPath)) === currentHash;
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/** Reuse only an output proven to correspond to the current source bytes. */
|
|
export async function reusableProjectOutput(run: ProjectRun, directory: string,
|
|
relPath: string, currentHash: string): Promise<string | undefined> {
|
|
const state = run.sourceState?.[relPath];
|
|
if (state) {
|
|
if (state.hash !== currentHash || !run.files.some((file) => file.output === state.output)) return undefined;
|
|
try {
|
|
const output = resolveWithin(join(directory, "files"), state.output);
|
|
return (await fs.lstat(output)).isFile() ? state.output : undefined;
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
|
throw error;
|
|
}
|
|
}
|
|
// Older in-place snapshots lack source hashes. An identical saved output is
|
|
// still authoritative; copy-mode source bytes cannot be reconstructed.
|
|
if (!(run.inPlace || run.sourceInPlace) || !run.files.some((file) => file.output === relPath)) return undefined;
|
|
return await matchesPreviousOutput(directory, relPath, currentHash) ? relPath : undefined;
|
|
}
|
|
|
|
/** Unknown or changed category coverage requires a new review of unchanged files. */
|
|
export function sameEntityTypeCoverage(run: ProjectRun, selected: readonly EntityType[]): boolean {
|
|
if (!Array.isArray(run.entityTypes)) return false;
|
|
const covered = new Set(run.entityTypes);
|
|
return covered.size === new Set(selected).size && selected.every((type) => covered.has(type));
|
|
}
|
|
|
|
/** Only an identical saved file can disambiguate a placeholder reused across runs. */
|
|
export async function mappingForMatchingSnapshots(relPath: string, currentHash: string,
|
|
earlier: Array<{ run: ProjectRun; directory: string }>): Promise<PlaceholderMapping> {
|
|
const matching = await Promise.all(earlier.filter(({ run }) =>
|
|
run.files.some((file) => file.output === relPath))
|
|
.map(async ({ run, directory }) => await matchesPreviousOutput(directory, relPath, currentHash)
|
|
? mappingForRestoration(run.mapping) : undefined));
|
|
return withUnambiguousHistoricalMappings({},
|
|
matching.filter((mapping): mapping is PlaceholderMapping => Boolean(mapping)));
|
|
}
|
|
|
|
export async function listAllRuns(support = environment.supportPath): Promise<Array<{
|
|
run: ProjectRun; directory: string;
|
|
}>> {
|
|
const root = join(support, "velum-projects");
|
|
let projects;
|
|
try { projects = await fs.readdir(root, { withFileTypes: true }); }
|
|
catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
|
|
throw error;
|
|
}
|
|
const results = [];
|
|
for (const project of projects) {
|
|
if (!project.isDirectory()) continue;
|
|
const runsDir = join(root, project.name, "runs");
|
|
let entries;
|
|
try { entries = await fs.readdir(runsDir, { withFileTypes: true }); }
|
|
catch { continue; }
|
|
for (const entry of entries) {
|
|
if (!entry.isDirectory()) continue;
|
|
const directory = join(runsDir, entry.name);
|
|
try {
|
|
const run = JSON.parse(await fs.readFile(join(directory, "run.json"), "utf8")) as ProjectRun;
|
|
if (run.version === 2) results.push({ run, directory });
|
|
} catch { /* incomplete run */ }
|
|
}
|
|
}
|
|
return results.sort((a, b) => b.run.createdAt.localeCompare(a.run.createdAt));
|
|
}
|
|
|
|
export function isRestorableDocument(filename: string): boolean {
|
|
return RESTORABLE_DOCUMENTS.has(extname(filename).toLowerCase());
|
|
}
|
|
|
|
export function isMarkdownFile(filename: string): boolean {
|
|
return MARKDOWN_EXTENSIONS.has(extname(filename).toLowerCase());
|
|
}
|
|
|
|
export function resolveWithin(root: string, relPath: string): string {
|
|
const target = resolve(root, safeRelativePath(relPath));
|
|
if (!target.startsWith(resolve(root) + sep)) throw new Error("Ausgabepfad verlässt den Zielordner.");
|
|
return target;
|
|
}
|
|
|
|
async function assertNoSymlinkParents(root: string, relPath: string): Promise<void> {
|
|
const parts = safeRelativePath(relPath).split("/");
|
|
let parent = resolve(root);
|
|
for (const part of parts.slice(0, -1)) {
|
|
parent = join(parent, part);
|
|
try {
|
|
if ((await fs.lstat(parent)).isSymbolicLink()) throw new Error(`Symbolischer Link im Ausgabepfad: ${relPath}`);
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Replaces selected originals only after every output exists and a private backup is complete. */
|
|
export async function replaceProjectFilesInPlace(projectPath: string, runDirectory: string, files: RunFile[],
|
|
expectedHashes?: ReadonlyMap<string, string>): Promise<void> {
|
|
const root = resolve(projectPath);
|
|
const sourcePaths = new Set(files.map((file) => resolveWithin(root, file.source)));
|
|
const targetPaths = new Set<string>();
|
|
const sourceModes = new Map<string, number>();
|
|
for (const file of files) {
|
|
const source = resolveWithin(root, file.source);
|
|
const target = resolveWithin(root, file.output);
|
|
if (targetPaths.has(target)) throw new Error(`Doppelter Zielname: ${file.output}`);
|
|
targetPaths.add(target);
|
|
await assertNoSymlinkParents(root, file.output);
|
|
const sourceInfo = await fs.lstat(source);
|
|
if (!sourceInfo.isFile()) throw new Error(`Quelldatei ist keine reguläre Datei: ${file.source}`);
|
|
sourceModes.set(source, sourceInfo.mode & 0o777);
|
|
try {
|
|
await fs.lstat(target);
|
|
if (!sourcePaths.has(target)) throw new Error(`Zielname bereits vorhanden: ${file.output}`);
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
}
|
|
await fs.access(resolveWithin(join(runDirectory, "files"), file.output));
|
|
}
|
|
|
|
const backupRoot = join(runDirectory, "backup");
|
|
for (const file of files) {
|
|
const backup = resolveWithin(backupRoot, file.source);
|
|
await fs.mkdir(dirname(backup), { recursive: true, mode: 0o700 });
|
|
await fs.copyFile(resolveWithin(root, file.source), backup, fsConstants.COPYFILE_EXCL);
|
|
await fs.chmod(backup, 0o600);
|
|
}
|
|
|
|
const written: string[] = [];
|
|
try {
|
|
for (const file of files) {
|
|
const source = resolveWithin(root, file.source);
|
|
if (expectedHashes && await hashProjectFile(source) !== expectedHashes.get(file.source)) {
|
|
throw new Error(`Projektdatei wurde vor dem Ersetzen erneut geändert: ${file.source}`);
|
|
}
|
|
await fs.unlink(source);
|
|
}
|
|
for (const file of files) {
|
|
const target = resolveWithin(root, file.output);
|
|
await fs.mkdir(dirname(target), { recursive: true, mode: 0o700 });
|
|
await fs.copyFile(resolveWithin(join(runDirectory, "files"), file.output), target, fsConstants.COPYFILE_EXCL);
|
|
written.push(target);
|
|
await fs.chmod(target, sourceModes.get(resolveWithin(root, file.source)) ?? 0o600);
|
|
}
|
|
} catch (error) {
|
|
for (const target of written) await fs.rm(target, { force: true });
|
|
for (const file of files) {
|
|
const source = resolveWithin(root, file.source);
|
|
try { await fs.lstat(source); }
|
|
catch (missing) {
|
|
if ((missing as NodeJS.ErrnoException).code !== "ENOENT") throw missing;
|
|
await fs.mkdir(dirname(source), { recursive: true, mode: 0o700 });
|
|
await fs.copyFile(resolveWithin(backupRoot, file.source), source, fsConstants.COPYFILE_EXCL);
|
|
await fs.chmod(source, sourceModes.get(source) ?? 0o600);
|
|
}
|
|
}
|
|
throw new Error(`Ersetzen fehlgeschlagen; Originale wurden wiederhergestellt. Sicherung: ${backupRoot}. ${(error as Error).message}`);
|
|
}
|
|
}
|