/** * @license * Copyright 2026 aphrody-code * SPDX-License-Identifier: Apache-2.0 */ import { Database } from "bun:sqlite"; import { getBxcDir } from "../../utils/paths.ts"; export class TranslationCache { private db: Database; private dbPath: string; private getStmt: any; private setStmt: any; constructor(customPath?: string) { this.dbPath = customPath || `${getBxcDir()}/translations.sqlite`; this.db = new Database(this.dbPath); this.db.run("PRAGMA journal_mode = WAL;"); this.db.run("PRAGMA synchronous = NORMAL;"); this.db.run(` CREATE TABLE IF NOT EXISTS translations ( id INTEGER PRIMARY KEY AUTOINCREMENT, hash TEXT UNIQUE, source_text TEXT, translated_text TEXT, source_lang TEXT, target_lang TEXT, format TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ) `); this.db.run("CREATE INDEX IF NOT EXISTS idx_trans_hash ON translations(hash);"); this.getStmt = this.db.prepare( "SELECT translated_text, source_lang FROM translations WHERE hash = ?" ); this.setStmt = this.db.prepare( "INSERT OR REPLACE INTO translations (hash, source_text, translated_text, source_lang, target_lang, format) VALUES (?, ?, ?, ?, ?, ?)" ); } private hashKey(text: string, target: string, source?: string, format: string = "text"): string { const hasher = new Bun.CryptoHasher("sha256"); hasher.update(`${source || "auto"}::${target}::${format}::${text}`); return hasher.digest("hex"); } get(text: string, target: string, source?: string, format: string = "text"): { translatedText: string; detectedSourceLanguage?: string } | null { try { const key = this.hashKey(text, target, source, format); const row = this.getStmt.get(key) as { translated_text: string; source_lang: string } | undefined; if (row) { return { translatedText: row.translated_text, detectedSourceLanguage: row.source_lang, }; } } catch {} return null; } set(text: string, translatedText: string, target: string, source?: string, format: string = "text"): void { try { const key = this.hashKey(text, target, source, format); this.setStmt.run(key, text, translatedText, source || "auto", target, format); } catch {} } getStats(): { totalEntries: number; dbPath: string } { try { const row = this.db.query("SELECT COUNT(*) as count FROM translations").get() as { count: number }; return { totalEntries: row.count, dbPath: this.dbPath, }; } catch { return { totalEntries: 0, dbPath: this.dbPath }; } } clear(): void { try { this.db.run("DELETE FROM translations"); } catch {} } } export const defaultTranslationCache = new TranslationCache();