@dharaneesh/env-schema-validator 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +263 -0
- package/dist/index.cjs +122 -0
- package/dist/index.d.cts +23 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +96 -0
- package/package.json +33 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 DHARANEESH
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
# @dharaneesh/env-schema-validator
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@dharaneesh/env-schema-validator)
|
|
4
|
+
[](./LICENSE)
|
|
5
|
+
[](./package.json)
|
|
6
|
+
[](./src/index.ts)
|
|
7
|
+
|
|
8
|
+
> Zero-dependency, TypeScript-first `.env` validator. Validates all environment variables **at startup**, returns a fully typed object, and tells you **everything that's wrong — all at once**.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## The Problem
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
// ❌ Without this package — crashes at runtime, no types, no helpful errors
|
|
16
|
+
const port = Number(process.env.PORT); // NaN if PORT is missing
|
|
17
|
+
const db = process.env.DATABASE_URL; // string | undefined, no safety
|
|
18
|
+
const flag = process.env.DEBUG === "true"; // works, but fragile
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
You only discover missing or malformed env vars when your app crashes in production — not at startup.
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## The Solution
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import { validateEnv } from "@dharaneesh/env-schema-validator";
|
|
29
|
+
|
|
30
|
+
const env = validateEnv({
|
|
31
|
+
PORT: { type: "number", default: "3000" },
|
|
32
|
+
DATABASE_URL: { type: "url", description: "PostgreSQL connection string" },
|
|
33
|
+
NODE_ENV: { type: "string", enum: ["development", "production", "test"] },
|
|
34
|
+
DEBUG: { type: "boolean", required: false, default: "false" },
|
|
35
|
+
ADMIN_EMAIL: { type: "email", required: false },
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
// ✅ Fully typed — no casting needed
|
|
39
|
+
env.PORT // number
|
|
40
|
+
env.DATABASE_URL // string (guaranteed valid URL)
|
|
41
|
+
env.DEBUG // boolean
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
If anything is wrong, you get one clear error at startup — before your server even starts:
|
|
45
|
+
|
|
46
|
+
```
|
|
47
|
+
EnvValidationError: Environment validation failed:
|
|
48
|
+
|
|
49
|
+
✗ DATABASE_URL: is required but not set (PostgreSQL connection string)
|
|
50
|
+
✗ PORT: must be a number, got "abc"
|
|
51
|
+
✗ NODE_ENV: must be one of [development, production, test], got "prod"
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
---
|
|
55
|
+
|
|
56
|
+
## Installation
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
npm install @dharaneesh/env-schema-validator
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
No other dependencies needed. Works with Node.js 18+, ESM and CJS projects.
|
|
63
|
+
|
|
64
|
+
---
|
|
65
|
+
|
|
66
|
+
## Usage
|
|
67
|
+
|
|
68
|
+
### Basic
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
import { validateEnv } from "@dharaneesh/env-schema-validator";
|
|
72
|
+
|
|
73
|
+
const env = validateEnv({
|
|
74
|
+
APP_NAME: { type: "string" },
|
|
75
|
+
PORT: { type: "number", default: "3000" },
|
|
76
|
+
DEBUG: { type: "boolean", required: false, default: "false" },
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
console.log(env.PORT); // 3000 (number, not string)
|
|
80
|
+
console.log(env.DEBUG); // false (boolean, not string)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### With dotenv
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
import "dotenv/config"; // loads .env into process.env first
|
|
87
|
+
import { validateEnv } from "@dharaneesh/env-schema-validator";
|
|
88
|
+
|
|
89
|
+
const env = validateEnv({
|
|
90
|
+
DATABASE_URL: { type: "url" },
|
|
91
|
+
JWT_SECRET: { type: "string" },
|
|
92
|
+
});
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### Recommended — shared config module
|
|
96
|
+
|
|
97
|
+
Create one file that validates everything at startup. Import it everywhere.
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
// src/config.ts
|
|
101
|
+
import { validateEnv } from "@dharaneesh/env-schema-validator";
|
|
102
|
+
|
|
103
|
+
export const config = validateEnv({
|
|
104
|
+
NODE_ENV: { type: "string", enum: ["development", "production", "test"] },
|
|
105
|
+
PORT: { type: "number", default: "3000" },
|
|
106
|
+
DATABASE_URL: { type: "url", description: "PostgreSQL connection string" },
|
|
107
|
+
REDIS_URL: { type: "url", required: false },
|
|
108
|
+
JWT_SECRET: { type: "string", description: "At least 32 characters" },
|
|
109
|
+
JWT_EXPIRES: { type: "string", default: "7d" },
|
|
110
|
+
DEBUG: { type: "boolean", required: false, default: "false" },
|
|
111
|
+
ADMIN_EMAIL: { type: "email", required: false },
|
|
112
|
+
SMTP_HOST: { type: "string", required: false },
|
|
113
|
+
SMTP_PORT: { type: "number", required: false, default: "587" },
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
// Now import config anywhere:
|
|
117
|
+
// import { config } from "./config";
|
|
118
|
+
// config.PORT → number
|
|
119
|
+
// config.DATABASE_URL → string
|
|
120
|
+
// config.DEBUG → boolean
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
### Validate a custom object (not process.env)
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
const env = validateEnv(
|
|
127
|
+
{ PORT: { type: "number" } },
|
|
128
|
+
{ PORT: "8080" } // pass any Record<string, string | undefined>
|
|
129
|
+
);
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
---
|
|
133
|
+
|
|
134
|
+
## Schema Reference
|
|
135
|
+
|
|
136
|
+
Every key in your schema maps to a `FieldSchema` object:
|
|
137
|
+
|
|
138
|
+
| Field | Type | Default | Description |
|
|
139
|
+
|---------------|---------------------------------------------------|----------|----------------------------------------------|
|
|
140
|
+
| `type` | `"string" \| "number" \| "boolean" \| "url" \| "email"` | — | How to validate and coerce the raw value |
|
|
141
|
+
| `required` | `boolean` | `true` | If `false`, missing field is skipped |
|
|
142
|
+
| `default` | `string` | — | Raw string used when field is absent |
|
|
143
|
+
| `enum` | `string[]` | — | Restricts to a list of allowed values |
|
|
144
|
+
| `description` | `string` | — | Shown in the error message when field fails |
|
|
145
|
+
|
|
146
|
+
---
|
|
147
|
+
|
|
148
|
+
## Types Explained
|
|
149
|
+
|
|
150
|
+
| Type | What it accepts | JS output |
|
|
151
|
+
|-----------|---------------------------------------------------------|-------------|
|
|
152
|
+
| `string` | Any non-empty string | `string` |
|
|
153
|
+
| `number` | Any numeric string (`"3000"`, `"3.14"`, `"-1"`) | `number` |
|
|
154
|
+
| `boolean` | `true`, `false`, `1`, `0`, `yes`, `no`, `on`, `off` | `boolean` |
|
|
155
|
+
| `url` | Any string parseable by `new URL()` (must include protocol) | `string` |
|
|
156
|
+
| `email` | Basic `user@domain.tld` format | `string` |
|
|
157
|
+
|
|
158
|
+
Boolean coercion is **case-insensitive** — `TRUE`, `True`, `YES` all work.
|
|
159
|
+
|
|
160
|
+
---
|
|
161
|
+
|
|
162
|
+
## API
|
|
163
|
+
|
|
164
|
+
### `validateEnv(schema, source?)`
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
function validateEnv<S extends EnvSchema>(
|
|
168
|
+
schema: S,
|
|
169
|
+
source?: Record<string, string | undefined> // defaults to process.env
|
|
170
|
+
): ValidatedEnv<S>
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
- **On success** — returns a typed `ValidatedEnv<S>` object with all values coerced to their proper JS types.
|
|
174
|
+
- **On failure** — throws `EnvValidationError` with **all** problems listed, not just the first one.
|
|
175
|
+
|
|
176
|
+
---
|
|
177
|
+
|
|
178
|
+
### `EnvValidationError`
|
|
179
|
+
|
|
180
|
+
```ts
|
|
181
|
+
import { validateEnv, EnvValidationError } from "@dharaneesh/env-schema-validator";
|
|
182
|
+
|
|
183
|
+
try {
|
|
184
|
+
const env = validateEnv(schema);
|
|
185
|
+
} catch (err) {
|
|
186
|
+
if (err instanceof EnvValidationError) {
|
|
187
|
+
// Human-readable multi-line string — log this
|
|
188
|
+
console.error(err.message);
|
|
189
|
+
|
|
190
|
+
// Machine-readable array — use this programmatically
|
|
191
|
+
err.errors.forEach(({ key, message }) => {
|
|
192
|
+
console.error(`${key}: ${message}`);
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
process.exit(1);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
`err.errors` is an array of `{ key: string; message: string }` objects, one per failed field.
|
|
201
|
+
|
|
202
|
+
---
|
|
203
|
+
|
|
204
|
+
## Why Not Just Use `envalid` or `zod`?
|
|
205
|
+
|
|
206
|
+
| Feature | `dotenv` | `envalid` | `zod` | **@dharaneesh/env-schema-validator** |
|
|
207
|
+
|----------------------------------|:--------:|:---------:|:-----:|:------------------------:|
|
|
208
|
+
| Zero runtime dependencies | ✅ | ❌ | ❌ | ✅ |
|
|
209
|
+
| TypeScript types from schema | ❌ | ✅ | ✅ | ✅ |
|
|
210
|
+
| URL + email types built-in | ❌ | ✅ | ❌ | ✅ |
|
|
211
|
+
| Reports ALL errors at once | ❌ | ✅ | ✅ | ✅ |
|
|
212
|
+
| ESM + CJS dual output | ❌ | ❌ | ✅ | ✅ |
|
|
213
|
+
| Single file, no config needed | ❌ | ❌ | ❌ | ✅ |
|
|
214
|
+
|
|
215
|
+
---
|
|
216
|
+
|
|
217
|
+
## TypeScript Support
|
|
218
|
+
|
|
219
|
+
Full types come included — no `@types/` package needed.
|
|
220
|
+
|
|
221
|
+
```ts
|
|
222
|
+
import { validateEnv, EnvSchema, ValidatedEnv, EnvValidationError } from "@dharaneesh/env-schema-validator";
|
|
223
|
+
|
|
224
|
+
const schema = {
|
|
225
|
+
PORT: { type: "number" as const },
|
|
226
|
+
NAME: { type: "string" as const },
|
|
227
|
+
} satisfies EnvSchema;
|
|
228
|
+
|
|
229
|
+
type AppEnv = ValidatedEnv<typeof schema>;
|
|
230
|
+
// { PORT: number; NAME: string }
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
---
|
|
234
|
+
|
|
235
|
+
## Example `.env` File
|
|
236
|
+
|
|
237
|
+
```env
|
|
238
|
+
NODE_ENV=production
|
|
239
|
+
PORT=3000
|
|
240
|
+
DATABASE_URL=postgres://user:pass@localhost:5432/mydb
|
|
241
|
+
JWT_SECRET=my-very-long-secret-key-here
|
|
242
|
+
DEBUG=false
|
|
243
|
+
ADMIN_EMAIL=admin@example.com
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
---
|
|
247
|
+
|
|
248
|
+
## Contributing
|
|
249
|
+
|
|
250
|
+
```bash
|
|
251
|
+
git clone https://github.com/dharaneesh-r/@dharaneesh/env-schema-validator
|
|
252
|
+
cd @dharaneesh/env-schema-validator
|
|
253
|
+
npm install
|
|
254
|
+
npm test # run tests
|
|
255
|
+
npm run test:watch # watch mode
|
|
256
|
+
npm run build # build dist/
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
---
|
|
260
|
+
|
|
261
|
+
## License
|
|
262
|
+
|
|
263
|
+
MIT © Dharaneesh R
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
EnvValidationError: () => EnvValidationError,
|
|
24
|
+
validateEnv: () => validateEnv
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(index_exports);
|
|
27
|
+
var EnvValidationError = class extends Error {
|
|
28
|
+
constructor(errors) {
|
|
29
|
+
const lines = errors.map((e) => ` \u2717 ${e.key}: ${e.message}`).join("\n");
|
|
30
|
+
super(`Environment validation failed:
|
|
31
|
+
|
|
32
|
+
${lines}
|
|
33
|
+
`);
|
|
34
|
+
this.name = "EnvValidationError";
|
|
35
|
+
this.errors = errors;
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
function coerceBoolean(raw) {
|
|
39
|
+
if (["true", "1", "yes", "on"].includes(raw.toLowerCase())) return true;
|
|
40
|
+
if (["false", "0", "no", "off"].includes(raw.toLowerCase())) return false;
|
|
41
|
+
return void 0;
|
|
42
|
+
}
|
|
43
|
+
function coerceNumber(raw) {
|
|
44
|
+
const n = Number(raw);
|
|
45
|
+
return isNaN(n) ? void 0 : n;
|
|
46
|
+
}
|
|
47
|
+
function isValidUrl(raw) {
|
|
48
|
+
try {
|
|
49
|
+
new URL(raw);
|
|
50
|
+
return true;
|
|
51
|
+
} catch {
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function isValidEmail(raw) {
|
|
56
|
+
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(raw);
|
|
57
|
+
}
|
|
58
|
+
function validateEnv(schema, source = process.env) {
|
|
59
|
+
const errors = [];
|
|
60
|
+
const result = {};
|
|
61
|
+
for (const [key, field] of Object.entries(schema)) {
|
|
62
|
+
const required = field.required !== false;
|
|
63
|
+
const raw = source[key] ?? field.default;
|
|
64
|
+
if (raw === void 0 || raw === "") {
|
|
65
|
+
if (required) {
|
|
66
|
+
const hint = field.description ? ` (${field.description})` : "";
|
|
67
|
+
errors.push({ key, message: `is required but not set${hint}` });
|
|
68
|
+
}
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
switch (field.type) {
|
|
72
|
+
case "string":
|
|
73
|
+
result[key] = raw;
|
|
74
|
+
break;
|
|
75
|
+
case "number": {
|
|
76
|
+
const n = coerceNumber(raw);
|
|
77
|
+
if (n === void 0) {
|
|
78
|
+
errors.push({ key, message: `must be a number, got "${raw}"` });
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
result[key] = n;
|
|
82
|
+
break;
|
|
83
|
+
}
|
|
84
|
+
case "boolean": {
|
|
85
|
+
const b = coerceBoolean(raw);
|
|
86
|
+
if (b === void 0) {
|
|
87
|
+
errors.push({ key, message: `must be a boolean (true/false/1/0/yes/no/on/off), got "${raw}"` });
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
result[key] = b;
|
|
91
|
+
break;
|
|
92
|
+
}
|
|
93
|
+
case "url":
|
|
94
|
+
if (!isValidUrl(raw)) {
|
|
95
|
+
errors.push({ key, message: `must be a valid URL, got "${raw}"` });
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
result[key] = raw;
|
|
99
|
+
break;
|
|
100
|
+
case "email":
|
|
101
|
+
if (!isValidEmail(raw)) {
|
|
102
|
+
errors.push({ key, message: `must be a valid email, got "${raw}"` });
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
result[key] = raw;
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
if (field.enum && result[key] !== void 0) {
|
|
109
|
+
const coerced = String(result[key]);
|
|
110
|
+
if (!field.enum.includes(coerced)) {
|
|
111
|
+
errors.push({ key, message: `must be one of [${field.enum.join(", ")}], got "${coerced}"` });
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
if (errors.length > 0) throw new EnvValidationError(errors);
|
|
116
|
+
return result;
|
|
117
|
+
}
|
|
118
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
119
|
+
0 && (module.exports = {
|
|
120
|
+
EnvValidationError,
|
|
121
|
+
validateEnv
|
|
122
|
+
});
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
type FieldType = "string" | "number" | "boolean" | "url" | "email";
|
|
2
|
+
interface FieldSchema {
|
|
3
|
+
type: FieldType;
|
|
4
|
+
required?: boolean;
|
|
5
|
+
default?: string;
|
|
6
|
+
enum?: string[];
|
|
7
|
+
description?: string;
|
|
8
|
+
}
|
|
9
|
+
type EnvSchema = Record<string, FieldSchema>;
|
|
10
|
+
type ValidatedEnv<S extends EnvSchema> = {
|
|
11
|
+
[K in keyof S]: S[K]["type"] extends "number" ? number : S[K]["type"] extends "boolean" ? boolean : string;
|
|
12
|
+
};
|
|
13
|
+
interface ValidationError {
|
|
14
|
+
key: string;
|
|
15
|
+
message: string;
|
|
16
|
+
}
|
|
17
|
+
declare class EnvValidationError extends Error {
|
|
18
|
+
errors: ValidationError[];
|
|
19
|
+
constructor(errors: ValidationError[]);
|
|
20
|
+
}
|
|
21
|
+
declare function validateEnv<S extends EnvSchema>(schema: S, source?: Record<string, string | undefined>): ValidatedEnv<S>;
|
|
22
|
+
|
|
23
|
+
export { type EnvSchema, EnvValidationError, type FieldSchema, type FieldType, type ValidatedEnv, type ValidationError, validateEnv };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
type FieldType = "string" | "number" | "boolean" | "url" | "email";
|
|
2
|
+
interface FieldSchema {
|
|
3
|
+
type: FieldType;
|
|
4
|
+
required?: boolean;
|
|
5
|
+
default?: string;
|
|
6
|
+
enum?: string[];
|
|
7
|
+
description?: string;
|
|
8
|
+
}
|
|
9
|
+
type EnvSchema = Record<string, FieldSchema>;
|
|
10
|
+
type ValidatedEnv<S extends EnvSchema> = {
|
|
11
|
+
[K in keyof S]: S[K]["type"] extends "number" ? number : S[K]["type"] extends "boolean" ? boolean : string;
|
|
12
|
+
};
|
|
13
|
+
interface ValidationError {
|
|
14
|
+
key: string;
|
|
15
|
+
message: string;
|
|
16
|
+
}
|
|
17
|
+
declare class EnvValidationError extends Error {
|
|
18
|
+
errors: ValidationError[];
|
|
19
|
+
constructor(errors: ValidationError[]);
|
|
20
|
+
}
|
|
21
|
+
declare function validateEnv<S extends EnvSchema>(schema: S, source?: Record<string, string | undefined>): ValidatedEnv<S>;
|
|
22
|
+
|
|
23
|
+
export { type EnvSchema, EnvValidationError, type FieldSchema, type FieldType, type ValidatedEnv, type ValidationError, validateEnv };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
var EnvValidationError = class extends Error {
|
|
3
|
+
constructor(errors) {
|
|
4
|
+
const lines = errors.map((e) => ` \u2717 ${e.key}: ${e.message}`).join("\n");
|
|
5
|
+
super(`Environment validation failed:
|
|
6
|
+
|
|
7
|
+
${lines}
|
|
8
|
+
`);
|
|
9
|
+
this.name = "EnvValidationError";
|
|
10
|
+
this.errors = errors;
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
function coerceBoolean(raw) {
|
|
14
|
+
if (["true", "1", "yes", "on"].includes(raw.toLowerCase())) return true;
|
|
15
|
+
if (["false", "0", "no", "off"].includes(raw.toLowerCase())) return false;
|
|
16
|
+
return void 0;
|
|
17
|
+
}
|
|
18
|
+
function coerceNumber(raw) {
|
|
19
|
+
const n = Number(raw);
|
|
20
|
+
return isNaN(n) ? void 0 : n;
|
|
21
|
+
}
|
|
22
|
+
function isValidUrl(raw) {
|
|
23
|
+
try {
|
|
24
|
+
new URL(raw);
|
|
25
|
+
return true;
|
|
26
|
+
} catch {
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function isValidEmail(raw) {
|
|
31
|
+
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(raw);
|
|
32
|
+
}
|
|
33
|
+
function validateEnv(schema, source = process.env) {
|
|
34
|
+
const errors = [];
|
|
35
|
+
const result = {};
|
|
36
|
+
for (const [key, field] of Object.entries(schema)) {
|
|
37
|
+
const required = field.required !== false;
|
|
38
|
+
const raw = source[key] ?? field.default;
|
|
39
|
+
if (raw === void 0 || raw === "") {
|
|
40
|
+
if (required) {
|
|
41
|
+
const hint = field.description ? ` (${field.description})` : "";
|
|
42
|
+
errors.push({ key, message: `is required but not set${hint}` });
|
|
43
|
+
}
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
switch (field.type) {
|
|
47
|
+
case "string":
|
|
48
|
+
result[key] = raw;
|
|
49
|
+
break;
|
|
50
|
+
case "number": {
|
|
51
|
+
const n = coerceNumber(raw);
|
|
52
|
+
if (n === void 0) {
|
|
53
|
+
errors.push({ key, message: `must be a number, got "${raw}"` });
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
result[key] = n;
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
case "boolean": {
|
|
60
|
+
const b = coerceBoolean(raw);
|
|
61
|
+
if (b === void 0) {
|
|
62
|
+
errors.push({ key, message: `must be a boolean (true/false/1/0/yes/no/on/off), got "${raw}"` });
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
result[key] = b;
|
|
66
|
+
break;
|
|
67
|
+
}
|
|
68
|
+
case "url":
|
|
69
|
+
if (!isValidUrl(raw)) {
|
|
70
|
+
errors.push({ key, message: `must be a valid URL, got "${raw}"` });
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
result[key] = raw;
|
|
74
|
+
break;
|
|
75
|
+
case "email":
|
|
76
|
+
if (!isValidEmail(raw)) {
|
|
77
|
+
errors.push({ key, message: `must be a valid email, got "${raw}"` });
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
result[key] = raw;
|
|
81
|
+
break;
|
|
82
|
+
}
|
|
83
|
+
if (field.enum && result[key] !== void 0) {
|
|
84
|
+
const coerced = String(result[key]);
|
|
85
|
+
if (!field.enum.includes(coerced)) {
|
|
86
|
+
errors.push({ key, message: `must be one of [${field.enum.join(", ")}], got "${coerced}"` });
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (errors.length > 0) throw new EnvValidationError(errors);
|
|
91
|
+
return result;
|
|
92
|
+
}
|
|
93
|
+
export {
|
|
94
|
+
EnvValidationError,
|
|
95
|
+
validateEnv
|
|
96
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@dharaneesh/env-schema-validator",
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "Zero-dependency TypeScript-first .env validator. Fails fast with clear, human-readable errors.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.cjs",
|
|
7
|
+
"module": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"import": { "types": "./dist/index.d.ts", "default": "./dist/index.js" },
|
|
12
|
+
"require": { "types": "./dist/index.d.cts", "default": "./dist/index.cjs" }
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": ["dist", "README.md"],
|
|
16
|
+
"scripts": {
|
|
17
|
+
"build": "tsup src/index.ts --format cjs,esm --dts --clean",
|
|
18
|
+
"test": "vitest run",
|
|
19
|
+
"test:watch": "vitest",
|
|
20
|
+
"lint": "tsc --noEmit",
|
|
21
|
+
"prepublishOnly": "npm run build && npm run test"
|
|
22
|
+
},
|
|
23
|
+
"keywords": ["env", "dotenv", "validator", "schema", "typescript", "environment", "zero-dependency"],
|
|
24
|
+
"author": "Dharaneesh R",
|
|
25
|
+
"license": "MIT",
|
|
26
|
+
"repository": { "type": "git", "url": "https://github.com/dharaneesh/env-schema-validator" },
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"@types/node": "^20.0.0",
|
|
29
|
+
"tsup": "^8.0.0",
|
|
30
|
+
"typescript": "^5.4.0",
|
|
31
|
+
"vitest": "^2.0.0"
|
|
32
|
+
}
|
|
33
|
+
}
|