110 lines
3.1 KiB
TypeScript
110 lines
3.1 KiB
TypeScript
import { existsSync, readFileSync } from "node:fs";
|
|||
|
|
import path from "node:path";
|
||
|
|
import dotenv from "dotenv";
|
||
|
|
import chokidar, { type FSWatcher } from "chokidar";
|
||
|
|
import { parse as parseYaml } from "yaml";
|
||
|
|
import { configSchema, type Config } from "./schema";
|
||
|
|
import { interpolateEnv } from "./interpolate";
|
||
|
|
|
||
|
|
const CONFIG_DIR = path.join(process.cwd(), "config");
|
||
|
|
const CONFIG_PATH = path.join(CONFIG_DIR, "config.yml");
|
||
|
|
const ENV_PATH = path.join(CONFIG_DIR, ".env");
|
||
|
|
|
||
|
|
export class ConfigError extends Error {}
|
||
|
|
|
||
|
|
function loadEnv(): Record<string, string | undefined> {
|
||
|
|
if (!existsSync(ENV_PATH)) return { ...process.env };
|
||
|
|
const parsed = dotenv.parse(readFileSync(ENV_PATH));
|
||
|
|
return { ...process.env, ...parsed };
|
||
|
|
}
|
||
|
|
|
||
|
|
export function readConfig(): Config {
|
||
|
|
if (!existsSync(CONFIG_PATH)) {
|
||
|
|
throw new ConfigError(`Config file not found at ${CONFIG_PATH}`);
|
||
|
|
}
|
||
|
|
|
||
|
|
const raw = readFileSync(CONFIG_PATH, "utf-8");
|
||
|
|
const env = loadEnv();
|
||
|
|
|
||
|
|
let interpolated: string;
|
||
|
|
try {
|
||
|
|
interpolated = interpolateEnv(raw, env);
|
||
|
|
} catch (err) {
|
||
|
|
throw new ConfigError((err as Error).message);
|
||
|
|
}
|
||
|
|
|
||
|
|
let parsedYaml: unknown;
|
||
|
|
try {
|
||
|
|
parsedYaml = parseYaml(interpolated);
|
||
|
|
} catch (err) {
|
||
|
|
throw new ConfigError(`Failed to parse config.yml: ${(err as Error).message}`);
|
||
|
|
}
|
||
|
|
|
||
|
|
const result = configSchema.safeParse(parsedYaml);
|
||
|
|
if (!result.success) {
|
||
|
|
const issues = result.error.issues
|
||
|
|
.map((issue) => ` - ${issue.path.join(".") || "(root)"}: ${issue.message}`)
|
||
|
|
.join("\n");
|
||
|
|
throw new ConfigError(`config.yml failed validation:\n${issues}`);
|
||
|
|
}
|
||
|
|
|
||
|
|
return result.data;
|
||
|
|
}
|
||
|
|
|
||
|
|
type ConfigListener = (config: Config) => void;
|
||
|
|
type ConfigErrorListener = (error: ConfigError) => void;
|
||
|
|
|
||
|
|
class ConfigStore {
|
||
|
|
private current: Config | null = null;
|
||
|
|
private watcher: FSWatcher | null = null;
|
||
|
|
private readonly listeners = new Set<ConfigListener>();
|
||
|
|
private readonly errorListeners = new Set<ConfigErrorListener>();
|
||
|
|
|
||
|
|
load(): Config {
|
||
|
|
this.current = readConfig();
|
||
|
|
return this.current;
|
||
|
|
}
|
||
|
|
|
||
|
|
get(): Config {
|
||
|
|
return this.current ?? this.load();
|
||
|
|
}
|
||
|
|
|
||
|
|
onUpdate(listener: ConfigListener): () => void {
|
||
|
|
this.listeners.add(listener);
|
||
|
|
return () => this.listeners.delete(listener);
|
||
|
|
}
|
||
|
|
|
||
|
|
onError(listener: ConfigErrorListener): () => void {
|
||
|
|
this.errorListeners.add(listener);
|
||
|
|
return () => this.errorListeners.delete(listener);
|
||
|
|
}
|
||
|
|
|
||
|
|
watch(): void {
|
||
|
|
if (this.watcher) return;
|
||
|
|
this.watcher = chokidar.watch([CONFIG_PATH, ENV_PATH], {
|
||
|
|
awaitWriteFinish: { stabilityThreshold: 200, pollInterval: 50 },
|
||
|
|
ignoreInitial: true,
|
||
|
|
});
|
||
|
|
this.watcher.on("all", () => this.reload());
|
||
|
|
}
|
||
|
|
|
||
|
|
stop(): void {
|
||
|
|
this.watcher?.close();
|
||
|
|
this.watcher = null;
|
||
|
|
}
|
||
|
|
|
||
|
|
private reload(): void {
|
||
|
|
try {
|
||
|
|
const next = readConfig();
|
||
|
|
this.current = next;
|
||
|
|
for (const listener of this.listeners) listener(next);
|
||
|
|
} catch (err) {
|
||
|
|
const configError = err instanceof ConfigError ? err : new ConfigError((err as Error).message);
|
||
|
|
console.error(`[config] ${configError.message}`);
|
||
|
|
for (const listener of this.errorListeners) listener(configError);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
export const configStore = new ConfigStore();
|