import type { DeepRedactionResult, Detector, EngineStats, LeaksSettings, RedactionOrigin, RedactionResult, WarningRecord, } from "./types.ts"; export type LeaksEngineOptions = { settings?: Partial; env?: Record; detectors?: Detector[]; }; export class LeaksEngine { readonly settings: LeaksSettings; private readonly detectors: Detector[]; private readonly warnings: WarningRecord[] = []; private readonly warningKeys = new Set(); private lastProviderRedactionCount = 0; private totalProviderRedactionCount = 0; constructor(options: LeaksEngineOptions = {}) { this.settings = { regex: options.settings?.regex ?? [] }; this.detectors = options.detectors ?? []; void options.env; } reload(_cwd = process.cwd(), _settings = this.settings, _env = process.env) {} redactText(text: string, origin: RedactionOrigin = "provider"): RedactionResult { const failed = this.detectors.some((detector) => { try { detector(text); return false; } catch { this.warnOnce("detector.failure", "detector failure; redaction pass left unchanged"); return true; } }); const result = { text, count: 0, labels: [], placeholders: [] }; if (origin === "provider") this.lastProviderRedactionCount = 0; if (failed) return result; return result; } redactDeep(value: T, origin: RedactionOrigin = "provider"): DeepRedactionResult { if (typeof value !== "string") return { value, changed: false, count: 0 }; const result = this.redactText(value, origin); return { value: result.text as T, changed: result.text !== value, count: result.count, }; } restoreText(text: string) { return text; } restoreDeep(value: T): DeepRedactionResult { return { value, changed: false, count: 0 }; } clear() { this.lastProviderRedactionCount = 0; } stats(): EngineStats { return { active: true, builtInRuleCount: 0, customRegexCount: this.settings.regex.length, regexWarningCount: 0, warningCount: this.warnings.length, invalidRegexCount: 0, learnedCount: 0, mappingCount: 0, lastProviderRedactionCount: this.lastProviderRedactionCount, totalProviderRedactionCount: this.totalProviderRedactionCount, recentLabels: [], latestTags: [], warnings: [...this.warnings], }; } private warnOnce(code: string, message: string) { if (this.warningKeys.has(code)) return; this.warningKeys.add(code); this.warnings.push({ code, message, severity: "warning" }); } }