import { readdir } from "node:fs/promises" import { join } from "node:path" const DICTIONARIES_PATH = join(process.cwd(), "data", "dictionaries") export const sanitizeDictionaryName = (name: string) => { return name.replace(/[^a-zA-Z0-9_]/g, "_") } export const createDictionary = async (name: string, content: string): Promise => { const dictionaryName = sanitizeDictionaryName(name) const path = join(DICTIONARIES_PATH, `${dictionaryName}.txt`) const file = Bun.file(path) if (await file.exists()) { throw new Error(`Dictionary "${dictionaryName}" already exists`) } await file.write(content) return dictionaryName } export const readDictionary = async (name: string): Promise => { const path = join(DICTIONARIES_PATH, `${sanitizeDictionaryName(name)}.txt`) const file = Bun.file(path) if (!(await file.exists())) { throw new Error(`Dictionary "${name === "" || name === undefined ? "undefined" : name}" does not exist`) } return await file.text() } export const listDictionaries = async (): Promise => { const files = await readdir(DICTIONARIES_PATH, { recursive: true }) return files.map((file) => file.replace(".txt", "")) } export const updateDictionary = async (name: string, content: string): Promise => { const path = join(DICTIONARIES_PATH, `${sanitizeDictionaryName(name)}.txt`) const file = Bun.file(path) if (!(await file.exists())) { throw new Error(`Dictionary "${name}" does not exist`) } await file.write(content) } export const deleteDictionary = async (name: string): Promise => { const path = join(DICTIONARIES_PATH, `${sanitizeDictionaryName(name)}.txt`) const file = Bun.file(path) if (!(await file.exists())) { throw new Error(`Dictionary "${name}" does not exist`) } await file.delete() }