You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
36 lines
1.1 KiB
36 lines
1.1 KiB
import { config } from "dotenv";
|
|
import path from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import { envSchema, type Env } from "./schema";
|
|
|
|
// ── Load .env from project root ──
|
|
// Resolve relative to this file: packages/env/ → ../../.env = project root
|
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
const projectRoot = path.resolve(__dirname, "..", "..");
|
|
config({ path: path.resolve(projectRoot, ".env") });
|
|
|
|
// ── Parse & validate ──
|
|
function parseEnv(): Env {
|
|
const raw: Record<string, string | undefined> = {};
|
|
|
|
// Collect only the keys we care about from process.env
|
|
for (const key of Object.keys(envSchema.shape)) {
|
|
raw[key] = process.env[key];
|
|
}
|
|
|
|
const result = envSchema.safeParse(raw);
|
|
|
|
if (!result.success) {
|
|
const errors = result.error.issues
|
|
.map((issue) => ` - ${issue.path.join(".")}: ${issue.message}`)
|
|
.join("\n");
|
|
throw new Error(`Environment variable validation failed:\n${errors}`);
|
|
}
|
|
|
|
return result.data;
|
|
}
|
|
|
|
export const env: Readonly<Env> = parseEnv();
|
|
|
|
// Re-export the type for consumers
|
|
export type { Env } from "./schema";
|
|
|