/**
 * Shared IPC utilities for atomic file writes.
 */
import fs from "fs";
import path from "path";
/**
 * Atomically write a JSON file to dir. Returns the filename (not full path).
 */
export function writeIpcFile(dir, data) {
    fs.mkdirSync(dir, { recursive: true });
    const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}.json`;
    const filepath = path.join(dir, filename);
    const tempPath = `${filepath}.tmp`;
    fs.writeFileSync(tempPath, JSON.stringify(data, null, 2));
    fs.renameSync(tempPath, filepath);
    return filename;
}
/**
 * Read and parse a JSON file. Returns null if the file does not exist.
 */
export function readJsonFile(filePath) {
    if (!fs.existsSync(filePath))
        return null;
    return JSON.parse(fs.readFileSync(filePath, "utf8"));
}
/**
 * Delete a result file to prevent reading stale data before a new request.
 */
export function clearStaleResult(filePath) {
    try {
        fs.unlinkSync(filePath);
    }
    catch { /* ok if missing */ }
}
/**
 * Poll a JSON file until the predicate returns true or timeout is reached.
 * Returns the parsed data or throws on timeout.
 */
export async function pollJsonFile(filePath, predicate, timeoutMs, intervalMs = 2000) {
    const deadline = Date.now() + timeoutMs;
    while (Date.now() < deadline) {
        if (fs.existsSync(filePath)) {
            try {
                const data = JSON.parse(fs.readFileSync(filePath, "utf-8"));
                if (predicate(data))
                    return data;
            }
            catch {
                // file still being written — retry
            }
        }
        await new Promise((resolve) => setTimeout(resolve, intervalMs));
    }
    throw new Error(`Timed out after ${timeoutMs}ms waiting for ${filePath}`);
}
//# sourceMappingURL=ipc.js.map