node-env-resolver 2.0.1 → 3.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.
Files changed (56) hide show
  1. package/README.md +418 -91
  2. package/dist/advanced-features.test.d.ts +2 -0
  3. package/dist/advanced-features.test.d.ts.map +1 -0
  4. package/dist/audit.js +1 -1
  5. package/dist/builder.d.ts +1 -1
  6. package/dist/builder.d.ts.map +1 -1
  7. package/dist/builder.js +1 -1
  8. package/dist/chunk-476ZUILE.js +1 -0
  9. package/dist/chunk-DAGPFV3V.js +1 -0
  10. package/dist/chunk-MGTYH57K.js +9 -0
  11. package/dist/chunk-MWG7FWHN.js +5 -0
  12. package/dist/chunk-QWDK3BUB.js +15 -0
  13. package/dist/chunk-VJZZNSRI.js +1 -0
  14. package/dist/cli.d.ts +49 -0
  15. package/dist/cli.d.ts.map +1 -0
  16. package/dist/cli.js +1 -0
  17. package/dist/cli.test.d.ts +2 -0
  18. package/dist/cli.test.d.ts.map +1 -0
  19. package/dist/computed.test.d.ts +2 -0
  20. package/dist/computed.test.d.ts.map +1 -0
  21. package/dist/index.d.ts +2 -4
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +1 -5
  24. package/dist/nested.test.d.ts +2 -0
  25. package/dist/nested.test.d.ts.map +1 -0
  26. package/dist/resolver.d.ts.map +1 -1
  27. package/dist/resolver.js +1 -9
  28. package/dist/resolvers.d.ts +129 -0
  29. package/dist/resolvers.d.ts.map +1 -1
  30. package/dist/resolvers.js +1 -3
  31. package/dist/type-inference.test.d.ts +2 -0
  32. package/dist/type-inference.test.d.ts.map +1 -0
  33. package/dist/types.d.ts +95 -4
  34. package/dist/types.d.ts.map +1 -1
  35. package/dist/utils.d.ts +168 -0
  36. package/dist/utils.d.ts.map +1 -1
  37. package/dist/utils.js +1 -1
  38. package/dist/valibot.d.ts +153 -0
  39. package/dist/valibot.d.ts.map +1 -0
  40. package/dist/valibot.js +1 -0
  41. package/dist/validation-types.d.ts +28 -0
  42. package/dist/validation-types.d.ts.map +1 -0
  43. package/dist/validation-types.js +0 -0
  44. package/dist/validators.d.ts +22 -2
  45. package/dist/validators.d.ts.map +1 -1
  46. package/dist/validators.js +1 -1
  47. package/dist/web.d.ts +1 -1
  48. package/dist/web.d.ts.map +1 -1
  49. package/dist/web.js +4 -4
  50. package/dist/zod.d.ts +18 -65
  51. package/dist/zod.d.ts.map +1 -1
  52. package/dist/zod.js +1 -1
  53. package/package.json +21 -16
  54. package/dist/standard-schema.d.ts +0 -32
  55. package/dist/standard-schema.d.ts.map +0 -1
  56. package/dist/standard-schema.js +0 -3
