# env-schema-checker

A zero-config, type-safe, schema-driven .env validator with automatic error reporting, autocomplete, and runtime checks.

## Features

- ✅ Auto Schema from .env.example
- ✅ TypeScript Autocomplete
- ✅ CLI & API Support
- ✅ Integrates with zod/yup
- ✅ Fails Fast
- ✅ Works with dotenv
- ✅ Safe for SSR/Next.js/NestJS

## Installation

```bash
npm install env-schema-checker
# or
yarn add env-schema-checker
# or
pnpm add env-schema-checker
```

## Quick Start

```typescript
import { loadEnv } from 'env-schema-checker';

const env = loadEnv({
  schema: {
    PORT: 'number',
    NODE_ENV: ['development', 'production', 'test'],
    API_KEY: 'string',
  }
});

// TypeScript will provide autocomplete and type checking
app.listen(env.PORT);
```

## CLI Usage

The package includes a command-line interface for easy environment validation and type generation.

### Initialize a Schema File

Create a new schema file with default configuration:

```bash
# Create default schema file
npx env-schema-checker init

# Create schema file with custom path
npx env-schema-checker init -o ./config/env.schema.json
```

This creates a `.env.schema.json` file with default schema:

```json
{
  "NODE_ENV": ["development", "production", "test"],
  "PORT": "number",
  "HOST": "string",
  "DEBUG": "boolean"
}
```

### Validate Environment Variables

Validate your environment variables against a schema:

```bash
# Validate using default schema file (.env.schema.json) and .env file
npx env-schema-checker validate

# Validate with custom schema and env file paths
npx env-schema-checker validate -s ./config/schema.json -p ./config/.env

# Validate existing environment variables (no .env file)
npx env-schema-checker validate -s ./config/schema.json
```

**Example Output (Success):**
```
✅ Environment validation successful!
```

**Example Output (Failure):**
```
Environment validation failed:
  PORT: Invalid number format (received: invalid)
  NODE_ENV: Invalid enum value. Expected 'development' | 'production' | 'test', received 'invalid'
```

### Generate TypeScript Types

Generate TypeScript type definitions from your schema:

```bash
# Generate types and output to console
npx env-schema-checker gen-types -s .env.schema.json

# Generate types and save to file
npx env-schema-checker gen-types -s .env.schema.json -o ./types/env.d.ts

# Generate types with custom schema path
npx env-schema-checker gen-types -s ./config/schema.json -o ./src/types/env.d.ts
```

**Generated TypeScript Types:**
```typescript
declare global {
  namespace NodeJS {
    interface ProcessEnv {
      NODE_ENV: 'development' | 'production' | 'test';
      PORT: number;
      HOST: string;
      DEBUG: boolean;
    }
  }
}

export {};
```

### CLI Options

#### `init` Command
- `-o, --output <path>` - Output path for schema file (default: `.env.schema.json`)

#### `validate` Command
- `-p, --path <path>` - Path to .env file (default: `.env`)
- `-s, --schema <path>` - Path to schema file (default: `.env.schema.json`)

#### `gen-types` Command
- `-s, --schema <path>` - Path to schema file (default: `.env.schema.json`)
- `-o, --output <path>` - Output path for type definitions (optional)

### Integration with Build Scripts

Add CLI commands to your `package.json` scripts:

```json
{
  "scripts": {
    "env:init": "env-schema-checker init",
    "env:validate": "env-schema-checker validate",
    "env:types": "env-schema-checker gen-types -o ./types/env.d.ts",
    "prebuild": "npm run env:validate",
    "build": "npm run env:types && tsc"
  }
}
```

### CI/CD Integration

Use in your CI/CD pipeline to validate environment variables:

```yaml
# GitHub Actions example
- name: Validate Environment
  run: npx env-schema-checker validate -s .env.schema.json
```

```bash
# Docker example
RUN npx env-schema-checker validate -s .env.schema.json
```

## API Reference

### loadEnv(options: LoadEnvOptions)

Loads and validates environment variables according to the provided schema.

```typescript
interface LoadEnvOptions {
  schema: EnvSchema;
  path?: string;        // Path to .env file
  encoding?: string;    // File encoding
  override?: boolean;   // Override existing env vars
  debug?: boolean;      // Enable debug mode
}
```

### generateTypes(options: TypeGeneratorOptions)

Generates TypeScript type definitions for your environment variables.

```typescript
interface TypeGeneratorOptions {
  outputPath?: string;  // Path to save type definitions
  schema: EnvSchema;    // Your environment schema
}
```

### validateEnv(schema: EnvSchema)

Validates environment variables without loading them from a file.

### parseEnvFile(path: string)

Parses an .env file and returns the variables as an object.

## Schema Types

The schema supports the following types:

- `'string'` - String values
- `'number'` - Numeric values
- `'boolean'` - Boolean values
- `'array'` - Comma-separated arrays
- `'object'` - JSON objects
- `string[]` - Enum values
- `z.ZodType` - Custom Zod schemas

## Examples

### Basic Usage

```typescript
import { loadEnv } from 'env-schema-checker';

const env = loadEnv({
  schema: {
    PORT: 'number',
    NODE_ENV: ['development', 'production', 'test'],
    API_KEY: 'string',
    DEBUG: 'boolean',
    ALLOWED_ORIGINS: 'array',
    CONFIG: 'object'
  }
});

if (!env.success) {
  console.error('Environment validation failed:', env.errors);
  process.exit(1);
}

// Use validated environment variables
const { PORT, NODE_ENV, API_KEY } = env.env;
```

### Custom Zod Schema

```typescript
import { z } from 'zod';
import { loadEnv } from 'env-schema-checker';

const env = loadEnv({
  schema: {
    PORT: z.string().transform(Number).pipe(z.number().min(1).max(65535)),
    API_KEY: z.string().min(32),
    DATABASE_URL: z.string().url()
  }
});
```

### Generate Type Definitions

```typescript
import { generateTypes } from 'env-schema-checker';

const types = generateTypes({
  schema: {
    PORT: 'number',
    NODE_ENV: ['development', 'production', 'test'],
    API_KEY: 'string'
  },
  outputPath: './types/env.d.ts'
});
```

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## License

MIT 