import { readJsonFileWithFallback, writeJsonFileAtomically } from "@hanzo/bot/plugin-sdk/msteams"; import fs from "node:fs"; import { withFileLock as withPathLock } from "./file-lock.js"; const STORE_LOCK_OPTIONS = { retries: { retries: 10, factor: 2, minTimeout: 100, maxTimeout: 10_000, randomize: true, }, stale: 30_000, } as const; export async function readJsonFile( filePath: string, fallback: T, ): Promise<{ value: T; exists: boolean }> { return await readJsonFileWithFallback(filePath, fallback); } export async function writeJsonFile(filePath: string, value: unknown): Promise { await writeJsonFileAtomically(filePath, value); } async function ensureJsonFile(filePath: string, fallback: unknown) { try { await fs.promises.access(filePath); } catch { await writeJsonFile(filePath, fallback); } } export async function withFileLock( filePath: string, fallback: unknown, fn: () => Promise, ): Promise { await ensureJsonFile(filePath, fallback); return await withPathLock(filePath, STORE_LOCK_OPTIONS, async () => { return await fn(); }); }