package/README.md CHANGED
@@ -4,7 +4,7 @@ Type-safe environment variable resolution with zero dependencies and ultra-small
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/node-env-resolver)](https://www.npmjs.com/package/node-env-resolver)
6
6
 
7
- **Bundle Size:** ~6KB gzipped (includes all validators)
7
+ **Bundle Size:** ~3.6KB gzipped
8
8
 
9
9
  ## Install
10
10
 
@@ -19,14 +19,14 @@ import { resolve } from 'node-env-resolver';
19
19
 
20
20
  const config = resolve({
21
21
  PORT: 3000,
22
- DATABASE_URL: 'postgres',
22
+ NODE_ENV: ['development', 'production', 'test'] as const,
23
23
  DEBUG: false,
24
24
  API_KEY: 'string?'
25
25
  });
26
26
 
27
27
  // config is fully typed
28
28
  config.PORT; // number
29
- config.DATABASE_URL; // verified postgres connection string
29
+ config.NODE_ENV; // 'development' | 'production' | 'test'
30
30
  config.DEBUG; // boolean
31
31
  config.API_KEY; // string | undefined
32
32
  ```
@@ -34,22 +34,46 @@ config.API_KEY; // string | undefined
34
34
  ## Quick start (async)
35
35
 
36
36
  ```ts
37
- import { resolve } from 'node-env-resolver';
37
+ import { resolve, processEnv } from 'node-env-resolver';
38
38
 
39
- const config = await resolve.with([asyncEnvProvider(),{
39
+ const config = await resolve.with([processEnv(), {
40
40
  PORT: 3000,
41
- DATABASE_URL: 'postgres',
41
+ NODE_ENV: ['development', 'production', 'test'] as const,
42
42
  DEBUG: false,
43
43
  API_KEY: 'string?'
44
44
  }]);
45
45
 
46
46
  // config is fully typed
47
47
  config.PORT; // number
48
- config.DATABASE_URL; // verified postgres connection string
48
+ config.NODE_ENV; // 'development' | 'production' | 'test'
49
49
  config.DEBUG; // boolean
50
50
  config.API_KEY; // string | undefined
51
51
  ```
52
52
 
53
+ ## Table of Contents
54
+
55
+ - [Install](#install)
56
+ - [Quick start](#quick-start-uses-processenv)
57
+ - [Basic usage](#basic-usage)
58
+ - [Required values](#required-values)
59
+ - [Default values](#default-values)
60
+ - [Optional values](#optional-values)
61
+ - [Enums](#enums)
62
+ - [Performance & Bundle Size](#performance--bundle-size)
63
+ - [Built-in validators](#built-in-validators)
64
+ - [Custom validators](#custom-validators)
65
+ - [Multiple sources](#multiple-sources)
66
+ - [Safe error handling](#safe-error-handling)
67
+ - [Synchronous resolution](#synchronous-resolution)
68
+ - [Advanced features](#advanced-features)
69
+ - [API Reference](#api-reference)
70
+ - [Configuration Options](#configuration-options)
71
+ - [Framework examples](#framework-examples)
72
+ - [Security Policies](#security-policies)
73
+ - [Audit Logging](#audit-logging)
74
+ - [Error messages](#error-messages)
75
+ - [Licence](#licence)
76
+
53
77
  ## Basic usage
54
78
 
55
79
  ### Required values
@@ -58,8 +82,8 @@ If an environment variable is missing and has no default, validation fails:
58
82
 
59
83
  ```ts
60
84
  const config = resolve({
61
- DATABASE_URL: 'url', // Required
62
- API_KEY: 'string' // Required
85
+ DATABASE_URL: 'postgres', // Required PostgreSQL URL
86
+ API_KEY: 'string' // Required
63
87
  });
64
88
  ```
65
89
 
@@ -104,36 +128,32 @@ config.LOG_LEVEL; // 'debug' | 'info' | 'warn' | 'error'
104
128
 
105
129
  ## Performance & Bundle Size
106
130
 
107
- **Ultra-lightweight and optimized.** The library uses intelligent validation strategies to minimize bundle size:
131
+ **Lightweight with powerful features.** The core library is **~3.6KB gzipped** with comprehensive validation and resolver capabilities - **38% smaller** than previous versions while maintaining all features.
108
132
 
109
- ### Inline validation for basic types
133
+ ### Efficient validation architecture
110
134
 
111
- Common types use **inline validation** with zero external dependencies:
135
+ The library uses a two-tier validation strategy with lazy-loaded validators:
136
+
137
+ **Basic types** (~3.6KB core - inline validation):
112
138
  - `string`, `number`, `boolean` (with min/max validation)
113
139
  - `enum` (array validation)
114
140
  - `pattern` (regex validation)
115
141
  - `custom` (validator functions)
116
142
 
117
- ```ts
118
- // Minimal overhead for basic validation
119
- const config = resolve({
120
- PORT: 3000,
121
- DEBUG: false,
122
- NODE_ENV: ['development', 'production'] as const,
123
- API_KEY: 'string'
124
- });
125
- ```
126
-
127
- ### All types work synchronously
143
+ **Advanced types** (+1KB when used - lazy-loaded):
144
+ - Database URLs: `postgres`, `mysql`, `mongodb`, `redis`
145
+ - Web types: `http`, `https`, `url`, `email`
146
+ - Format types: `json`, `date`, `timestamp`, `port`
128
147
 
129
- All validator types (including advanced ones) work in both synchronous and asynchronous contexts:
148
+ Advanced validators are lazy-loaded only when you use them, keeping the base bundle minimal. All types work both synchronously and asynchronously:
130
149
 
131
150
  ```ts
132
151
  // Synchronous - works with all types
133
152
  const config = resolve({
153
+ PORT: 3000,
134
154
  DATABASE_URL: 'postgres',
135
155
  API_URL: 'url',
136
- PORT: 'port:3000'
156
+ NODE_ENV: ['development', 'production'] as const
137
157
  });
138
158
 
139
159
  // Also works with async resolvers
@@ -143,37 +163,66 @@ const config = await resolve.with([
143
163
  ]);
144
164
  ```
145
165
 
166
+ ### What's in the 3.6KB core?
167
+ - Core resolver logic (async/sync resolution)
168
+ - Schema normalization & type coercion
169
+ - Basic validation (string, number, boolean, enum, pattern, custom)
170
+ - Interpolation & policy checking
171
+ - Provenance tracking & error handling
172
+
173
+ ### Code Splitting Architecture
174
+ The library uses intelligent code splitting to keep the core minimal:
175
+ - **Advanced validators** (~1KB): Lazy-loaded when using types like `url`, `email`, `postgres`
176
+ - **Audit logging** (~150 bytes): Lazy-loaded when `enableAudit: true`
177
+ - **dotenv parser** (~1.6KB): Separate import from `'node-env-resolver/resolvers'`
178
+ - **Utility functions** (~1KB): Separate import from `'node-env-resolver/utils'`
179
+
180
+ Only the code you actually use gets loaded!
181
+
146
182
  ### Audit Logging (Lazy Loaded)
147
183
 
148
- Audit logging is **only loaded when enabled**:
184
+ Audit logging is lazy-loaded only when enabled, keeping the base bundle minimal:
149
185
 
150
186
  ```ts
151
- // Audit module not loaded
187
+ // Base bundle
152
188
  const config = resolve({ PORT: 3000 });
153
189
 
154
- // Audit loaded when enabled
190
+ // Audit module loaded when enabled
155
191
  const config = resolve({ PORT: 3000 }, { enableAudit: true });
156
192
  ```
157
193
 
158
- ### Tree-Shaking Friendly
194
+ ### Optimized Module Structure
159
195
 
160
- The library uses ES modules for optimal tree-shaking:
196
+ Import only what you need for optimal bundle size:
161
197
 
162
198
  ```ts
163
- // Your bundle only includes what you import
164
- import { resolve } from 'node-env-resolver'; // ✅ Core functionality
199
+ // Core (~3.6KB) - Main API
200
+ import { resolve, safeResolve, processEnv } from 'node-env-resolver';
201
+
202
+ // Resolvers (separate chunk) - .env file parsing
203
+ import { dotenv } from 'node-env-resolver/resolvers';
204
+
205
+ // Utils (separate chunk) - caching & retry logic
206
+ import { cached, retry, TTL, awsCache } from 'node-env-resolver/utils';
165
207
 
166
- import { resolveZod } from 'node-env-resolver/zod'; // ✅ Separate chunk
167
- import { awsSecrets } from 'node-env-resolver-aws'; // ✅ Separate package
208
+ // Validators (separate chunk) - reusable validation functions
209
+ import { validateUrl, validateEmail } from 'node-env-resolver/validators';
210
+
211
+ // Integrations (separate packages)
212
+ import { resolveZod } from 'node-env-resolver/zod';
213
+ import { resolveValibot } from 'node-env-resolver/valibot';
214
+ import { awsSecrets } from 'node-env-resolver-aws';
168
215
  ```
169
216
 
217
+ **Most apps only need the core (~3.6KB)!**
218
+
170
219
  ## Built-in validators
171
220
 
172
221
  All validator types work synchronously and asynchronously.
173
222
 
174
223
  ### Basic types
175
224
 
176
- These types use inline validation with **zero external dependencies**:
225
+ These types use inline validation:
177
226
 
178
227
  - `'string'` - Any string value (with optional `min`/`max` length)
179
228
  - `'number'` - Numeric value (coerced from string, with optional `min`/`max`)
@@ -188,24 +237,80 @@ Advanced validators provide specialized validation and parsing:
188
237
 
189
238
  **Network types:**
190
239
 
191
- - `'url'` - Valid URL (returns URL object)
192
- - `'http'` - HTTP or HTTPS URL
193
- - `'https'` - HTTPS-only URL (strict)
194
- - `'email'` - Email address
240
+ - `'url'` - Valid URL (returns string)
241
+ - `'http'` - HTTP or HTTPS URL (returns string)
242
+ - `'https'` - HTTPS-only URL (returns string)
243
+ - `'email'` - Email address (returns string)
195
244
 
196
245
  **Database connection strings:**
197
246
 
198
- - `'postgres'` or `'postgresql'` - PostgreSQL connection string
199
- - `'mysql'` - MySQL connection string
200
- - `'mongodb'` - MongoDB connection string
201
- - `'redis'` - Redis connection string
247
+ - `'postgres'` or `'postgresql'` - PostgreSQL connection string (returns string)
248
+ - `'mysql'` - MySQL connection string (returns string)
249
+ - `'mongodb'` - MongoDB connection string (returns string)
250
+ - `'redis'` - Redis connection string (returns string)
202
251
 
203
252
  **Format types:**
204
253
 
205
- - `'json'` - JSON value (parsed automatically)
206
- - `'port'` - Port number (1-65535)
207
- - `'date'` - ISO 8601 date string
208
- - `'timestamp'` - Unix timestamp
254
+ - `'json'` - JSON value (returns parsed object/array)
255
+ - `'port'` - Port number (returns number, 1-65535)
256
+ - `'date'` - ISO 8601 date string (returns string)
257
+ - `'timestamp'` - Unix timestamp (returns number)
258
+ - `'duration'` - Time duration like `'5s'`, `'2m'`, `'1h'` (returns milliseconds as number)
259
+ - `'file'` - Read content from file path (returns trimmed file content as string)
260
+
261
+ **Array types:**
262
+
263
+ - `'string[]'` - Array of strings from comma-separated values (returns `string[]`)
264
+ - `'number[]'` - Array of numbers from comma-separated values (returns `number[]`)
265
+ - `'url[]'` - Array of validated URLs from comma-separated values (returns `string[]`)
266
+
267
+ ```ts
268
+ // Array examples
269
+ process.env.TAGS = 'frontend,backend,mobile';
270
+ process.env.PORTS = '3000,8080,9000';
271
+ process.env.ALLOWED_ORIGINS = 'https://app.com,https://api.com';
272
+
273
+ const config = resolve({
274
+ TAGS: 'string[]', // ['frontend', 'backend', 'mobile']
275
+ PORTS: 'number[]', // [3000, 8080, 9000]
276
+ ALLOWED_ORIGINS: 'url[]' // ['https://app.com', 'https://api.com']
277
+ });
278
+
279
+ // Custom separator
280
+ const config = resolve({
281
+ TAGS: { type: 'string[]', separator: '|' } // Use pipe instead of comma
282
+ });
283
+
284
+ // Duration parsing
285
+ process.env.TIMEOUT = '30s';
286
+ process.env.CACHE_TTL = '5m';
287
+ process.env.SESSION_DURATION = '24h';
288
+
289
+ const config = await resolve.with([processEnv(), {
290
+ TIMEOUT: 'duration', // 30000 (milliseconds)
291
+ CACHE_TTL: 'duration', // 300000
292
+ SESSION_DURATION: 'duration' // 86400000
293
+ }]);
294
+
295
+ // File reading (useful for Docker/Kubernetes secrets)
296
+ // Method 1: Explicit path in env var
297
+ process.env.DB_PASSWORD_FILE = '/run/secrets/db_password';
298
+ const config = await resolve.with([processEnv(), {
299
+ DB_PASSWORD_FILE: 'file' // 'my-secret-password' (file content, trimmed)
300
+ }]);
301
+
302
+ // Method 2: Using secretsDir (cleaner for Docker/K8s)
303
+ // Reads from /run/secrets/db_password automatically (key name lowercased)
304
+ const config = await resolve.with([processEnv(), {
305
+ DB_PASSWORD: 'file' // Reads /run/secrets/db_password
306
+ }], { secretsDir: '/run/secrets' });
307
+
308
+ // Per-field secretsDir (overrides global)
309
+ const config = await resolve.with([processEnv(), {
310
+ DB_PASSWORD: { type: 'file', secretsDir: '/custom/secrets' },
311
+ API_KEY: 'file' // Uses global secretsDir
312
+ }], { secretsDir: '/run/secrets' });
313
+ ```
209
314
 
210
315
  All validators automatically handle type coercion from environment variable strings.
211
316
 
@@ -235,12 +340,43 @@ const config = resolve({
235
340
  });
236
341
  ```
237
342
 
343
+ ### Reusing built-in validators
344
+
345
+ For advanced use cases, you can import and compose the built-in validation functions:
346
+
347
+ ```ts
348
+ import { resolve } from 'node-env-resolver';
349
+ import { validateUrl, validateEmail } from 'node-env-resolver/validators';
350
+
351
+ const validateMarketingUrl = (value: string): string => {
352
+ // Reuse built-in URL validator
353
+ const result = validateUrl(value);
354
+ if (!result.valid) {
355
+ throw new Error(result.error || 'Invalid URL');
356
+ }
357
+
358
+ // Add custom business logic
359
+ if (!value.includes('marketing.example.com')) {
360
+ throw new Error('Must be a marketing domain URL');
361
+ }
362
+
363
+ return value;
364
+ };
365
+
366
+ const config = resolve({
367
+ MARKETING_URL: validateMarketingUrl
368
+ });
369
+ ```
370
+
371
+ Available validation functions: `validatePostgres`, `validateMysql`, `validateMongodb`, `validateRedis`, `validateHttp`, `validateHttps`, `validateUrl`, `validateEmail`, `validatePort`, `validateNumber`, `validateBoolean`, `validateJson`, `validateDate`, `validateTimestamp`.
372
+
238
373
  ## Multiple sources
239
374
 
240
375
  Load configuration from multiple sources. By default, later sources override earlier ones:
241
376
 
242
377
  ```ts
243
- import { resolve, processEnv, dotenv } from 'node-env-resolver';
378
+ import { resolve, processEnv } from 'node-env-resolver';
379
+ import { dotenv } from 'node-env-resolver/resolvers';
244
380
 
245
381
  const config = await resolve.with(
246
382
  [processEnv(), {
@@ -248,7 +384,7 @@ const config = await resolve.with(
248
384
  NODE_ENV: ['development', 'production'] as const,
249
385
  }],
250
386
  [dotenv(), {
251
- DATABASE_URL: 'url',
387
+ DATABASE_URL: 'postgres',
252
388
  API_KEY: 'string',
253
389
  }]
254
390
  );
@@ -261,15 +397,15 @@ Use `priority` to control how resolvers merge values:
261
397
  ```ts
262
398
  // priority: 'last' (default) - later resolvers override earlier ones
263
399
  const config = await resolve.with(
264
- [processEnv(), { DATABASE_URL: 'url' }],
265
- [awsSecrets(), { DATABASE_URL: 'url' }]
400
+ [processEnv(), { DATABASE_URL: 'postgres' }],
401
+ [awsSecrets(), { DATABASE_URL: 'postgres' }]
266
402
  // AWS wins
267
403
  );
268
404
 
269
405
  // priority: 'first' - earlier resolvers take precedence
270
406
  const config = await resolve.with(
271
- [dotenv(), { DATABASE_URL: 'url' }],
272
- [awsSecrets(), { DATABASE_URL: 'url' }],
407
+ [dotenv(), { DATABASE_URL: 'postgres' }],
408
+ [awsSecrets(), { DATABASE_URL: 'postgres' }],
273
409
  { priority: 'first' }
274
410
  // dotenv wins
275
411
  );
@@ -287,9 +423,9 @@ When using `priority: 'first'`, resolvers are called sequentially, but execution
287
423
 
288
424
  ```ts
289
425
  const config = await resolve.with(
290
- [dotenv(), { DATABASE_URL: 'url', API_KEY: 'string', PORT: 3000 }],
291
- [awsSecrets(), { DATABASE_URL: 'url', API_KEY: 'string', PORT: 3000 }],
292
- [gcpSecrets(), { DATABASE_URL: 'url', API_KEY: 'string', PORT: 3000 }],
426
+ [dotenv(), { DATABASE_URL: 'postgres', API_KEY: 'string', PORT: 3000 }],
427
+ [awsSecrets(), { DATABASE_URL: 'postgres', API_KEY: 'string', PORT: 3000 }],
428
+ [gcpSecrets(), { DATABASE_URL: 'postgres', API_KEY: 'string', PORT: 3000 }],
293
429
  { priority: 'first' }
294
430
  );
295
431
  // If dotenv() provides all required keys, awsSecrets() and gcpSecrets() are never called!
@@ -312,7 +448,7 @@ When using `priority: 'last'` (the default), all resolvers are called **in paral
312
448
 
313
449
  ```ts
314
450
  const config = await resolve.with(
315
- [awsSecrets(), { DATABASE_URL: 'url' }], // 100ms
451
+ [awsSecrets(), { DATABASE_URL: 'postgres' }], // 100ms
316
452
  [awsParameterStore(), { API_KEY: 'string' }], // 100ms
317
453
  [gcpSecrets(), { JWT_SECRET: 'string' }] // 100ms
318
454
  // Default: priority: 'last'
@@ -337,7 +473,7 @@ import { safeResolve } from 'node-env-resolver';
337
473
 
338
474
  const result = safeResolve({
339
475
  PORT: 'number',
340
- DATABASE_URL: 'url'
476
+ DATABASE_URL: 'postgres'
341
477
  });
342
478
 
343
479
  if (result.success) {
@@ -385,13 +521,114 @@ const config = await resolve.with(
385
521
 
386
522
  ## Advanced features
387
523
 
524
+ ### CLI arguments
525
+
526
+ Parse command-line arguments as environment variables - perfect for CLI tools:
527
+
528
+ ```ts
529
+ import { resolve } from 'node-env-resolver';
530
+ import { cliArgs } from 'node-env-resolver/cli';
531
+
532
+ // $ node app.js --port 8080 --database-url postgres://localhost --verbose
533
+
534
+ const config = await resolve.with(
535
+ [processEnv(), {
536
+ PORT: 3000,
537
+ DATABASE_URL: 'postgres',
538
+ VERBOSE: false
539
+ }],
540
+ [cliArgs(), {
541
+ PORT: 3000,
542
+ DATABASE_URL: 'postgres',
543
+ VERBOSE: false
544
+ }]
545
+ );
546
+
547
+ // config.PORT === 8080 (from CLI)
548
+ // config.DATABASE_URL === 'postgres://localhost' (from CLI)
549
+ // config.VERBOSE === true (from CLI flag)
550
+ ```
551
+
552
+ **Supported formats:**
553
+ - `--key value` → `KEY=value`
554
+ - `--key=value` → `KEY=value`
555
+ - `--flag` → `FLAG=true` (boolean flags)
556
+ - `--kebab-case` → `KEBAB_CASE` (auto-normalization)
557
+
558
+ **Bundle size:** ~500 bytes (lazy-loaded)
559
+
560
+ ### Computed fields
561
+
562
+ Derive properties from resolved configuration:
563
+
564
+ ```ts
565
+ import { resolve } from 'node-env-resolver';
566
+ import { withComputed } from 'node-env-resolver/utils';
567
+
568
+ const config = resolve({
569
+ HOST: 'localhost',
570
+ PORT: 3000,
571
+ SSL_ENABLED: false,
572
+ NODE_ENV: ['development', 'production'] as const
573
+ });
574
+
575
+ // Add computed properties
576
+ const appConfig = withComputed(config, {
577
+ // Build URLs from components
578
+ url: (c) => `${c.SSL_ENABLED ? 'https' : 'http'}://${c.HOST}:${c.PORT}`,
579
+
580
+ // Environment checks
581
+ isProd: (c) => c.NODE_ENV === 'production',
582
+ isDev: (c) => c.NODE_ENV === 'development',
583
+
584
+ // Complex derived config
585
+ serverOptions: (c) => ({
586
+ host: c.HOST,
587
+ port: c.PORT,
588
+ cors: c.NODE_ENV !== 'production',
589
+ compression: c.NODE_ENV === 'production'
590
+ })
591
+ });
592
+
593
+ console.log(appConfig.url); // 'http://localhost:3000'
594
+ console.log(appConfig.isProd); // false
595
+ console.log(appConfig.serverOptions); // { host: 'localhost', ... }
596
+ ```
597
+
598
+ **Common patterns:**
599
+ ```ts
600
+ // Build database connection URLs
601
+ withComputed(config, {
602
+ databaseUrl: (c) =>
603
+ `postgres://${c.DB_USER}:${c.DB_PASSWORD}@${c.DB_HOST}:${c.DB_PORT}/${c.DB_NAME}`
604
+ });
605
+
606
+ // Derive API endpoints
607
+ withComputed(config, {
608
+ endpoints: (c) => ({
609
+ users: `${c.API_BASE_URL}/${c.API_VERSION}/users`,
610
+ posts: `${c.API_BASE_URL}/${c.API_VERSION}/posts`
611
+ })
612
+ });
613
+
614
+ // Feature flags based on environment
615
+ withComputed(config, {
616
+ features: (c) => ({
617
+ analytics: c.ENABLE_ANALYTICS && c.NODE_ENV === 'production',
618
+ debug: c.NODE_ENV === 'development'
619
+ })
620
+ });
621
+ ```
622
+
623
+ **Bundle size:** ~200 bytes (included in utils)
624
+
388
625
  ### Zod integration
389
626
 
390
- Use Zod schemas directly:
627
+ Use Zod schemas for powerful validation:
391
628
 
392
629
  ```ts
393
630
  import { resolveZod } from 'node-env-resolver/zod';
394
- import { z } from 'zod';
631
+ import * as z from 'zod'; // ✅ Recommended import pattern (better tree-shaking)
395
632
 
396
633
  const schema = z.object({
397
634
  PORT: z.coerce.number().default(3000),
@@ -401,12 +638,90 @@ const schema = z.object({
401
638
  });
402
639
 
403
640
  const config = await resolveZod(schema);
641
+ // config.PORT is number, config.DATABASE_URL is string, etc.
642
+ ```
643
+
644
+ **Safe error handling** with field-level errors:
645
+
646
+ ```ts
647
+ import { safeResolveZod } from 'node-env-resolver/zod';
648
+ import * as z from 'zod';
649
+
650
+ const schema = z.object({
651
+ PORT: z.coerce.number(),
652
+ DATABASE_URL: z.string().url()
653
+ });
654
+
655
+ const result = await safeResolveZod(schema);
656
+
657
+ if (result.success) {
658
+ console.log(result.data.PORT);
659
+ } else {
660
+ console.error(result.error); // Summary message
661
+ result.issues.forEach(issue => {
662
+ // Field-level details: path, message, code
663
+ console.log(`${issue.path.join('.')}: ${issue.message}`);
664
+ });
665
+ }
404
666
  ```
405
667
 
406
- Available functions:
668
+ **Available functions:**
407
669
 
408
670
  - `resolveZod()` - Async, throws on error
409
- - `safeResolveZod()` - Async, returns result object
671
+ - `safeResolveZod()` - Async, returns `{ success, data/error, issues }`
672
+ - `resolveSyncZod()` - Sync, throws on error
673
+ - `safeResolveSyncZod()` - Sync, returns `{ success, data/error, issues }`
674
+
675
+ ### Valibot integration
676
+
677
+ Use Valibot for lightweight, modular validation:
678
+
679
+ ```ts
680
+ import { resolveValibot } from 'node-env-resolver/valibot';
681
+ import * as v from 'valibot'; // User imports valibot separately
682
+
683
+ const schema = v.object({
684
+ PORT: v.pipe(v.string(), v.transform(Number)),
685
+ DATABASE_URL: v.pipe(v.string(), v.url()),
686
+ NODE_ENV: v.picklist(['development', 'production', 'test']),
687
+ DEBUG: v.optional(v.pipe(v.string(), v.transform(Boolean))),
688
+ });
689
+
690
+ const config = await resolveValibot(schema);
691
+ ```
692
+
693
+ **Safe error handling** with unified error format:
694
+
695
+ ```ts
696
+ import { safeResolveValibot } from 'node-env-resolver/valibot';
697
+ import * as v from 'valibot';
698
+
699
+ const schema = v.object({
700
+ PORT: v.pipe(v.string(), v.transform(Number)),
701
+ DATABASE_URL: v.pipe(v.string(), v.url())
702
+ });
703
+
704
+ const result = await safeResolveValibot(schema);
705
+
706
+ if (result.success) {
707
+ console.log(result.data.PORT);
708
+ } else {
709
+ console.error(result.error); // Summary message
710
+ result.issues.forEach(issue => {
711
+ // Same format as Zod - consistent across validators!
712
+ console.log(`${issue.path.join('.')}: ${issue.message}`);
713
+ });
714
+ }
715
+ ```
716
+
717
+ **Available functions:**
718
+
719
+ - `resolveValibot()` - Async, throws on error
720
+ - `safeResolveValibot()` - Async, returns `{ success, data/error, issues }`
721
+ - `resolveSyncValibot()` - Sync, throws on error
722
+ - `safeResolveSyncValibot()` - Sync, returns `{ success, data/error, issues }`
723
+
724
+ **Why unified errors?** Switch between Zod and Valibot without changing error handling code!
410
725
 
411
726
  ### Custom resolvers
412
727
 
@@ -425,7 +740,7 @@ const databaseResolver: Resolver = {
425
740
 
426
741
  const config = await resolve.with(
427
742
  [processEnv(), { PORT: 3000 }],
428
- [databaseResolver, { FEATURE_FLAGS: 'json' }]
743
+ [databaseResolver, { API_KEY: 'string' }]
429
744
  );
430
745
  ```
431
746
 
@@ -445,7 +760,7 @@ import { resolveSecrets } from 'node-env-resolver-aws';
445
760
  const config = await resolveSecrets({
446
761
  secretId: 'myapp/secrets'
447
762
  }, {
448
- DATABASE_URL: 'url',
763
+ DATABASE_URL: 'postgres',
449
764
  API_KEY: 'string'
450
765
  });
451
766
  ```
@@ -458,8 +773,8 @@ import { awsSecrets, awsSsm } from 'node-env-resolver-aws';
458
773
 
459
774
  const config = await resolve.with(
460
775
  [processEnv(), { PORT: 3000 }],
461
- [awsSecrets({ secretId: 'app/secrets' }), { DATABASE_URL: 'url' }],
462
- [awsSsm({ path: '/app/config' }), { FEATURE_FLAGS: 'json' }]
776
+ [awsSecrets({ secretId: 'app/secrets' }), { DATABASE_URL: 'postgres' }],
777
+ [awsSsm({ path: '/app/config' }), { API_KEY: 'string' }]
463
778
  );
464
779
  ```
465
780
 
@@ -470,7 +785,8 @@ See the [AWS package documentation](../node-env-resolver-aws/README.md) for deta
470
785
  Cache expensive operations like AWS API calls:
471
786
 
472
787
  ```ts
473
- import { resolve, cached, TTL } from 'node-env-resolver';
788
+ import { resolve } from 'node-env-resolver';
789
+ import { cached, TTL } from 'node-env-resolver/utils';
474
790
  import { awsSecrets } from 'node-env-resolver-aws';
475
791
 
476
792
  export const getConfig = async () => {
@@ -479,7 +795,7 @@ export const getConfig = async () => {
479
795
  awsSecrets({ secretId: 'app/secrets' }),
480
796
  { ttl: TTL.minutes5 }
481
797
  ), {
482
- DATABASE_URL: 'url',
798
+ DATABASE_URL: 'postgres',
483
799
  API_KEY: 'string',
484
800
  }]
485
801
  );
@@ -514,17 +830,24 @@ Performance:
514
830
 
515
831
  | Syntax | Type | Description |
516
832
  |--------|------|-------------|
517
- | `'string'` | `string` | Required string |
833
+ | `'string'` | `string` | Required string (empty strings rejected by default) |
518
834
  | `'string?'` | `string \| undefined` | Optional string |
519
- | `'number'` | `number` | Required number |
835
+ | `'number'` | `number` | Required number (coerced from string) |
520
836
  | `'number?'` | `number \| undefined` | Optional number |
521
- | `'boolean'` | `boolean` | Required boolean |
837
+ | `'boolean'` | `boolean` | Required boolean (coerced from string) |
522
838
  | `'boolean?'` | `boolean \| undefined` | Optional boolean |
523
- | `'url'` | `string` | Valid URL |
524
- | `'email'` | `string` | Email address |
525
- | `'port'` | `number` | Port (1-65535) |
526
- | `'json'` | `unknown` | Parsed JSON |
527
- | `'postgres'` | `string` | PostgreSQL connection string |
839
+ | `'string[]'` | `string[]` | Array of strings (comma-separated) |
840
+ | `'number[]'` | `number[]` | Array of numbers (comma-separated) |
841
+ | `'url[]'` | `string[]` | Array of validated URLs |
842
+ | `'url'` | `string` | Validated URL (returns string) |
843
+ | `'email'` | `string` | Validated email address |
844
+ | `'port'` | `number` | Validated port number (1-65535) |
845
+ | `'json'` | `unknown` | Parsed JSON (returns object/array) |
846
+ | `'postgres'` | `string` | Validated PostgreSQL URL |
847
+ | `'date'` | `string` | Validated ISO 8601 date |
848
+ | `'timestamp'` | `number` | Validated Unix timestamp |
849
+ | `'duration'` | `number` | Time duration (`5s`, `2m`, `1h` → milliseconds) |
850
+ | `'file'` | `string` | Read content from file path |
528
851
  | `3000` | `number` | Number with default |
529
852
  | `false` | `boolean` | Boolean with default |
530
853
  | `['a', 'b']` | `'a' \| 'b'` | Enum (requires `as const`) |
@@ -640,15 +963,15 @@ await resolve.with(
640
963
  ```ts
641
964
  // Production: AWS secrets override process.env
642
965
  await resolve.with(
643
- [processEnv(), { DATABASE_URL: 'url' }],
644
- [awsSecrets(), { DATABASE_URL: 'url' }]
966
+ [processEnv(), { DATABASE_URL: 'postgres' }],
967
+ [awsSecrets(), { DATABASE_URL: 'postgres' }]
645
968
  // priority: 'last' (default) - AWS wins
646
969
  );
647
970
 
648
971
  // Development: Local .env overrides cloud
649
972
  await resolve.with(
650
- [dotenv(), { DATABASE_URL: 'url' }],
651
- [awsSecrets(), { DATABASE_URL: 'url' }],
973
+ [dotenv(), { DATABASE_URL: 'postgres' }],
974
+ [awsSecrets(), { DATABASE_URL: 'postgres' }],
652
975
  { priority: 'first' } // dotenv wins
653
976
  );
654
977
  ```
@@ -725,6 +1048,7 @@ interface ResolveOptions {
725
1048
  priority?: 'first' | 'last'; // Merge strategy (default: 'last')
726
1049
  policies?: PolicyOptions; // Security policies (default: undefined)
727
1050
  enableAudit?: boolean; // Audit logging (default: auto in production)
1051
+ secretsDir?: string; // Base directory for file secrets (Docker/K8s)
728
1052
  }
729
1053
 
730
1054
  interface PolicyOptions {
@@ -759,7 +1083,7 @@ import { resolve } from 'node-env-resolver/nextjs';
759
1083
 
760
1084
  export const env = resolve({
761
1085
  server: {
762
- DATABASE_URL: 'url',
1086
+ DATABASE_URL: 'postgres',
763
1087
  API_SECRET: 'string',
764
1088
  },
765
1089
  client: {
@@ -771,7 +1095,8 @@ export const env = resolve({
771
1095
  ### AWS Lambda
772
1096
 
773
1097
  ```ts
774
- import { resolve, cached, TTL } from 'node-env-resolver';
1098
+ import { resolve } from 'node-env-resolver';
1099
+ import { cached, TTL } from 'node-env-resolver/utils';
775
1100
  import { awsSecrets } from 'node-env-resolver-aws';
776
1101
 
777
1102
  const getConfig = async () => {
@@ -780,7 +1105,7 @@ const getConfig = async () => {
780
1105
  awsSecrets({ secretId: 'lambda/config' }),
781
1106
  { ttl: TTL.minutes5 }
782
1107
  ), {
783
- DATABASE_URL: 'url',
1108
+ DATABASE_URL: 'postgres',
784
1109
  }]
785
1110
  );
786
1111
  };
@@ -805,7 +1130,7 @@ By default, `.env` files are **completely blocked in production** for security.
805
1130
  // In production (NODE_ENV=production)
806
1131
  const config = await resolve.with(
807
1132
  [dotenv(), {
808
- DATABASE_URL: 'url',
1133
+ DATABASE_URL: 'postgres',
809
1134
  }]
810
1135
  );
811
1136
  // ❌ Throws: "DATABASE_URL cannot be sourced from .env files in production"
@@ -816,7 +1141,7 @@ const config = await resolve.with(
816
1141
  ```ts
817
1142
  const config = await resolve.with(
818
1143
  [dotenv(), {
819
- DATABASE_URL: 'url',
1144
+ DATABASE_URL: 'postgres',
820
1145
  }],
821
1146
  {
822
1147
  policies: {
@@ -832,7 +1157,7 @@ const config = await resolve.with(
832
1157
  const config = await resolve.with(
833
1158
  [dotenv(), {
834
1159
  PORT: 3000,
835
- DATABASE_URL: 'url',
1160
+ DATABASE_URL: 'postgres',
836
1161
  }],
837
1162
  {
838
1163
  policies: {
@@ -874,7 +1199,8 @@ const config = await resolve.with(
874
1199
  **Use case:** Ensure production secrets only come from AWS Secrets Manager, never from `.env` or `process.env`:
875
1200
 
876
1201
  ```ts
877
- import { resolve, processEnv, cached, TTL } from 'node-env-resolver';
1202
+ import { resolve, processEnv } from 'node-env-resolver';
1203
+ import { cached, TTL } from 'node-env-resolver/utils';
878
1204
  import { awsSecrets } from 'node-env-resolver-aws';
879
1205
 
880
1206
  const config = await resolve.with(
@@ -934,7 +1260,7 @@ import { resolve, getAuditLog, clearAuditLog } from 'node-env-resolver';
934
1260
 
935
1261
  // Option 1: Explicitly enable (works in any environment)
936
1262
  const config = resolve({
937
- DATABASE_URL: 'url',
1263
+ DATABASE_URL: 'postgres',
938
1264
  API_KEY: 'string',
939
1265
  }, {
940
1266
  enableAudit: true // ← Enable audit logging
@@ -956,7 +1282,7 @@ clearAuditLog();
956
1282
  process.env.NODE_ENV = 'production';
957
1283
 
958
1284
  const config = resolve({
959
- DATABASE_URL: 'url',
1285
+ DATABASE_URL: 'postgres',
960
1286
  });
961
1287
 
962
1288
  // Audit automatically enabled in production
@@ -978,12 +1304,13 @@ console.log(getAuditLog());
978
1304
  Audit logs include cache metadata to help monitor performance:
979
1305
 
980
1306
  ```ts
981
- import { resolve, cached, getAuditLog } from 'node-env-resolver';
1307
+ import { resolve, getAuditLog } from 'node-env-resolver';
1308
+ import { cached } from 'node-env-resolver/utils';
982
1309
  import { awsSecrets } from 'node-env-resolver-aws';
983
1310
 
984
1311
  const config = await resolve.with(
985
1312
  [cached(awsSecrets({ secretId: 'prod/db' }), { ttl: 300000 }), {
986
- DATABASE_URL: 'url',
1313
+ DATABASE_URL: 'postgres',
987
1314
  }],
988
1315
  { enableAudit: true }
989
1316
  );