envguard-ts 1.0.0

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 envx contributors
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,363 @@
1
+ # envguard
2
+
3
+ [![npm version](https://img.shields.io/npm/v/envguard?color=brightgreen)](https://www.npmjs.com/package/envguard)
4
+ [![npm downloads](https://img.shields.io/npm/dw/envguard)](https://www.npmjs.com/package/envguard)
5
+ [![bundle size](https://img.shields.io/bundlephobia/minzip/envguard?label=minzip)](https://bundlephobia.com/package/envguard)
6
+ [![CI](https://github.com/Mehulbirare/npm-install-envx/actions/workflows/ci.yml/badge.svg)](https://github.com/Mehulbirare/npm-install-envx/actions)
7
+ [![coverage](https://codecov.io/gh/Mehulbirare/npm-install-envx/branch/main/graph/badge.svg)](https://codecov.io/gh/Mehulbirare/npm-install-envx)
8
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.x-blue)](https://www.typescriptlang.org/)
9
+ [![license](https://img.shields.io/npm/l/envguard)](LICENSE)
10
+
11
+ **Zero-dependency** TypeScript environment variable validator with compile-time type inference.
12
+ Validates on startup, throws human-readable errors, infers types — no `string` widening anywhere.
13
+
14
+ ```ts
15
+ import { createEnv, str, num, bool, url, port } from 'envguard-ts'
16
+
17
+ export const env = createEnv({
18
+ schema: {
19
+ DATABASE_URL: url(),
20
+ PORT: port({ default: 3000 }),
21
+ NODE_ENV: str({ choices: ['development', 'production', 'test'], default: 'development' }),
22
+ DEBUG: bool({ default: false }),
23
+ API_KEY: str({ secret: true }), // masked in error output
24
+ },
25
+ })
26
+
27
+ env.PORT // → number (not string!)
28
+ env.DATABASE_URL // → string
29
+ env.DEBUG // → boolean
30
+ ```
31
+
32
+ If any required variable is missing or fails validation, `createEnv` throws a **structured, readable error at startup** — not a cryptic runtime crash deep in your app.
33
+
34
+ ```
35
+ ✖ Environment validation failed
36
+
37
+ DATABASE_URL: is required but missing
38
+ PORT: must be between 1 and 65535 (received: "99999")
39
+ NODE_ENV: must be one of ["development", "production", "test"] (received: "staging")
40
+ ```
41
+
42
+ ---
43
+
44
+ ## Table of contents
45
+
46
+ - [Why envguard?](#why-envguard)
47
+ - [Install](#install)
48
+ - [Quick start](#quick-start)
49
+ - [API reference](#api-reference)
50
+ - [createEnv](#createenv)
51
+ - [Validators](#validators)
52
+ - [generateExample](#generateexample)
53
+ - [validateEnvFile](#validateenvfile)
54
+ - [EnvValidationError](#envvalidationerror)
55
+ - [CLI](#cli)
56
+ - [Examples](#examples)
57
+ - [Comparison](#comparison-vs-alternatives)
58
+ - [Contributing](#contributing)
59
+
60
+ ---
61
+
62
+ ## Why envguard?
63
+
64
+ | Feature | envguard | envalid | envsafe | t3-env |
65
+ |---|:---:|:---:|:---:|:---:|
66
+ | Zero dependencies | ✅ | ❌ (dotenv) | ✅ | ❌ (zod) |
67
+ | TypeScript-first types | ✅ | ⚠️ | ✅ | ✅ |
68
+ | Compile-time inference | ✅ | ❌ | ✅ | ✅ |
69
+ | Bundle size | **< 3 KB** | ~15 KB | ~4 KB | ~12 KB |
70
+ | Works in Edge / Deno / Bun | ✅ | ❌ | ⚠️ | ⚠️ |
71
+ | CLI (`npx envguard check`) | ✅ | ❌ | ❌ | ❌ |
72
+ | Auto `.env.example` gen | ✅ | ❌ | ❌ | ❌ |
73
+ | Secret masking | ✅ | ❌ | ❌ | ❌ |
74
+ | `choices` enum narrowing | ✅ | ✅ | ✅ | ✅ |
75
+
76
+ ---
77
+
78
+ ## Install
79
+
80
+ ```bash
81
+ npm install envguard-ts
82
+ # or
83
+ pnpm add envguard-ts
84
+ # or
85
+ yarn add envguard-ts
86
+ ```
87
+
88
+ No peer dependencies required. Works with Node ≥ 18, Deno, Bun, and all Edge runtimes.
89
+
90
+ ---
91
+
92
+ ## Quick start
93
+
94
+ ### 1. Create your env file
95
+
96
+ ```ts
97
+ // src/env.ts
98
+ import { createEnv, str, num, bool, url, port, email } from 'envguard-ts'
99
+
100
+ export const env = createEnv({
101
+ schema: {
102
+ DATABASE_URL: url({ protocols: ['postgresql:', 'postgres:'] }),
103
+ REDIS_URL: url({ default: 'redis://localhost:6379' }),
104
+ PORT: port({ default: 3000 }),
105
+ NODE_ENV: str({ choices: ['development', 'production', 'test'], default: 'development' }),
106
+ DEBUG: bool({ default: false }),
107
+ API_KEY: str({ secret: true }),
108
+ ADMIN_EMAIL: email({ default: 'admin@example.com' }),
109
+ MAX_POOL_SIZE: num({ default: 10, min: 1, max: 100 }),
110
+ },
111
+ })
112
+ ```
113
+
114
+ ### 2. Import it everywhere
115
+
116
+ ```ts
117
+ import { env } from './env'
118
+
119
+ // Fully typed, never undefined at runtime
120
+ const db = createPool(env.DATABASE_URL)
121
+ app.listen(env.PORT)
122
+ ```
123
+
124
+ ### 3. Validate before deploy
125
+
126
+ ```bash
127
+ npx envguard check --env .env.production --schema src/env.js
128
+ ```
129
+
130
+ ---
131
+
132
+ ## API reference
133
+
134
+ ### `createEnv(options)`
135
+
136
+ The primary API. Validates environment variables and returns a **frozen, typed object**.
137
+
138
+ ```ts
139
+ function createEnv<S extends Schema>(options: CreateEnvOptions<S>): InferEnv<S>
140
+ ```
141
+
142
+ | Option | Type | Default | Description |
143
+ |---|---|---|---|
144
+ | `schema` | `Schema` | required | Map of variable names → validators |
145
+ | `env` | `Record<string, string \| undefined>` | `process.env` | Override the env source (great for tests) |
146
+ | `skipValidation` | `boolean` | `false` | Return without throwing (useful in test setup) |
147
+ | `onError` | `(errors: FieldError[]) => void` | — | Called before throwing, for custom logging |
148
+
149
+ Throws [`EnvValidationError`](#envvalidationerror) if validation fails.
150
+
151
+ ---
152
+
153
+ ### Validators
154
+
155
+ All validators accept a `BaseOptions` bag:
156
+
157
+ ```ts
158
+ interface BaseOptions<T> {
159
+ default?: T // Makes the variable optional
160
+ description?: string // Shown in generated .env.example
161
+ secret?: boolean // Mask value in error output
162
+ }
163
+ ```
164
+
165
+ #### `str(opts?)`
166
+
167
+ Validates a string. Returned type: `string`.
168
+
169
+ ```ts
170
+ str()
171
+ str({ choices: ['a', 'b', 'c'] }) // string literal union NOT inferred — use enums() for that
172
+ str({ minLength: 1, maxLength: 255 })
173
+ str({ pattern: /^[a-z]+$/ })
174
+ str({ default: 'hello', secret: true })
175
+ ```
176
+
177
+ | Option | Type | Description |
178
+ |---|---|---|
179
+ | `choices` | `string[]` | Restrict to allowed values |
180
+ | `minLength` | `number` | Minimum string length (inclusive) |
181
+ | `maxLength` | `number` | Maximum string length (inclusive) |
182
+ | `pattern` | `RegExp` | Must match regex |
183
+
184
+ #### `num(opts?)`
185
+
186
+ Validates a number (integer or float). Returned type: `number`.
187
+
188
+ ```ts
189
+ num()
190
+ num({ min: 0, max: 100 })
191
+ num({ default: 42 })
192
+ ```
193
+
194
+ #### `bool(opts?)`
195
+
196
+ Validates a boolean. Accepts: `true/false/1/0/yes/no/on/off` (case-insensitive). Returned type: `boolean`.
197
+
198
+ ```ts
199
+ bool()
200
+ bool({ default: false })
201
+ ```
202
+
203
+ #### `url(opts?)`
204
+
205
+ Validates a URL using the WHATWG `URL` parser. Returned type: `string`.
206
+
207
+ ```ts
208
+ url()
209
+ url({ protocols: ['https:'] })
210
+ url({ protocols: ['postgresql:', 'postgres:'] })
211
+ ```
212
+
213
+ #### `port(opts?)`
214
+
215
+ Validates a port number (1–65535). Returned type: `number`.
216
+
217
+ ```ts
218
+ port()
219
+ port({ default: 3000 })
220
+ ```
221
+
222
+ #### `email(opts?)`
223
+
224
+ Validates an email address. Returned type: `string`.
225
+
226
+ ```ts
227
+ email()
228
+ email({ default: 'admin@example.com' })
229
+ ```
230
+
231
+ #### `json<T>(opts?)`
232
+
233
+ Parses a JSON-encoded string. Returned type: `T` (defaults to `unknown`).
234
+
235
+ ```ts
236
+ json()
237
+ json<string[]>({ default: [] })
238
+ json<{ apiUrl: string; timeout: number }>()
239
+ ```
240
+
241
+ #### `enums(values, opts?)`
242
+
243
+ Validates against a const-asserted string tuple. **Narrows the return type** to the union.
244
+
245
+ ```ts
246
+ enums(['debug', 'info', 'warn', 'error'] as const)
247
+ // → ValidatorSpec<'debug' | 'info' | 'warn' | 'error'>
248
+ ```
249
+
250
+ ---
251
+
252
+ ### `generateExample(schema)`
253
+
254
+ Generates the text of a `.env.example` file from a schema. Secrets are shown as `[secret]`.
255
+
256
+ ```ts
257
+ import { generateExample } from 'envguard'
258
+ import { schema } from './env'
259
+ import fs from 'node:fs'
260
+
261
+ fs.writeFileSync('.env.example', generateExample(schema))
262
+ ```
263
+
264
+ Or use the CLI: `npx envguard generate`
265
+
266
+ ---
267
+
268
+ ### `validateEnvFile(parsed, schema)`
269
+
270
+ Validates a pre-parsed `{ KEY: value }` map against a schema, returning errors without throwing. Used internally by the CLI.
271
+
272
+ ```ts
273
+ const errors = validateEnvFile(
274
+ { PORT: 'not-a-number' },
275
+ { PORT: port() },
276
+ )
277
+ // errors → [{ field: 'PORT', message: '...', received: 'not-a-number' }]
278
+ ```
279
+
280
+ ---
281
+
282
+ ### `EnvValidationError`
283
+
284
+ ```ts
285
+ class EnvValidationError extends Error {
286
+ readonly errors: readonly FieldError[]
287
+ }
288
+
289
+ interface FieldError {
290
+ field: string // Variable name
291
+ message: string // Human-readable failure reason
292
+ received: string | undefined // Raw value (or '[secret]' / undefined)
293
+ }
294
+ ```
295
+
296
+ ---
297
+
298
+ ## CLI
299
+
300
+ ```bash
301
+ # Validate a .env file against a schema
302
+ npx envguard check
303
+ npx envguard check --env .env.production --schema dist/env.js
304
+
305
+ # Generate .env.example from a schema
306
+ npx envguard generate
307
+ npx envguard generate --schema dist/env.js --out .env.example
308
+ ```
309
+
310
+ The schema file must export the schema object as `default`, `schema`, or the module itself:
311
+
312
+ ```js
313
+ // envguard-ts.schema.js (default location)
314
+ const { str, url, port } = require('envguard-ts')
315
+ module.exports = {
316
+ DATABASE_URL: url(),
317
+ PORT: port({ default: 3000 }),
318
+ API_KEY: str({ secret: true }),
319
+ }
320
+ ```
321
+
322
+ Exit codes: `0` = valid, `1` = invalid or error.
323
+
324
+ ---
325
+
326
+ ## Examples
327
+
328
+ - [Express](./examples/express/)
329
+ - [Next.js](./examples/nextjs/)
330
+ - [Fastify](./examples/fastify/)
331
+
332
+ ---
333
+
334
+ ## Comparison vs alternatives
335
+
336
+ ### vs `envalid`
337
+
338
+ envalid is battle-tested but has a dotenv peer dependency, a larger bundle (~15 KB), no TypeScript-first design, and no CLI tooling. envguard is zero-dep and infers precise types at compile time.
339
+
340
+ ### vs `envsafe`
341
+
342
+ envsafe is TS-first and has good inference but is no longer actively maintained. envguard adds the CLI, secret masking, and `.env.example` generation.
343
+
344
+ ### vs `t3-env`
345
+
346
+ t3-env wraps Zod which is powerful but adds ~12 KB to your bundle and requires Zod as a peer. envguard is zero-dependency and covers 95% of real-world use cases in < 3 KB. If you already use Zod heavily, t3-env might be a better fit; otherwise envguard is the lighter choice.
347
+
348
+ ---
349
+
350
+ ## Contributing
351
+
352
+ 1. Fork the repository
353
+ 2. Create a feature branch: `git checkout -b feat/my-feature`
354
+ 3. Run tests: `npm test`
355
+ 4. Submit a pull request
356
+
357
+ Please ensure `npm run test:coverage` passes at ≥ 90% coverage before opening a PR.
358
+
359
+ ---
360
+
361
+ ## License
362
+
363
+ MIT © envguard contributors
package/bin/envx.js ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ // envx CLI entry point
3
+ import('../dist/esm/cli.js').catch((e) => {
4
+ // Fallback to CJS if ESM import fails (Node 18 with --require hooks, etc.)
5
+ try {
6
+ require('../dist/cjs/cli.js')
7
+ } catch {
8
+ console.error('[envx] Failed to load CLI:', e?.message ?? e)
9
+ process.exit(1)
10
+ }
11
+ })
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ /**
4
+ * envx CLI — validate and generate .env files
5
+ *
6
+ * Commands:
7
+ * envx check [--env <file>] [--schema <file>]
8
+ * envx generate [--schema <file>] [--out <file>]
9
+ */
10
+ const fs = require("node:fs");
11
+ const path = require("node:path");
12
+ const core_js_1 = require("./core.js");
13
+ // ---------------------------------------------------------------------------
14
+ // Tiny .env parser (no dependency)
15
+ // ---------------------------------------------------------------------------
16
+ function parseEnvFile(content) {
17
+ const result = {};
18
+ for (const rawLine of content.split(/\r?\n/)) {
19
+ const line = rawLine.trim();
20
+ if (!line || line.startsWith('#'))
21
+ continue;
22
+ const eqIdx = line.indexOf('=');
23
+ if (eqIdx === -1)
24
+ continue;
25
+ const key = line.slice(0, eqIdx).trim();
26
+ let value = line.slice(eqIdx + 1).trim();
27
+ // Strip surrounding quotes
28
+ if ((value.startsWith('"') && value.endsWith('"')) ||
29
+ (value.startsWith("'") && value.endsWith("'"))) {
30
+ value = value.slice(1, -1);
31
+ }
32
+ result[key] = value;
33
+ }
34
+ return result;
35
+ }
36
+ // ---------------------------------------------------------------------------
37
+ // Arg parser
38
+ // ---------------------------------------------------------------------------
39
+ function parseArgs(argv) {
40
+ const args = {};
41
+ for (let i = 0; i < argv.length; i++) {
42
+ const arg = argv[i];
43
+ if (arg !== undefined && arg.startsWith('--')) {
44
+ const key = arg.slice(2);
45
+ const next = argv[i + 1];
46
+ if (next !== undefined && !next.startsWith('--')) {
47
+ args[key] = next;
48
+ i++;
49
+ }
50
+ else {
51
+ args[key] = true;
52
+ }
53
+ }
54
+ }
55
+ return args;
56
+ }
57
+ // ---------------------------------------------------------------------------
58
+ // Commands
59
+ // ---------------------------------------------------------------------------
60
+ async function loadSchema(schemaPath) {
61
+ const resolved = path.resolve(process.cwd(), schemaPath);
62
+ if (!fs.existsSync(resolved)) {
63
+ console.error(`[envx] schema file not found: ${resolved}`);
64
+ process.exit(1);
65
+ }
66
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
67
+ const mod = await Promise.resolve(`${resolved}`).then(s => require(s));
68
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
69
+ const schema = (mod.default ?? mod.schema ?? mod);
70
+ if (typeof schema !== 'object' || schema === null) {
71
+ console.error('[envx] schema file must export a default schema object');
72
+ process.exit(1);
73
+ }
74
+ return schema;
75
+ }
76
+ async function cmdCheck(args) {
77
+ const envFile = typeof args['env'] === 'string' ? args['env'] : '.env';
78
+ const schemaFile = typeof args['schema'] === 'string' ? args['schema'] : 'envguard.schema.js';
79
+ const envPath = path.resolve(process.cwd(), envFile);
80
+ if (!fs.existsSync(envPath)) {
81
+ console.error(`[envx] env file not found: ${envPath}`);
82
+ process.exit(1);
83
+ }
84
+ const schema = await loadSchema(schemaFile);
85
+ const parsed = parseEnvFile(fs.readFileSync(envPath, 'utf8'));
86
+ const errors = (0, core_js_1.validateEnvFile)(parsed, schema);
87
+ if (errors.length === 0) {
88
+ console.log(`\x1b[32m✔ ${envFile} is valid\x1b[0m`);
89
+ return;
90
+ }
91
+ console.error(`\x1b[31m✖ ${envFile} has ${errors.length} error(s):\x1b[0m\n`);
92
+ for (const err of errors) {
93
+ const received = err.received !== undefined ? ` (received: \x1b[90m${JSON.stringify(err.received)}\x1b[0m)` : '';
94
+ console.error(` \x1b[33m${err.field}\x1b[0m: ${err.message}${received}`);
95
+ }
96
+ console.error('');
97
+ process.exit(1);
98
+ }
99
+ async function cmdGenerate(args) {
100
+ const schemaFile = typeof args['schema'] === 'string' ? args['schema'] : 'envguard.schema.js';
101
+ const outFile = typeof args['out'] === 'string' ? args['out'] : '.env.example';
102
+ const schema = await loadSchema(schemaFile);
103
+ const content = (0, core_js_1.generateExample)(schema);
104
+ fs.writeFileSync(path.resolve(process.cwd(), outFile), content, 'utf8');
105
+ console.log(`\x1b[32m✔ Generated ${outFile}\x1b[0m`);
106
+ }
107
+ function printHelp() {
108
+ console.log(`
109
+ \x1b[1menvx\x1b[0m — Environment variable validator
110
+
111
+ \x1b[1mUsage:\x1b[0m
112
+ envx check [--env <file>] [--schema <file>]
113
+ envx generate [--schema <file>] [--out <file>]
114
+
115
+ \x1b[1mCommands:\x1b[0m
116
+ check Validate a .env file against a schema (default: .env / envx.schema.js)
117
+ generate Generate a .env.example from a schema (default output: .env.example)
118
+
119
+ \x1b[1mOptions:\x1b[0m
120
+ --env Path to the .env file (default: .env)
121
+ --schema Path to the schema JS/TS file (default: envx.schema.js)
122
+ --out Output path for generate (default: .env.example)
123
+ --help Show this help message
124
+ `);
125
+ }
126
+ // ---------------------------------------------------------------------------
127
+ // Entry point
128
+ // ---------------------------------------------------------------------------
129
+ async function main() {
130
+ const [, , command, ...rest] = process.argv;
131
+ const args = parseArgs(rest);
132
+ if (args['help'] || !command) {
133
+ printHelp();
134
+ return;
135
+ }
136
+ switch (command) {
137
+ case 'check':
138
+ await cmdCheck(args);
139
+ break;
140
+ case 'generate':
141
+ await cmdGenerate(args);
142
+ break;
143
+ default:
144
+ console.error(`[envx] Unknown command: ${command}`);
145
+ printHelp();
146
+ process.exit(1);
147
+ }
148
+ }
149
+ main().catch((err) => {
150
+ console.error('[envx] Unexpected error:', err);
151
+ process.exit(1);
152
+ });
153
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../../src/cli.ts"],"names":[],"mappings":";;AAAA;;;;;;GAMG;AACH,8BAA6B;AAC7B,kCAAiC;AACjC,uCAA4D;AAG5D,8EAA8E;AAC9E,mCAAmC;AACnC,8EAA8E;AAE9E,SAAS,YAAY,CAAC,OAAe;IACnC,MAAM,MAAM,GAA2B,EAAE,CAAA;IACzC,KAAK,MAAM,OAAO,IAAI,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;QAC7C,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,EAAE,CAAA;QAC3B,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC;YAAE,SAAQ;QAC3C,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;QAC/B,IAAI,KAAK,KAAK,CAAC,CAAC;YAAE,SAAQ;QAC1B,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,IAAI,EAAE,CAAA;QACvC,IAAI,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAA;QACxC,2BAA2B;QAC3B,IACE,CAAC,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;YAC9C,CAAC,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAC9C,CAAC;YACD,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA;QAC5B,CAAC;QACD,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAA;IACrB,C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O,CAAC,GAAG,CAAC,uBAAuB,OAAO,SAAS,CAAC,CAAA;AACtD,CAAC;AAED,SAAS,SAAS;IAChB,OAAO,CAAC,GAAG,CAAC;;;;;;;;;;;;;;;;CAgBb,CAAC,CAAA;AACF,CAAC;AAED,8EAA8E;AAC9E,cAAc;AACd,8EAA8E;AAE9E,KAAK,UAAU,IAAI;IACjB,MAAM,CAAC,EAAE,AAAD,EAAG,OAAO,EAAE,GAAG,IAAI,CAAC,GAAG,OAAO,CAAC,IAAI,CAAA;IAC3C,MAAM,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,CAAA;IAE5B,IAAI,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;QAC7B,SAAS,EAAE,CAAA;QACX,OAAM;IACR,CAAC;IAED,QAAQ,OAAO,EAAE,CAAC;QAChB,KAAK,OAAO;YACV,MAAM,QAAQ,CAAC,IAAI,CAAC,CAAA;YACpB,MAAK;QACP,KAAK,UAAU;YACb,MAAM,WAAW,CAAC,IAAI,CAAC,CAAA;YACvB,MAAK;QACP;YACE,OAAO,CAAC,KAAK,CAAC,2BAA2B,OAAO,EAAE,CAAC,CAAA;YACnD,SAAS,EAAE,CAAA;YACX,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;IACnB,CAAC;AACH,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;IACnB,OAAO,CAAC,KAAK,CAAC,0BAA0B,EAAE,GAAG,CAAC,CAAA;IAC9C,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;AACjB,CAAC,CAAC,CAAA"}
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createEnv = createEnv;
4
+ exports.generateExample = generateExample;
5
+ exports.validateEnvFile = validateEnvFile;
6
+ const errors_js_1 = require("./errors.js");
7
+ // ---------------------------------------------------------------------------
8
+ // createEnv
9
+ // ---------------------------------------------------------------------------
10
+ /**
11
+ * Validates environment variables against the provided schema and returns a
12
+ * fully-typed, frozen object. Throws {@link EnvValidationError} on failure.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * export const env = createEnv({
17
+ * schema: {
18
+ * DATABASE_URL: url(),
19
+ * PORT: port({ default: 3000 }),
20
+ * NODE_ENV: str({ choices: ['development', 'production', 'test'], default: 'development' }),
21
+ * DEBUG: bool({ default: false }),
22
+ * API_KEY: str({ secret: true }),
23
+ * },
24
+ * })
25
+ * ```
26
+ */
27
+ function createEnv(options) {
28
+ const { schema, env = process.env, skipValidation = false, onError } = options;
29
+ const errors = [];
30
+ const result = {};
31
+ for (const [field, spec] of Object.entries(schema)) {
32
+ const raw = env[field];
33
+ if (raw === undefined || raw === '') {
34
+ if (spec._default !== undefined) {
35
+ result[field] = spec._default;
36
+ continue;
37
+ }
38
+ if (!spec._required) {
39
+ // optional with no default → undefined (shouldn't happen given the overloads, but be safe)
40
+ result[field] = undefined;
41
+ continue;
42
+ }
43
+ errors.push({ field, message: 'is required but missing', received: undefined });
44
+ continue;
45
+ }
46
+ try {
47
+ const parsed = spec._parse(raw, field);
48
+ spec._validate(parsed, field);
49
+ result[field] = parsed;
50
+ }
51
+ catch (e) {
52
+ errors.push({
53
+ field,
54
+ message: e instanceof Error ? e.message : String(e),
55
+ received: spec._secret ? '[secret]' : raw,
56
+ });
57
+ }
58
+ }
59
+ if (errors.length > 0 && !skipValidation) {
60
+ onError?.(errors);
61
+ throw new errors_js_1.EnvValidationError(errors);
62
+ }
63
+ return Object.freeze(result);
64
+ }
65
+ // ---------------------------------------------------------------------------
66
+ // generateExample
67
+ // ---------------------------------------------------------------------------
68
+ /**
69
+ * Generates the text content of a `.env.example` file from a schema.
70
+ * Variables without defaults are left blank; those with defaults show the default.
71
+ * Secrets are shown as `[secret]`.
72
+ *
73
+ * @example
74
+ * ```ts
75
+ * import { schema } from './env'
76
+ * import { generateExample } from 'envx'
77
+ * fs.writeFileSync('.env.example', generateExample(schema))
78
+ * ```
79
+ */
80
+ function generateExample(schema) {
81
+ const lines = [
82
+ '# Auto-generated by envx — do not commit real secrets',
83
+ '',
84
+ ];
85
+ for (const [field, spec] of Object.entries(schema)) {
86
+ if (spec._description) {
87
+ lines.push(`# ${spec._description}`);
88
+ }
89
+ let value;
90
+ if (spec._secret) {
91
+ value = '[secret]';
92
+ }
93
+ else if (spec._default !== undefined) {
94
+ value = String(spec._default);
95
+ }
96
+ else {
97
+ value = '';
98
+ }
99
+ lines.push(`${field}=${value}`);
100
+ }
101
+ return lines.join('\n') + '\n';
102
+ }
103
+ // ---------------------------------------------------------------------------
104
+ // validateEnvFile
105
+ // ---------------------------------------------------------------------------
106
+ /**
107
+ * Given the parsed key=value pairs from a `.env` file and a schema, returns
108
+ * any validation errors without throwing. Useful in CI/pre-deploy checks.
109
+ */
110
+ function validateEnvFile(parsed, schema) {
111
+ const errors = [];
112
+ for (const [field, spec] of Object.entries(schema)) {
113
+ const raw = parsed[field];
114
+ if (raw === undefined || raw === '') {
115
+ if (spec._default !== undefined || !spec._required)
116
+ continue;
117
+ errors.push({ field, message: 'is required but missing', received: undefined });
118
+ continue;
119
+ }
120
+ try {
121
+ const parsed2 = spec._parse(raw, field);
122
+ spec._validate(parsed2, field);
123
+ }
124
+ catch (e) {
125
+ errors.push({
126
+ field,
127
+ message: e instanceof Error ? e.message : String(e),
128
+ received: spec._secret ? '[secret]' : raw,
129
+ });
130
+ }
131
+ }
132
+ return errors;
133
+ }
134
+ //# sourceMappingURL=core.js.map