type EnvValue = string | string[] | number;
type EnvVars = Record<string, EnvValue>;
/**
Parses a string value into an array of strings.
@param value - The string value to parse.
@returns An array of non-empty trimmed strings.
*/
function parseStringArray(value: string): string[] {
// Yeet that string into an array, no cap
return value
.split(" ")
.map((item) => item.trim())
.filter(Boolean);
}
/**
Resolves a reference to another environment variable.
@param value - The reference string (starting with $).
@param envVars - The current environment variables object.
@returns The resolved value or the original reference if not found.
*/
function resolveEnvReference(value: string, envVars: EnvVars): string {
// Time to play "Find that var" - it's giving hide and seek vibes
return value.replace(/$([A-Z0-9_]+)/g, (_, p1) => {
const replacement = envVars[p1];
if (typeof replacement === "string") {
return resolveEnvReference(replacement, envVars);
}
return replacement !== undefined ? String(replacement) : $${p1};
});
}
/**
Attempts to parse a string as a number.
@param value - The string to parse.
@returns The parsed number or the original string if parsing fails.
*/
function parseNumberOrString(value: string): number | string {
const num = Number(value);
// Is it giving number? Or is it just a string catfishing us?
return isNaN(num) ? value : num;
}
Assistant
/**
Parses an environment variable value.
@param value - The string value to parse.
@param envVars - The current environment variables object.
@returns The parsed value as a string, string array, or number.
*/
function parseEnv(value: string, envVars: EnvVars): EnvValue {
const resolvedValue = resolveEnvReference(value, envVars);
// This value be looking kinda sus, might need to split
if (resolvedValue.includes(" ")) {
return parseStringArray(resolvedValue);
}
return parseNumberOrString(resolvedValue);
}
/**
Loads environment variables from a file.
@param filename - The name of the file to load.
@returns An object containing the loaded environment variables.
*/
export async function loadEnv(filename: string): Promise {
try {
const envText = await Deno.readTextFile(filename);
const envVars: EnvVars = {};
// Time to split these lines like my parents split up
const lines = envText.split("\n");
for (const line of lines) {
const equalIndex = line.indexOf("=");
if (equalIndex > 0) {
const key = line.slice(0, equalIndex).trim();
const value = line.slice(equalIndex + 1).trim();
envVars[key] = value; // Yolo, store that raw value
}
}
// Resolve variable references after all variables are loaded
for (const [key, value] of Object.entries(envVars)) {
if (typeof value === "string") {
envVars[key] = parseEnv(value, envVars);
}
}
return envVars;
} catch {
return {}; // Oof, empty object. This file ghosted us harder than my ex
}
}
/**
Type definition for the environment variables.
*/
export type Env = z.infer;
/**
Loads and parses environment variables.
@param customEnvPath - Optional custom path for the .env file.
@returns A promise that resolves to the parsed environment variables.
@throws {z.ZodError} If the loaded environment variables fail validation.
*/
export async function loadAndParseEnv(customEnvPath?: string): Promise {
const nodeEnv = Deno.env.get("NODE_ENV")?.toLowerCase() ?? "development";
let loadedEnv: EnvVars = {};
// Time to go on a scavenger hunt for env files, it's giving Amazing Race vibes
const envPaths = [
customEnvPath,
.env.${nodeEnv},
".env",
...getAdditionalEnvPaths(),
].filter(Boolean);
for (const path of envPaths) {
try {
loadedEnv = await loadEnv(path as string);
if (Object.keys(loadedEnv).length > 0) {
break; // We found a non-empty env file, it's a whole vibe
}
} catch {
// noop (No Operation, like my will to adult today)
}
}
// Time to face Zod, the final boss. It's gonna be lit... or we'll rage quit
return envSchema.parse(combinedEnv);
}
/**
Gets additional environment file paths from configuration.
@returns An array of additional environment file paths.
*/
function getAdditionalEnvPaths(): string[] {
const additionalPaths = Deno.env.get("ADDITIONAL_ENV_PATHS");
// More env files? This config is extra af
return additionalPaths ? parseStringArray(additionalPaths) : [];
}
/**
The parsed and validated environment variables.
@example
console.log(env.NODE_ENV);
*/
export const env = await loadAndParseEnv();
PROMPT: You are an expert code reviewer. Your task is to analyze the provided code files and provide a comprehensive code review. For each file, consider:
Code Quality: Assess readability, maintainability, and adherence to best practices
Potential Issues: Identify bugs, security vulnerabilities, or performance concerns
Suggestions: Provide specific recommendations for improvements
Format your review as follows:
Start with a brief overview of all files
For each file, provide:
A summary of the file's purpose
Key findings (both positive and negative)
Specific recommendations
End with any overall suggestions for the codebase
Your review should be detailed but concise, focusing on the most important aspects of the code.
type EnvValue = string | string[] | number;
type EnvVars = Record<string, EnvValue>;
/**
Parses a string value into an array of strings.
@param value - The string value to parse.
@returns An array of non-empty trimmed strings.
*/
function parseStringArray(value: string): string[] {
// Yeet that string into an array, no cap
return value
.split(" ")
.map((item) => item.trim())
.filter(Boolean);
}
/**
Resolves a reference to another environment variable.
@param value - The reference string (starting with $).
@param envVars - The current environment variables object.
@returns The resolved value or the original reference if not found.
*/
function resolveEnvReference(value: string, envVars: EnvVars): string {
// Time to play "Find that var" - it's giving hide and seek vibes
return value.replace(/$([A-Z0-9_]+)/g, (_, p1) => {
const replacement = envVars[p1];
if (typeof replacement === "string") {
return resolveEnvReference(replacement, envVars);
}
return replacement !== undefined ? String(replacement) : $${p1};
});
}
/**
Attempts to parse a string as a number.
@param value - The string to parse.
@returns The parsed number or the original string if parsing fails.
*/
function parseNumberOrString(value: string): number | string {
const num = Number(value);
// Is it giving number? Or is it just a string catfishing us?
return isNaN(num) ? value : num;
}
/**
Parses an environment variable value.
@param value - The string value to parse.
@param envVars - The current environment variables object.
@returns The parsed value as a string, string array, or number.
*/
function parseEnv(value: string, envVars: EnvVars): EnvValue {
const resolvedValue = resolveEnvReference(value, envVars);
// This value be looking kinda sus, might need to split
if (resolvedValue.includes(" ")) {
return parseStringArray(resolvedValue);
}
return parseNumberOrString(resolvedValue);
}
/**
Loads environment variables from a file.
@param filename - The name of the file to load.
@returns An object containing the loaded environment variables.
*/
export async function loadEnv(filename: string): Promise {
try {
const envText = await Deno.readTextFile(filename);
const envVars: EnvVars = {};
// Time to split these lines like my parents split up
const lines = envText.split("\n");
for (const line of lines) {
const equalIndex = line.indexOf("=");
if (equalIndex > 0) {
const key = line.slice(0, equalIndex).trim();
const value = line.slice(equalIndex + 1).trim();
envVars[key] = value; // Yolo, store that raw value
}
}
// Resolve variable references after all variables are loaded
for (const [key, value] of Object.entries(envVars)) {
if (typeof value === "string") {
envVars[key] = parseEnv(value, envVars);
}
}
return envVars;
} catch {
return {}; // Oof, empty object. This file ghosted us harder than my ex
}
}
/**
Type definition for the environment variables.
*/
export type Env = z.infer;
/**
Loads and parses environment variables.
@param customEnvPath - Optional custom path for the .env file.
@returns A promise that resolves to the parsed environment variables.
@throws {z.ZodError} If the loaded environment variables fail validation.
*/
export async function loadAndParseEnv(customEnvPath?: string): Promise {
const nodeEnv = Deno.env.get("NODE_ENV")?.toLowerCase() ?? "development";
let loadedEnv: EnvVars = {};
// Time to go on a scavenger hunt for env files, it's giving Amazing Race vibes
const envPaths = [
customEnvPath,
.env.${nodeEnv},
".env",
...getAdditionalEnvPaths(),
].filter(Boolean);
for (const path of envPaths) {
try {
loadedEnv = await loadEnv(path as string);
if (Object.keys(loadedEnv).length > 0) {
break; // We found a non-empty env file, it's a whole vibe
}
} catch {
// noop (No Operation, like my will to adult today)
}
}
// Time to face Zod, the final boss. It's gonna be lit... or we'll rage quit
return envSchema.parse(combinedEnv);
}
/**
Gets additional environment file paths from configuration.
@returns An array of additional environment file paths.
*/
function getAdditionalEnvPaths(): string[] {
const additionalPaths = Deno.env.get("ADDITIONAL_ENV_PATHS");
// More env files? This config is extra af
return additionalPaths ? parseStringArray(additionalPaths) : [];
}
/**
The parsed and validated environment variables.
@example
console.log(env.NODE_ENV);
*/
export const env = await loadAndParseEnv();
Overview of the File
The file ./src/lib/env.ts is responsible for handling environment variables within a Deno application. It includes schema validation using Zod to ensure environment variable compliance, string and array parsing utilities, and methods to load and resolve environment variables from files. Here's a detailed review of this code:
File: ./src/lib/env.ts
Summary of the File's Purpose
This file aims to provide utilities for loading, validating, and parsing environment variables in a Deno application. It leverages zod for schema validation and includes functions to handle defaults, type conversions, and cross-references among variables.
Key Findings
Positive Aspects:
Schema Validation: The use of Zod for validating environment variables ensures that only expected values are present, increasing reliability.
Modularity: The functions are small and focused, making it easier to test and maintain.
Error Handling: Several try-catch blocks handle potential errors when reading files, ensuring that the application doesn't crash due to a missing or unreadable .env file.
Environment Resolution: Functionality to resolve references between environment variables is well-abstracted and can be useful in complex situations where env vars depend on each other.
Negative Aspects:
Informal Comments: Some comments contain informal language ("Yeet," "Time to play," "Oof"), which can be distracting and unprofessional in a shared codebase.
Error Handling in loadEnv: The loadEnv function returns an empty object if there's an error reading a file. Without logging or additional handling, it might be difficult to track down what went wrong in production.
Lack of Comments in Key Areas: While there are many comments, they often describe the obvious. More complex logic, like environment variable resolution, may benefit from clearer explanations.
Unused Variables/Imports: The line export const env = await loadAndParseEnv(); suggests this code is expecting await at the top level, which may not always be supported depending on the runtime. Also, it's important to ensure that functions are invoked in a supported manner for all environments.
Specific Recommendations
Comment Revisions: Replace informal comments with professional and descriptive ones that add value by explaining why certain decisions were made or why certain logic exists.
Enhanced Error Handling and Logging: Implement a logging mechanism to provide more context in case of failures during file reads or parsing. This will assist in debugging and maintaining the application.
Refactor loadEnv Functionality: Consider refactoring to handle file errors more gracefully or log the specific reason why a file couldn't be read.
Use Destructuring: Destructure the Deno.env object to simplify access to environment variables and improve readability.
Top-Level Await Support: Ensure usage of top-level await (await loadAndParseEnv();) aligns with runtime support. If not supported, wrap the asynchronous call in an async function.
Overall Suggestions for the Codebase
Standardize Commenting: Implement a code style guide to enforce consistent and professional commenting across the codebase. This makes the code more approachable for maintenance and onboarding new developers.
Dependency Management: Keep an eye on external dependencies like zod for updates and ensure compatibility with the rest of the codebase regularly.
Testing: Consider implementing testing, if not already present, to cover key functionalities like environment variable parsing and validation.
These improvements will not only enhance the maintainability and readability of the code but also increase resilience and better prepare it for production environments.