import { randomUUID } from 'node:crypto'; import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'; import { dirname } from 'node:path'; import { withFileLock } from "../storage.js"; const EMPTY = { version: 1, departments: [] }; async function atomicWrite(path, content) { await mkdir(dirname(path), { recursive: true }); const temporary = path + '.' + String(process.pid) + '.' + randomUUID() + '.tmp'; try { await writeFile(temporary, content, { encoding: 'utf8', mode: 0o600 }); await rename(temporary, path); } catch (error) { await rm(temporary, { force: true }).catch(() => { }); throw error; } } /** JSON registry for one global or project department collection. */ export class DepartmentRegistry { path; constructor(path) { this.path = path; } async read() { let text; try { text = await readFile(this.path, 'utf8'); } catch (error) { if (error.code === 'ENOENT') return { ...EMPTY, departments: [] }; throw new Error('department_registry_read_failed: ' + (error instanceof Error ? error.message : String(error))); } let value; try { value = JSON.parse(text); } catch { throw new Error('department_registry_corrupt'); } if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error('department_registry_corrupt'); const file = value; if (file.version !== undefined && file.version !== 1) throw new Error('department_registry_incompatible'); if (!Array.isArray(file.departments)) throw new Error('department_registry_incompatible'); return { version: 1, departments: file.departments }; } async update(job) { return withFileLock(this.path + '.lock', async () => { const file = await this.read(); const result = await job(file); await atomicWrite(this.path, JSON.stringify(file, null, 2) + '\n'); return result; }); } }