A TypeScript utility to automatically check and verify environment variables in your project
Gardisto (from Esperanto, meaning "Guardian") is a TypeScript utility that helps you prevent environment variable related issues before they happen in production. It automatically scans your codebase for environment variable usage and verifies their existence and values, helping you catch configuration issues early in development.
-
Automatic Environment Variable Detection
- Recursively scans TypeScript files for
process.env
usage - Identifies missing or empty environment variables
- Detects potentially unsafe fallback patterns
- Recursively scans TypeScript files for
-
Flexible Configuration
- Customizable include/exclude patterns
- Debug mode for detailed scanning information
- Support for TypeScript and JavaScript files
-
Developer-Friendly Outputs
- Clear error messages with file and line references
- Warning system for potential issues
- Detailed logging in debug mode
Main function to check environment variables in your project.
Option | Type | Default | Description |
---|---|---|---|
debug |
boolean |
false |
Enable debug logging for detailed information |
include |
string[] |
[] |
Glob patterns for files to include |
exclude |
string[] |
[] |
Glob patterns for files to exclude |
showDefaultValues |
boolean |
false |
Show default values in warnings |
projectPath |
string |
process.cwd() |
Root path of the project to analyze |
import { gardisto } from 'gardisto';
gardisto({
// Enable debug mode for verbose logging
debug: true,
// Only check files in src and config directories
include: ['src/**/*.ts', 'config/**/*.ts'],
// Exclude test files and generated code
exclude: [
'**/*.test.ts',
'**/*.spec.ts',
'**/dist/**',
'**/node_modules/**'
],
// Show default values in warnings
showDefaultValues: true,
// Custom project path
projectPath: './my-project'
});
Gardisto provides detailed error messages with file locations:
// Missing required environment variable
Error: Missing required environment variable: API_KEY
at src/config.ts:10:15
// Warning for default value usage
Warning: Environment variable DATABASE_URL uses a default value: "localhost:5432"
at src/database.ts:5:20
import { createLogger } from 'gardisto';
const logger = createLogger({
debug: true,
minLevel: 'info',
maxLength: 5000,
colorize: true
});
// Use the logger
logger('info', 'Starting environment check...');
logger('error', new Error('Failed to read .env file'));
import { gardisto } from 'gardisto';
async function validateEnvironment() {
try {
const result = gardisto({
debug: true,
include: ['src/**/*.ts']
});
// Handle results
if (result.errors.length > 0) {
console.error('Environment validation failed!');
process.exit(1);
}
} catch (error) {
console.error('Failed to validate environment:', error);
process.exit(1);
}
}
-
CI/CD Integration
# GitHub Actions example jobs: validate-env: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-node@v2 - run: npm install gardisto - run: npx gardisto
-
Pre-commit Hook
{ "husky": { "hooks": { "pre-commit": "gardisto" } } }
-
Environment Variable Patterns
// Good - Easy to detect const apiKey = process.env.API_KEY; // Good - Default value is visible const port = process.env.PORT || '3000'; // Avoid - Hard to detect const config = { key: process[['env']]['API_KEY'] };
Problem:
Error: Missing required environment variable: API_KEY
Solution:
- Add the variable to your
.env
file - Set the variable in your environment
- Or add a default value if appropriate
Warning:
Warning: Environment variable PORT uses a default value: "3000"
Solutions:
- Set the variable explicitly if needed
- Ignore if the default is acceptable
- Document the default in your README
For better type safety, use type assertions:
const port = process.env.PORT || '3000';
const numericPort = parseInt(port, 10);
if (isNaN(numericPort)) {
throw new Error('PORT must be a valid number');
}
npm install gardisto
Basic usage with TypeScript:
import { gardisto } from 'gardisto';
// Basic usage
gardisto({
debug: false,
exclude: ['dist', 'node_modules']
});
// Advanced usage with custom patterns
gardisto({
debug: process.env.DEBUG === 'true',
include: ['src'],
exclude: ['dist', 'node_modules', '**/*.test.ts'],
}, './path/to/project/root');
To try out Gardisto with the provided example project, follow these steps:
-
Build and Link the Package
# Build the package npm run build # Create a global link npm link
-
Set Up the Example Project
# Navigate to the example directory cd example # Link to the local gardisto package npm link gardisto
-
Run the Example
The example project includes three test scenarios:
# Run with all environment variables set npm run test:complete # Run with some missing environment variables npm run test:partial # Run with no environment variables npm run test:missing
The test scripts demonstrate how Gardisto behaves with:
- Complete environment configuration (
test:complete
) - Partial environment configuration (
test:partial
) - Missing environment variables (
test:missing
)
- Complete environment configuration (
-
Expected Output
When running
test:complete
, you should see:- Environment variable checks
- Debug logs (if enabled)
- Warnings for any variables using default values
- Success message if all required variables are present
- Built with TypeScript
- Powered by Node.js file system APIs
- Uses AST parsing for accurate detection
We welcome contributions! Here's how you can help:
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature
) - Commit your changes (
git commit -m 'Add some AmazingFeature'
) - Push to the branch (
git push origin feature/AmazingFeature
) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
Need help? Found a bug? Have a feature request?
- π« Open an issue
- π¬ Start a discussion
- β Star the project if you find it useful!