import fs from 'node:fs'; import path from 'node:path'; import dotenv from 'dotenv'; const loadedFiles = new Set(); const loadedKeys = new Set(); /** * Load `.env` from the current working directory. * If `mode` is provided, also load `.env.` and let it override `.env`. * Existing process env values keep highest priority. */ export function ensureRuntimeEnvLoaded(mode?: string): void { loadEnvFile(path.resolve(process.cwd(), '.env')); const normalizedMode = mode?.trim(); if (!normalizedMode) { return; } loadEnvFile(path.resolve(process.cwd(), `.env.${normalizedMode}`)); } function loadEnvFile(filePath: string): void { if (loadedFiles.has(filePath) || !fs.existsSync(filePath)) { return; } const parsed = dotenv.parse(fs.readFileSync(filePath)); for (const [key, value] of Object.entries(parsed)) { if (process.env[key] !== undefined && !loadedKeys.has(key)) { continue; } process.env[key] = value; loadedKeys.add(key); } loadedFiles.add(filePath); }