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 = {}; // 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 = parseEnv(); // Re-export the type for consumers export type { Env } from "./schema";