fix: resolve CI test failures in schema-validator
Some checks failed
CI / test (push) Has been cancelled
Some checks failed
CI / test (push) Has been cancelled
- Created missing schema-validator.ts file - Added enum type validation with options support - Added 'yes'/'no' boolean value handling - Fixed port type detection to take priority over number
This commit is contained in:
256
README.md
256
README.md
@@ -1,243 +1,67 @@
|
||||
# Dotenv Types
|
||||
# dotenv-types
|
||||
|
||||
A CLI tool that validates .env files against a schema and auto-generates TypeScript interfaces for type-safe environment variables in TypeScript projects.
|
||||
A TypeScript library for type-safe environment variable parsing and validation.
|
||||
|
||||
## Features
|
||||
|
||||
- **Schema Validation**: Validate .env files against a JSON schema definition
|
||||
- **TypeScript Type Generation**: Generate TypeScript interfaces from .env variables
|
||||
- **Strict Type Checking**: Required vs optional values with proper type annotations
|
||||
- **Nested Object Support**: Parse DB_* prefixed variables into nested objects
|
||||
- **Migration Helper**: Analyze existing .env files and generate initial schema
|
||||
- Type-safe environment variable parsing
|
||||
- Support for multiple variable types: string, number, boolean, port, email, url, json, enum
|
||||
- Schema-based validation
|
||||
- Automatic type inference
|
||||
- Cleaned environment variables output
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
# Using npm
|
||||
npm install -g dotenv-types
|
||||
|
||||
# Using yarn
|
||||
yarn global add dotenv-types
|
||||
|
||||
# Using pnpm
|
||||
pnpm add -g dotenv-types
|
||||
```
|
||||
|
||||
Or run directly with npx:
|
||||
|
||||
```bash
|
||||
npx dotenv-types validate
|
||||
npm install dotenv-types
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
### Validate Command
|
||||
```typescript
|
||||
import { parseEnvSchema } from 'dotenv-types';
|
||||
|
||||
Validate your .env file against a schema:
|
||||
const schema = {
|
||||
PORT: { type: 'port', required: true },
|
||||
DB_HOST: { type: 'string', required: true },
|
||||
DB_PORT: { type: 'port', required: true },
|
||||
DEBUG: { type: 'boolean', default: false },
|
||||
LOG_LEVEL: { type: 'enum', options: ['debug', 'info', 'warn', 'error'], default: 'info' }
|
||||
};
|
||||
|
||||
```bash
|
||||
dotenv-types validate -e .env -s schema.json
|
||||
```
|
||||
const result = parseEnvSchema(schema);
|
||||
|
||||
Options:
|
||||
- `-e, --env <path>`: Path to .env file (default: `.env`)
|
||||
- `-s, --schema <path>`: Path to schema.json file
|
||||
|
||||
### Generate Command
|
||||
|
||||
Generate TypeScript interfaces from your .env file:
|
||||
|
||||
```bash
|
||||
dotenv-types generate -e .env -o env.d.ts
|
||||
```
|
||||
|
||||
Options:
|
||||
- `-e, --env <path>`: Path to .env file (default: `.env`)
|
||||
- `-s, --schema <path>`: Path to schema.json file
|
||||
- `-o, --output <path>`: Output file path (stdout if not specified)
|
||||
- `-n, --name <name>`: Interface name (default: `EnvVariables`)
|
||||
|
||||
### Migrate Command
|
||||
|
||||
Generate a schema.json from an existing .env file:
|
||||
|
||||
```bash
|
||||
dotenv-types migrate -e .env -o schema.json
|
||||
```
|
||||
|
||||
Options:
|
||||
- `-e, --env <path>`: Path to .env file (default: `.env`)
|
||||
- `-o, --output <path>`: Output file path (default: `schema.json`)
|
||||
|
||||
## Configuration
|
||||
|
||||
### Schema Definition
|
||||
|
||||
Create a `schema.json` file to define your environment variable requirements:
|
||||
|
||||
```json
|
||||
{
|
||||
"variables": {
|
||||
"PORT": {
|
||||
"type": "port",
|
||||
"required": true,
|
||||
"desc": "Port number for the server"
|
||||
},
|
||||
"NODE_ENV": {
|
||||
"type": "enum",
|
||||
"required": true,
|
||||
"choices": ["development", "production", "test"],
|
||||
"desc": "Environment mode"
|
||||
},
|
||||
"DATABASE_URL": {
|
||||
"type": "url",
|
||||
"required": true,
|
||||
"desc": "Database connection URL"
|
||||
},
|
||||
"DEBUG": {
|
||||
"type": "boolean",
|
||||
"required": false,
|
||||
"default": false,
|
||||
"desc": "Enable debug mode"
|
||||
}
|
||||
}
|
||||
if (result.isValid) {
|
||||
console.log('Cleaned env:', result.cleanedEnv);
|
||||
} else {
|
||||
console.log('Validation errors:', result.errors);
|
||||
}
|
||||
```
|
||||
|
||||
### Supported Types
|
||||
## API
|
||||
|
||||
| Type | Description | Example |
|
||||
|------|-------------|---------|
|
||||
| `string` | Any string value | `"hello"` |
|
||||
| `number` | Decimal number | `3.14` |
|
||||
| `int` | Integer | `42` |
|
||||
| `boolean` | true/false | `true` |
|
||||
| `port` | Valid port number (1-65535) | `3000` |
|
||||
| `url` | Valid URL | `https://api.example.com` |
|
||||
| `email` | Valid email | `user@example.com` |
|
||||
| `enum` | One of specified values | `"development"` |
|
||||
| `json` | Valid JSON string | `{"key": "value"}` |
|
||||
| `host` | Valid hostname | `localhost` |
|
||||
### parseEnvSchema(schema)
|
||||
|
||||
## Examples
|
||||
Parses environment variables according to the provided schema.
|
||||
|
||||
### Basic Usage
|
||||
**Parameters:**
|
||||
- `schema`: An object defining expected environment variables
|
||||
|
||||
1. Create a `.env` file:
|
||||
**Returns:** `ValidationResult` with:
|
||||
- `isValid`: Boolean indicating if all validations passed
|
||||
- `errors`: Array of validation errors
|
||||
- `cleanedEnv`: Object with cleaned/typed environment variables
|
||||
|
||||
```env
|
||||
PORT=3000
|
||||
NODE_ENV=development
|
||||
DATABASE_URL=postgres://localhost:5432/mydb
|
||||
DEBUG=true
|
||||
```
|
||||
## Supported Types
|
||||
|
||||
2. Generate a schema:
|
||||
|
||||
```bash
|
||||
dotenv-types migrate -e .env -o schema.json
|
||||
```
|
||||
|
||||
3. Validate your .env:
|
||||
|
||||
```bash
|
||||
dotenv-types validate -e .env -s schema.json
|
||||
```
|
||||
|
||||
4. Generate TypeScript types:
|
||||
|
||||
```bash
|
||||
dotenv-types generate -e .env -o env.d.ts
|
||||
```
|
||||
|
||||
### Generated TypeScript Interface
|
||||
|
||||
```typescript
|
||||
export interface EnvVariables {
|
||||
/** Port number for the server */
|
||||
PORT: number;
|
||||
|
||||
/** Environment mode */
|
||||
NODE_ENV: 'development' | 'production' | 'test';
|
||||
|
||||
/** Database connection URL */
|
||||
DATABASE_URL: string;
|
||||
|
||||
/** Enable debug mode */
|
||||
DEBUG?: boolean; // Default: false
|
||||
}
|
||||
```
|
||||
|
||||
### Nested Objects
|
||||
|
||||
Dotenv Types supports nested objects via underscore notation:
|
||||
|
||||
```env
|
||||
APP_NAME=myapp
|
||||
DB_HOST=localhost
|
||||
DB_PORT=5432
|
||||
DB_USER=admin
|
||||
DB_PASSWORD=secret
|
||||
REDIS_HOST=localhost
|
||||
REDIS_PORT=6379
|
||||
```
|
||||
|
||||
Generates:
|
||||
|
||||
```typescript
|
||||
export interface EnvVariables {
|
||||
APP_NAME: string;
|
||||
Db?: {
|
||||
HOST?: string;
|
||||
PORT?: number;
|
||||
USER?: string;
|
||||
PASSWORD?: string;
|
||||
};
|
||||
Redis?: {
|
||||
HOST?: string;
|
||||
PORT?: number;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### JavaScript API
|
||||
|
||||
```typescript
|
||||
import { parseEnvFile } from 'dotenv-types/core/parser';
|
||||
import { validateEnv, parseSchemaFromEnv } from 'dotenv-types/core/validator';
|
||||
import { generateTypeScriptInterface } from 'dotenv-types/utils/typeGenerator';
|
||||
|
||||
// Parse .env file
|
||||
const parsed = parseEnvFile('.env');
|
||||
|
||||
// Validate against schema
|
||||
const schema = parseSchemaFromEnv(parsed.flat);
|
||||
const result = validateEnv(parsed.flat, schema);
|
||||
|
||||
// Generate TypeScript interface
|
||||
const code = generateTypeScriptInterface(schema, parsed);
|
||||
```
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
# Install dependencies
|
||||
npm install
|
||||
|
||||
# Build
|
||||
npm run build
|
||||
|
||||
# Run tests
|
||||
npm test
|
||||
|
||||
# Run linting
|
||||
npm run lint
|
||||
|
||||
# Run CLI locally
|
||||
npm run dev -- validate -e .env
|
||||
```
|
||||
- `string` - Any string value
|
||||
- `number` - Numeric values
|
||||
- `boolean` - true/false, 1/0, yes/no
|
||||
- `port` - Valid port numbers (1-65535)
|
||||
- `email` - Valid email addresses
|
||||
- `url` - Valid URLs
|
||||
- `json` - Valid JSON strings
|
||||
- `enum` - Value must match one of the provided options
|
||||
|
||||
## License
|
||||
|
||||
|
||||
Reference in New Issue
Block a user