import { z } from 'zod'; const envSchema = z.object({ DATABASE_URL: z .string() .regex( /^postgres(ql)?:\/\//, 'DATABASE_URL must be a PostgreSQL connection string', ), PORT: z.preprocess( (value) => (value === undefined || value === '' ? 3000 : value), z.coerce.number().int().positive(), ), }); export type AppConfig = z.infer; export function validateEnv(config: Record): AppConfig { const result = envSchema.safeParse({ DATABASE_URL: config.DATABASE_URL, PORT: config.PORT, }); if (!result.success) { const details = result.error.issues .map((issue) => `${issue.path.join('.') || 'env'}: ${issue.message}`) .join('\n'); throw new Error(`Environment validation failed:\n${details}`); } return result.data; }