all repos — stealth-developers @ 529dba23bb15864af72a10bbf4162a6406dd9294

pkgs/config/src/index.ts (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
import { join, resolve } from "node:path";
import schema, { type Config } from "./schema";

export const ENVIRONMENT = Bun.env.NODE_ENV || "development";
export const IS_PROD = ENVIRONMENT === "production";
export const CONFIG_PATH = getConfigPath();

function getConfigPath() {
	let envPath = Bun.env.CONFIG_FILE;
	if (envPath) {
		envPath = envPath.replaceAll("{ENVIRONMENT}", ENVIRONMENT).replaceAll("{ENV}", ENVIRONMENT);
		return resolve(envPath);
	}

	return join(import.meta.dir, "..", "environments", `config.${ENVIRONMENT}.json`);
}

async function loadConfig(): Promise<Config> {
	const file = Bun.file(CONFIG_PATH);
	if (!(await file.exists())) {
		console.error(`[!] couldn't find a config file at ${CONFIG_PATH}`);
		process.exit(1);
	}

	const json = await file.json();
	const parsed = schema.safeParse(json);

	if (parsed.success) return parsed.data;

	console.error("[!] failed to parse config:");

	const longestPath = Math.max(...parsed.error.issues.map((err) => err.path.join(".").length));
	for (const err of parsed.error.issues) {
		const path = err.path.join(".");
		console.error(` * ${path.padEnd(longestPath)}   ${err.message} (${err.code})`);
	}
	process.exit(1);
}

const config = await loadConfig();
export default config;