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 { PlaceholderMapping } from "../types"; import { whitelistKey } from "./project-whitelist"; import type { ProjectWhitelistEntry } from "./project-whitelist"; export { whitelistKey } from "./project-whitelist"; export type { ProjectWhitelistEntry } from "./project-whitelist"; export type ProjectRule = { type: "BEGRIFF" | "PERSON" | "ORG" | "ORT" | "FIRMA" | "KUNDE"; value: string }; export type ProjectFile = { relPath: string; absPath: string; kind: "text" | "document"; size: number }; export type RunFile = { source: string; output: string; kind: ProjectFile["kind"] }; export type ProjectRun = { version: 2; origin?: "direct" | "imported"; id: string; projectPath: string; projectName: string; createdAt: string; mapping: PlaceholderMapping; /** Generic replacement mode for placeholders embedded in code identifiers. */ matchModes?: Record; 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; }; const DOCUMENTS = new Set([".docx", ".xlsx", ".pptx", ".pdf"]); const RESTORABLE_DOCUMENTS = new Set([".docx", ".xlsx", ".pptx"]); 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"]); function projectIdFor(path: string): string { return createHash("sha1").update(path.replace(/\/+$/, "")).digest("hex").slice(0, 16); } async function isBinary(path: string): Promise { 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(); } } 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 async function loadProjectWhitelist(projectPath: string, support?: string): Promise { 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 { 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 { 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; return ["BEGRIFF", "PERSON", "ORG", "ORT", "FIRMA", "KUNDE"].includes(String(rule.type)) && typeof rule.value === "string" && rule.value.trim().length >= 2; } export function parseProjectRules(input: string): ProjectRule[] { const rules = input.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).map((line) => { const match = /^(BEGRIFF|PERSON|ORG|ORT|FIRMA|KUNDE):\s*(.+)$/i.exec(line); return match ? { type: match[1].toUpperCase() as ProjectRule["type"], value: match[2].trim() } : { type: "BEGRIFF" as const, value: line }; }); if (rules.length > 500 || rules.some((rule) => rule.value.length < 2 || rule.value.length > 200)) { 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 async function saveProjectRules(projectPath: string, rules: ProjectRule[], support?: string): Promise { const path = rulesPath(projectPath, support); await fs.mkdir(dirname(path), { recursive: true, mode: 0o700 }); await fs.writeFile(path, JSON.stringify(rules), { encoding: "utf8", mode: 0o600 }); } export function forceMasks(rules: ProjectRule[]): Record { const result: Record = {}; for (const rule of rules) (result[rule.type] ??= []).push(rule.value); return result; } export async function scanProjectFiles(root: string, maxSize = 20 * 1024 * 1024): Promise<{ files: ProjectFile[]; skipped: string[]; }> { const files: ProjectFile[] = []; const skipped: string[] = []; async function walk(directory: string): Promise { 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()) { skipped.push(relPath); continue; } if (entry.isDirectory()) { if (EXCLUDES.has(entry.name)) { skipped.push(relPath); continue; } await walk(path); continue; } if (!entry.isFile()) continue; if (entry.name === ".env" || entry.name.startsWith(".env.") || SECRET_EXTENSIONS.has(extname(entry.name).toLowerCase())) { skipped.push(relPath); continue; } const stat = await fs.stat(path); if (stat.size > maxSize) { skipped.push(relPath); continue; } const kind = DOCUMENTS.has(extname(path).toLowerCase()) ? "document" : "text"; if (kind === "text") { if (await isBinary(path)) { skipped.push(relPath); continue; } try { new TextDecoder("utf-8", { fatal: true }).decode(await fs.readFile(path)); } catch { skipped.push(relPath); 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(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 { 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"]): RegExp | undefined { const keys = Object.keys(mapping).sort((a, b) => b.length - a.length); if (!keys.length) return undefined; const parts = keys.map((key) => { const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); return matchModes?.[key] === "anywhere" ? escaped : `(? mapping[key].original) : source; } export function restorePath(relPath: string, mapping: PlaceholderMapping, matchModes?: ProjectRun["matchModes"]): string { const pattern = restorePattern(mapping, matchModes); const segments = safeRelativePath(relPath).split("/").map((segment) => { const restored = pattern ? segment.replace(pattern, (key) => mapping[key].original) : 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; }> { 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 { 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 async function listRuns(projectPath: string, support = environment.supportPath): Promise> { 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 && run.projectPath === 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 { try { const previous = await fs.readFile(resolveWithin(join(directory, "files"), relPath)); return digest(previous) === currentHash; } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; throw error; } } export async function listAllRuns(support = environment.supportPath): Promise> { 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 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 { 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[]): Promise { const root = resolve(projectPath); const sourcePaths = new Set(files.map((file) => resolveWithin(root, file.source))); const targetPaths = new Set(); const sourceModes = new Map(); 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) await fs.unlink(resolveWithin(root, file.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}`); } }