import { readFile, writeFile } from 'node:fs/promises' import { existsSync } from 'node:fs' import type { StateEntry, StateFile } from './types.js' const STATE_PATH = '.metabase-state.json' export async function loadState(): Promise { if (!existsSync(STATE_PATH)) return [] const raw = await readFile(STATE_PATH, 'utf-8') return JSON.parse(raw) as StateFile } export async function saveState(state: StateFile): Promise { await writeFile(STATE_PATH, JSON.stringify(state, null, 2) + '\n') } export function findInState( state: StateFile, kind: StateEntry['kind'], name: string, collection?: string, ): StateEntry | undefined { return state.find( (e) => e.kind === kind && e.name === name && (collection === undefined || e.collection === collection), ) } export function upsertState(state: StateFile, entry: StateEntry): StateFile { const idx = state.findIndex( (e) => e.kind === entry.kind && e.name === entry.name && e.collection === entry.collection, ) if (idx >= 0) { state[idx] = entry } else { state.push(entry) } return state }