const fs = require('node:fs/promises'); const path = require('node:path'); const { randomUUID } = require('node:crypto'); function createStore(rootDirectory) { if (!rootDirectory || !path.isAbsolute(rootDirectory)) throw new Error('An absolute private data directory is required'); const root = path.resolve(rootDirectory); const queues = new Map(); async function directory(workspace) { if (!/^[a-f0-9]{64}$/.test(workspace.namespace || '')) throw new Error('Invalid server workspace namespace'); await fs.mkdir(root, { recursive: true, mode: 0o700 }); const dir = path.join(root, workspace.namespace); await fs.mkdir(dir, { mode: 0o700 }).catch(error => { if (error.code !== 'EEXIST') throw error; }); const stat = await fs.lstat(dir); if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error('Unsafe workspace directory'); return dir; } async function read(workspace, kind = 'stores') { if (!['stores', 'brand'].includes(kind)) throw new Error('Invalid storage kind'); const dir = await directory(workspace); let text; try { text = await fs.readFile(path.join(dir, kind + '.json'), 'utf8'); } catch (error) { if (error.code === 'ENOENT') return kind === 'stores' ? [] : null; throw error; } const records = JSON.parse(text); if (kind === 'stores' ? !Array.isArray(records) : (!records || typeof records !== 'object' || Array.isArray(records))) throw new Error('Invalid saved workspace data'); return records; } async function update(workspace, change, kind = 'stores') { const key = workspace.namespace; const previous = queues.get(key) || Promise.resolve(); const task = previous.catch(() => {}).then(async () => { const records = await read(workspace, kind); const next = change(records); const dir = await directory(workspace); const target = path.join(dir, kind + '.json'); const temporary = path.join(dir, '.' + kind + '-' + randomUUID() + '.tmp'); let handle; try { handle = await fs.open(temporary, 'wx', 0o600); await handle.writeFile(JSON.stringify(next)); await handle.sync(); await handle.close(); handle = null; await fs.rename(temporary, target); if (process.platform !== 'win32') { const parent = await fs.open(dir, 'r'); try { await parent.sync(); } finally { await parent.close(); } } } finally { if (handle) await handle.close(); await fs.unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; }); } return next; }); queues.set(key, task); try { return await task; } finally { if (queues.get(key) === task) queues.delete(key); } } return { read, readBrand(workspace) { return read(workspace, 'brand'); }, saveBrand(workspace, brand) { return update(workspace, () => brand, 'brand'); }, upsert(workspace, store) { if (!store || typeof store.id !== 'string' || !store.id || store.id.length > 160 || !Array.isArray(store.products)) { return Promise.reject(new Error('Invalid imported store')); } return update(workspace, records => { const index = records.findIndex(item => item.id === store.id); if (index < 0) return [...records, store]; return records.map((item, position) => position === index ? store : item); }); }, remove(workspace, storeId) { if (typeof storeId !== 'string' || !storeId || storeId.length > 160) return Promise.reject(new Error('Invalid store ID')); return update(workspace, records => records.filter(item => item.id !== storeId)); } }; } module.exports = { createStore };