// Configuration management for OGraph CLI import { readFile, writeFile, mkdir } from 'node:fs/promises' import { existsSync } from 'node:fs' import { join } from 'node:path' import { homedir } from 'node:os' // ─── Types ───────────────────────────────────────────────────────────────────── export interface Config { endpoint?: string token?: string } // ─── Paths ───────────────────────────────────────────────────────────────────── function getConfigDir(): string { return process.env.OGRAPH_CONFIG_DIR || join(homedir(), '.config', 'ograph') } function getConfigPath(): string { return join(getConfigDir(), 'config.json') } // ─── Config Functions ────────────────────────────────────────────────────────── export async function loadConfig(): Promise { const CONFIG_PATH = getConfigPath() if (!existsSync(CONFIG_PATH)) { return {} } try { const data = await readFile(CONFIG_PATH, 'utf-8') return JSON.parse(data) } catch (error) { console.warn('Warning: config.json is malformed, using empty config') return {} } } export async function saveConfig(config: Config): Promise { const CONFIG_DIR = getConfigDir() const CONFIG_PATH = getConfigPath() try { // Ensure config directory exists if (!existsSync(CONFIG_DIR)) { await mkdir(CONFIG_DIR, { recursive: true }) } await writeFile(CONFIG_PATH, JSON.stringify(config, null, 2), 'utf-8') } catch (error) { throw new Error(`Failed to save config: ${error}`) } } export async function setConfigValue(key: keyof Config, value: string): Promise { const config = await loadConfig() config[key] = value await saveConfig(config) } export async function getConfigValue(key: keyof Config): Promise { const config = await loadConfig() return config[key] }