58 lines
1.4 KiB
TypeScript
58 lines
1.4 KiB
TypeScript
import { join } from 'node:path';
|
|
import { TOML } from 'bun';
|
|
import { safeParse } from '@schema-hub/zod-error-formatter';
|
|
import { BotzillaConfig, BotzillaConfigSchema } from './schemas/index.js';
|
|
|
|
async function loadConfigFile() {
|
|
const path = join(__dirname, '..', '..', '..', 'config.toml');
|
|
|
|
const file = Bun.file(path);
|
|
|
|
if (!(await file.exists())) {
|
|
throw new Error('conifg.toml does not exist');
|
|
}
|
|
|
|
return await file.text();
|
|
}
|
|
|
|
type TomlParseResult =
|
|
| {
|
|
success: true;
|
|
obj: object;
|
|
}
|
|
| {
|
|
success: false;
|
|
line: number;
|
|
column: number;
|
|
message: string;
|
|
};
|
|
|
|
function isToml(contents: string): TomlParseResult {
|
|
try {
|
|
const obj = TOML.parse(contents);
|
|
return { success: true, obj };
|
|
} catch ({ line, column, message }: any) {
|
|
return { success: false, line, column, message };
|
|
}
|
|
}
|
|
|
|
export async function loadConfig(): Promise<BotzillaConfig> {
|
|
const contents = await loadConfigFile();
|
|
|
|
const tomlParseResult = isToml(contents);
|
|
|
|
if (!tomlParseResult.success) {
|
|
throw new Error(
|
|
`Parsing error on line ${tomlParseResult.line}, column ${tomlParseResult.column}: ${tomlParseResult.message}`
|
|
);
|
|
}
|
|
|
|
const parseResult = safeParse(BotzillaConfigSchema, tomlParseResult.obj);
|
|
|
|
if (parseResult.success) return parseResult.data;
|
|
|
|
throw parseResult.error;
|
|
}
|
|
|
|
export * from './schemas/index.js';
|