node-env-resolver 0.0.0 → 1.1.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.
Files changed (63) hide show
  1. package/README.md +273 -82
  2. package/dist/audit.d.ts +16 -0
  3. package/dist/audit.d.ts.map +1 -0
  4. package/dist/audit.js +1 -0
  5. package/dist/audit.test.d.ts +2 -0
  6. package/dist/audit.test.d.ts.map +1 -0
  7. package/dist/builder.d.ts +146 -0
  8. package/dist/builder.d.ts.map +1 -0
  9. package/dist/builder.js +1 -0
  10. package/dist/composition.test.d.ts +7 -0
  11. package/dist/composition.test.d.ts.map +1 -0
  12. package/dist/index.d.ts +124 -4
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +9 -20
  15. package/dist/index.test.d.ts +2 -0
  16. package/dist/index.test.d.ts.map +1 -0
  17. package/dist/providers.d.ts +11 -0
  18. package/dist/providers.d.ts.map +1 -0
  19. package/dist/resolver.d.ts +17 -0
  20. package/dist/resolver.d.ts.map +1 -0
  21. package/dist/resolver.js +9 -0
  22. package/dist/resolvers.d.ts +11 -0
  23. package/dist/resolvers.d.ts.map +1 -0
  24. package/dist/resolvers.js +3 -0
  25. package/dist/resolvers.test.d.ts +2 -0
  26. package/dist/resolvers.test.d.ts.map +1 -0
  27. package/dist/standard-schema.d.ts +32 -0
  28. package/dist/standard-schema.d.ts.map +1 -0
  29. package/dist/standard-schema.js +3 -0
  30. package/dist/type-override.test.d.ts +2 -0
  31. package/dist/type-override.test.d.ts.map +1 -0
  32. package/dist/types.d.ts +67 -0
  33. package/dist/types.d.ts.map +1 -0
  34. package/dist/types.js +0 -0
  35. package/dist/utils.d.ts +41 -0
  36. package/dist/utils.d.ts.map +1 -0
  37. package/dist/utils.js +1 -0
  38. package/dist/utils.test.d.ts +2 -0
  39. package/dist/utils.test.d.ts.map +1 -0
  40. package/dist/validators.d.ts +68 -0
  41. package/dist/validators.d.ts.map +1 -0
  42. package/dist/validators.js +1 -0
  43. package/dist/web.d.ts +51 -0
  44. package/dist/web.d.ts.map +1 -0
  45. package/dist/web.js +6 -0
  46. package/dist/zod.d.ts +51 -0
  47. package/dist/zod.d.ts.map +1 -0
  48. package/dist/zod.js +1 -0
  49. package/package.json +88 -28
  50. package/dist/chunk-AST3HVOG.js +0 -148
  51. package/dist/chunk-UQYMDWOU.js +0 -13
  52. package/dist/chunk-XC5PWSNR.js +0 -37
  53. package/dist/esm/chunk-AST3HVOG.js +0 -144
  54. package/dist/esm/chunk-UQYMDWOU.js +0 -11
  55. package/dist/esm/chunk-XC5PWSNR.js +0 -35
  56. package/dist/esm/index.js +0 -3
  57. package/dist/esm/resolve.js +0 -2
  58. package/dist/esm/resolveZod.js +0 -2
  59. package/dist/index-6c4171f8.d.ts +0 -27
  60. package/dist/resolve.d.ts +0 -6
  61. package/dist/resolve.js +0 -15
  62. package/dist/resolveZod.d.ts +0 -7
  63. package/dist/resolveZod.js +0 -15
package/README.md CHANGED
@@ -1,148 +1,339 @@
1
1
  # node-env-resolver
2
2
 
3
- This package provides an easy way to resolve environment variables for Node.js applications.
3
+ Type-safe environment variable handling with zero dependencies.
4
4
 
5
- All you need to do is provide the names of the environment variables you want to resolve, an object with defaults and the package will do the rest.
5
+ [![npm version](https://img.shields.io/npm/v/node-env-resolver)](https://www.npmjs.com/package/node-env-resolver)
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install node-env-resolver
11
+ ```
12
+
13
+ ## Quick start
6
14
 
7
15
  ```ts
8
16
  import { resolve } from 'node-env-resolver';
9
17
 
10
- // using array of environment variables
11
- const resolvedEnvs = await resolve([
12
- 'NODE_ENV',
13
- 'PORT',
14
- 'DATABASE_URL',
15
- 'REDIS_URL',
16
- ]);
17
-
18
- // using object with default values
19
- const resolvedEnvs = await resolve({
20
- NODE_ENV: 'local',
18
+ const config = await resolve({
21
19
  PORT: 3000,
22
- DATABASE_URL: 'postgres://localhost:5432/mydb',
23
- REDIS_URL: '',
20
+ DATABASE_URL: 'url',
21
+ DEBUG: false,
22
+ API_KEY: 'string?'
24
23
  });
24
+
25
+ // All typed correctly
26
+ config.PORT; // number
27
+ config.DATABASE_URL; // URL object
28
+ config.DEBUG; // boolean
29
+ config.API_KEY; // string | undefined
25
30
  ```
26
31
 
27
- will both return an object with the following structure:
32
+ ## Features
28
33
 
29
- ```json
30
- {
31
- "NODE_ENV": "local",
32
- "PORT": 3000,
33
- "DATABASE_URL": "postgres://localhost:5432/mydb",
34
- "REDIS_URL": "redis://localhost:6379"
35
- }
36
- ```
34
+ - Zero runtime dependencies
35
+ - Full TypeScript type inference
36
+ - Custom validation functions
37
+ - Standard Schema compliant
38
+ - Works with any Node.js application
37
39
 
38
- The library also supports Zod Schemas. If you provide a Zod Schema, the package will validate the resolved environment variables against the schema and throw an error if any of the environment variables are invalid.
40
+ ## Built-in validators
39
41
 
40
- ```ts
41
- const resolvedEnvs = await resolveZod(
42
- z.object({
43
- NODE_ENV: z.string().default('local'),
44
- PORT: z.coerce.number().default(3000),
45
- DATABASE_URL: z.string().url().default('postgres://localhost:5432/mydb'),
46
- REDIS_URL: z.string().url().default('redis://localhost:6379'),
47
- })
48
- );
49
- ```
42
+ The library includes validators for common use cases:
50
43
 
51
- ## Installation
44
+ - **Basic**: `string`, `number`, `boolean`, `json`, `port`
45
+ - **Network**: `url`, `http`, `https`, `email`
46
+ - **Database**: `postgres`, `mysql`, `mongodb`, `redis`
52
47
 
53
- ```sh
54
- npm install node-env-resolver
48
+ ## Usage
49
+
50
+ ### Simple schema
51
+
52
+ ```ts
53
+ import { resolve } from 'node-env-resolver';
54
+
55
+ const config = await resolve({
56
+ PORT: 3000,
57
+ NODE_ENV: ['development', 'production'] as const,
58
+ DATABASE_URL: 'postgres',
59
+ DEBUG: false
60
+ });
55
61
  ```
56
62
 
57
- ## Usage
63
+ ### Optional values
64
+
65
+ Add `?` to make a value optional:
58
66
 
59
- By default the package will resolve the following environment variables from process.env.
67
+ ```ts
68
+ const config = await resolve({
69
+ API_KEY: 'string?',
70
+ REDIS_URL: 'url?'
71
+ });
72
+ ```
60
73
 
61
- You can configure and add additional resolvers in the second argument of the resolve function.
74
+ ### Custom validators
62
75
 
63
- The default value of this argument is `local` which uses an in-built resolver that resolves environment variables from process.env.
76
+ Write your own validation functions:
64
77
 
65
78
  ```ts
66
- const resolvedEnvs = await resolve(['PORT'], 'local');
79
+ const portValidator = (value: string): number => {
80
+ const port = parseInt(value, 10);
81
+ if (isNaN(port) || port < 1 || port > 65535) {
82
+ throw new Error('Port must be between 1 and 65535');
83
+ }
84
+ return port;
85
+ };
86
+
87
+ const config = await resolve({
88
+ CUSTOM_PORT: portValidator,
89
+ DATABASE_URL: 'postgres'
90
+ });
67
91
  ```
68
92
 
69
- Environmental variables are resolved in the order of the resolvers provided in the second argument.
93
+ ### Multiple sources
70
94
 
71
- For example, if you provide `['local', 'aws-secrets']` as the second argument, the package will first resolve the environment variables from process.env and then from AWS Secrets Manager.
95
+ Load from different sources with explicit mapping:
72
96
 
73
- Values resolved from AWS Secrets Manager will override the values resolved from process.env.
97
+ ```ts
98
+ import { resolve, processEnv, dotenv } from 'node-env-resolver';
99
+
100
+ const config = await resolve.with(
101
+ [processEnv(), {
102
+ PORT: 3000,
103
+ NODE_ENV: ['development', 'production'] as const,
104
+ }],
105
+ [dotenv(), {
106
+ DATABASE_URL: 'postgres',
107
+ API_KEY: 'string',
108
+ }]
109
+ );
110
+ ```
74
111
 
75
- ### Adding a custom resolver
112
+ Later sources override earlier ones if there are conflicts.
76
113
 
77
- You can add a custom resolver by providing a function that returns a promise that resolves to an object with the resolved environment variables.
114
+ ### Safe resolve (Zod-like pattern)
115
+
116
+ Like Zod's `parse()` vs `safeParse()`, choose between throwing errors or getting result objects:
78
117
 
79
118
  ```ts
80
- async function customResolver(): EnvValues {
81
- return Promise.resolve({
82
- FOO: 'bar',
83
- QUZ: 'quux',
119
+ import { resolve, safeResolve } from 'node-env-resolver';
120
+
121
+ // ❌ Throws on validation failure (like Zod's parse())
122
+ try {
123
+ const config = await resolve({
124
+ PORT: 'number',
125
+ DATABASE_URL: 'postgres',
84
126
  });
127
+ console.log(config.PORT);
128
+ } catch (error) {
129
+ console.error(error.message);
85
130
  }
86
131
 
87
- const resolvedEnvs = await resolve(['FOO', 'QUZ'], customResolver);
132
+ // ✅ Returns result object (like Zod's safeParse())
133
+ const result = await safeResolve({
134
+ PORT: 'number',
135
+ DATABASE_URL: 'postgres',
136
+ });
137
+
138
+ if (result.success) {
139
+ console.log('Port:', result.data.PORT);
140
+ // result.data is fully typed
141
+ } else {
142
+ console.error('Failed:', result.error);
143
+ }
88
144
  ```
89
145
 
90
- which will return an object with the following structure:
146
+ **All variants:**
91
147
 
92
- ```json
93
- {
94
- "FOO": "bar",
95
- "QUZ": "quux"
148
+ | Function | Behavior | Use case |
149
+ |----------|----------|----------|
150
+ | `resolve()` | Throws on error | Simple apps, fail-fast |
151
+ | `safeResolve()` | Returns `{ success, data?, error? }` | Graceful error handling |
152
+ | `resolveSync()` | Sync, throws on error | Sync config loading |
153
+ | `safeResolveSync()` | Sync, returns result object | Sync with error handling |
154
+
155
+ All functions support `.with()` for multiple sources:
156
+
157
+ ```ts
158
+ const result = await safeResolve.with(
159
+ [processEnv(), { PORT: 3000 }],
160
+ [awsSecrets(), { API_KEY: 'string' }]
161
+ );
162
+
163
+ if (!result.success) {
164
+ console.error(result.error);
165
+ process.exit(1);
96
166
  }
97
167
  ```
98
168
 
99
- ### AWS Secrets Manager
169
+ ### With caching
100
170
 
101
- It also has in-built support for the resolving environment variables from aws-secrets-manager.
171
+ Add TTL caching for remote sources:
102
172
 
103
173
  ```ts
104
- import { resolve } from 'node-env-resolver';
105
- const resolvedEnvs = await resolve(
106
- ['NODE_ENV', 'PORT', 'DATABASE_URL', 'REDIS_URL'],
107
- 'aws-secrets'
174
+ import { resolve, cached, TTL } from 'node-env-resolver';
175
+
176
+ const config = await resolve.with(
177
+ [processEnv(), { PORT: 3000 }],
178
+ [cached(customProvider, { ttl: TTL.minutes5 }), {
179
+ API_KEY: 'string',
180
+ }]
108
181
  );
109
182
  ```
110
183
 
111
- In this case the package expects to use aws credentials from the environment variables `AWS_DEFAULT_REGION`, `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`.
184
+ ## API
185
+
186
+ ### Shorthand syntax
112
187
 
113
- In addition you need to provide the id of the secret in AWS Secrets Manager that contains the environment variables you want to resolve using the environmental variable `AWS_SECRET_ID`.
188
+ ```ts
189
+ 'string' // Required string
190
+ 'string?' // Optional string
191
+ 'url' // URL (returns URL object)
192
+ 'email' // Email address
193
+ 'port' // Port number (1-65535)
194
+ 'json' // JSON value
195
+ 'postgres' // PostgreSQL connection string
196
+ 'mysql' // MySQL connection string
197
+ 'mongodb' // MongoDB connection string
198
+ 'redis' // Redis connection string
199
+
200
+ // Defaults
201
+ 3000 // number with default
202
+ false // boolean with default
203
+ ['dev', 'prod'] as const // enum (requires 'as const')
204
+ ```
114
205
 
115
- ### Mixing and matching resolver types
206
+ ### Object syntax
116
207
 
117
- You can mix and match the resolver types.
208
+ For advanced validation:
118
209
 
119
210
  ```ts
120
- async function customResolver(): EnvValues {
121
- return Promise.resolve({
122
- FOO: 'bar',
123
- QUZ: 'quux',
124
- });
211
+ {
212
+ type: 'string',
213
+ pattern: '^sk_[a-zA-Z0-9]+$',
214
+ min: 32,
215
+ max: 64,
216
+ optional: true,
217
+ description: 'API key'
125
218
  }
219
+ ```
220
+
221
+ ### Options
126
222
 
127
- const resolvedEnvs = await resolve(['FOO', 'QUZ'], ['local', customResolver]);
223
+ ```ts
224
+ await resolve(schema, {
225
+ resolvers: [customResolver], // Custom resolvers
226
+ extend: [awsSecrets()], // Extend default resolvers
227
+ strict: true, // Strict mode
228
+ enableAudit: true, // Audit logging
229
+ policies: { // Security policies
230
+ enforceAllowedSources: {
231
+ DATABASE_URL: ['aws-secrets']
232
+ }
233
+ }
234
+ });
128
235
  ```
129
236
 
130
- This will first resolve the environment variables from process.env and then from the custom resolver.
237
+ ### Built-in resolvers
131
238
 
132
- ### Options
239
+ ```ts
240
+ import { dotenv, processEnv } from 'node-env-resolver';
133
241
 
134
- The third argument of the resolve function is an options object.
242
+ // Load from .env files
243
+ dotenv({ path: '.env', expand: true })
244
+
245
+ // Load from process.env
246
+ processEnv()
247
+ ```
248
+
249
+ ### Utility resolvers
135
250
 
136
251
  ```ts
137
- {
138
- strict?: boolean;
252
+ import { cached, retry, TTL } from 'node-env-resolver';
253
+
254
+ // Cache with TTL
255
+ cached(resolver, { ttl: 300 })
256
+
257
+ // Retry on failure
258
+ retry(resolver, { attempts: 3 })
259
+
260
+ // TTL constants
261
+ TTL.minute // 60
262
+ TTL.minutes5 // 300
263
+ TTL.hour // 3600
264
+ TTL.day // 86400
265
+ ```
266
+
267
+ ## Examples
268
+
269
+ ### Express app
270
+
271
+ ```ts
272
+ import { resolve } from 'node-env-resolver';
273
+
274
+ const config = await resolve({
275
+ PORT: 3000,
276
+ NODE_ENV: ['development', 'production', 'test'] as const,
277
+ DATABASE_URL: 'postgres',
278
+ REDIS_URL: 'redis?',
279
+ JWT_SECRET: 'string',
280
+ JWT_EXPIRES_IN: '7d',
281
+ ENABLE_ANALYTICS: false
282
+ });
283
+
284
+ app.listen(config.PORT, () => {
285
+ console.log(`Server running on port ${config.PORT}`);
286
+ });
287
+ ```
288
+
289
+ ### AWS Lambda
290
+
291
+ ```ts
292
+ import { resolve } from 'node-env-resolver';
293
+ import { awsSecrets } from 'node-env-resolver-aws';
294
+
295
+ const config = await resolve({
296
+ API_ENDPOINT: 'url',
297
+ TIMEOUT: 30,
298
+ LOG_LEVEL: ['debug', 'info', 'warn', 'error'] as const
299
+ }, {
300
+ extend: [awsSecrets({ secretId: 'lambda/secrets' })]
301
+ });
302
+
303
+ export const handler = async (event) => {
304
+ // Use config values
139
305
  };
140
306
  ```
141
307
 
142
- By default the package will throw an error if any of the environment variables are not found.
308
+ ## Error messages
309
+
310
+ The library provides clear, actionable error messages:
311
+
312
+ ```
313
+ ❌ Environment validation failed:
314
+ - Missing required environment variable: DATABASE_URL
315
+ - PORT: Invalid port number (1-65535)
316
+ - NODE_ENV: must be one of: development, production (got: "staging")
317
+ ```
318
+
319
+ ## TypeScript support
143
320
 
144
- You can disable this behaviour by setting the `strict` option to `false`.
321
+ Full type inference works automatically:
145
322
 
146
323
  ```ts
147
- const resolvedEnvs = await resolve(['FOO', 'QUZ'], 'local', { strict: false });
324
+ const config = await resolve({
325
+ PORT: 3000,
326
+ DATABASE_URL: 'url',
327
+ NODE_ENV: ['dev', 'prod'] as const,
328
+ DEBUG: false
329
+ });
330
+
331
+ config.PORT.toFixed(2); // ✓ number
332
+ config.DATABASE_URL.protocol; // ✓ URL object
333
+ config.NODE_ENV === 'dev'; // ✓ 'dev' | 'prod'
334
+ config.DEBUG ? 'yes' : 'no'; // ✓ boolean
148
335
  ```
336
+
337
+ ## License
338
+
339
+ MIT © [Jagvinder Singh Reehal](https://jagreehal.com)
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Audit logging for environment variable resolution
3
+ */
4
+ export type AuditEventType = 'validation_success' | 'validation_failure' | 'policy_violation' | 'env_loaded' | 'provider_error' | 'resolver_error';
5
+ export interface AuditEvent {
6
+ type: AuditEventType;
7
+ timestamp: number;
8
+ key?: string;
9
+ source?: string;
10
+ error?: string;
11
+ metadata?: Record<string, unknown>;
12
+ }
13
+ export declare function logAuditEvent(event: AuditEvent): void;
14
+ export declare function getAuditLog(): readonly AuditEvent[];
15
+ export declare function clearAuditLog(): void;
16
+ //# sourceMappingURL=audit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audit.d.ts","sourceRoot":"","sources":["../src/audit.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,MAAM,MAAM,cAAc,GACtB,oBAAoB,GACpB,oBAAoB,GACpB,kBAAkB,GAClB,YAAY,GACZ,gBAAgB,GAChB,gBAAgB,CAAC;AAErB,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,cAAc,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;IAClB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC;AAKD,wBAAgB,aAAa,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI,CAMrD;AAED,wBAAgB,WAAW,IAAI,SAAS,UAAU,EAAE,CAEnD;AAED,wBAAgB,aAAa,IAAI,IAAI,CAEpC"}
package/dist/audit.js ADDED
@@ -0,0 +1 @@
1
+ const t=[];function n(e){t.push(e),t.length>1e3&&t.shift();}function o(){return [...t]}function r(){t.length=0;}export{r as clearAuditLog,o as getAuditLog,n as logAuditEvent};
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=audit.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audit.test.d.ts","sourceRoot":"","sources":["../src/audit.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,146 @@
1
+ /**
2
+ * EnvBuilder - Fluent API for composing environment variables from multiple resolvers
3
+ *
4
+ * @example
5
+ * ```typescript
6
+ * const config = await env({
7
+ * FOO: 'string',
8
+ * BAR: 3000,
9
+ * })
10
+ * .from(customResolver, {
11
+ * QUZ: 'string',
12
+ * })
13
+ * .resolve();
14
+ * ```
15
+ */
16
+ import type { Resolver, SimpleEnvSchema, InferSimpleSchema, ResolveOptions } from './types.js';
17
+ export type MergeSchemas<T, U> = Omit<T, keyof U> & U;
18
+ /**
19
+ * EnvBuilder class - accumulates resolvers and schemas, then resolves
20
+ */
21
+ export declare class EnvBuilder<TAccumulated extends Record<string, unknown>> {
22
+ private localSchema;
23
+ private options;
24
+ private layers;
25
+ constructor(localSchema: SimpleEnvSchema, options?: Partial<ResolveOptions>);
26
+ /**
27
+ * Add a custom provider with its schema
28
+ * Later resolvers override earlier ones (last-wins)
29
+ */
30
+ from<TNew extends SimpleEnvSchema>(resolver: Resolver, schema: TNew): EnvBuilder<MergeSchemas<TAccumulated, InferSimpleSchema<TNew>>>;
31
+ /**
32
+ * Resolve all resolvers and validate environment variables
33
+ */
34
+ resolve(): Promise<TAccumulated>;
35
+ /**
36
+ * Build default resolvers (dotenv + process.env) for local schema
37
+ */
38
+ private buildDefaultResolvers;
39
+ }
40
+ /**
41
+ * Synchronous EnvBuilder - only works with sync-capable resolvers
42
+ */
43
+ export declare class EnvBuilderSync<TAccumulated extends Record<string, unknown>> {
44
+ private localSchema;
45
+ private options;
46
+ private layers;
47
+ constructor(localSchema: SimpleEnvSchema, options?: Partial<ResolveOptions>);
48
+ /**
49
+ * Add a custom provider with its schema (sync version)
50
+ */
51
+ from<TNew extends SimpleEnvSchema>(resolver: Resolver, schema: TNew): EnvBuilderSync<MergeSchemas<TAccumulated, InferSimpleSchema<TNew>>>;
52
+ /**
53
+ * Synchronously resolve all resolvers
54
+ */
55
+ resolveSync(): TAccumulated;
56
+ private buildDefaultResolvers;
57
+ }
58
+ /**
59
+ * Create an environment builder with local schema
60
+ * Use .from() to add custom resolvers, then .resolve() to execute
61
+ *
62
+ * @example
63
+ * ```typescript
64
+ * const config = await env({
65
+ * FOO: 'string',
66
+ * BAR: 3000,
67
+ * })
68
+ * .from(customResolver, { QUZ: 'string' })
69
+ * .resolve();
70
+ * ```
71
+ */
72
+ export declare function env<T extends SimpleEnvSchema>(localSchema: T, options?: Partial<ResolveOptions>): EnvBuilder<InferSimpleSchema<T>>;
73
+ /**
74
+ * Synchronous version of env() - only works with sync-capable resolvers
75
+ *
76
+ * @example
77
+ * ```typescript
78
+ * const config = envSync({
79
+ * FOO: 'string',
80
+ * BAR: 3000,
81
+ * }).resolveSync();
82
+ * ```
83
+ */
84
+ export declare function envSync<T extends SimpleEnvSchema>(localSchema: T, options?: Partial<ResolveOptions>): EnvBuilderSync<InferSimpleSchema<T>>;
85
+ /**
86
+ * ResolvableBuilder - A builder that is both awaitable AND chainable
87
+ * Simple usage: await resolve({...})
88
+ * Composition: await resolve({...}).from(...).compose()
89
+ */
90
+ export declare class ResolvableBuilder<TAccumulated extends Record<string, unknown>> implements PromiseLike<TAccumulated> {
91
+ private builder;
92
+ private simpleResolve;
93
+ constructor(localSchema: SimpleEnvSchema, options?: Partial<ResolveOptions>);
94
+ /**
95
+ * Add a custom provider with its schema
96
+ */
97
+ from<TNew extends SimpleEnvSchema>(resolver: Resolver, schema: TNew): ResolvableBuilder<MergeSchemas<TAccumulated, InferSimpleSchema<TNew>>>;
98
+ /**
99
+ * Terminal operation for composition - resolves all resolvers
100
+ * Only needed when using .from() - otherwise just await directly
101
+ */
102
+ compose(): Promise<TAccumulated>;
103
+ /**
104
+ * Make this object awaitable (PromiseLike)
105
+ * Allows: const config = await resolve({...})
106
+ */
107
+ then<TResult1 = TAccumulated, TResult2 = never>(onfulfilled?: ((value: TAccumulated) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null): PromiseLike<TResult1 | TResult2>;
108
+ /**
109
+ * Catch errors (Promise-like interface)
110
+ */
111
+ catch<TResult = never>(onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null): Promise<TAccumulated | TResult>;
112
+ /**
113
+ * Finally handler (Promise-like interface)
114
+ */
115
+ finally(onfinally?: (() => void) | null): Promise<TAccumulated>;
116
+ }
117
+ /**
118
+ * ResolvableBuilderSync - Synchronous version
119
+ * Returns the resolved value directly, but also chainable
120
+ *
121
+ * The returned object has all properties from TAccumulated plus builder methods
122
+ */
123
+ export declare class ResolvableBuilderSync<TAccumulated extends Record<string, unknown>> {
124
+ private builder;
125
+ private _resolved;
126
+ private _hasComposition;
127
+ constructor(localSchema: SimpleEnvSchema, options?: Partial<ResolveOptions>);
128
+ /**
129
+ * Add a custom provider with its schema
130
+ */
131
+ from<TNew extends SimpleEnvSchema>(resolver: Resolver, schema: TNew): ResolvableBuilderSync<MergeSchemas<TAccumulated, InferSimpleSchema<TNew>>>;
132
+ /**
133
+ * Terminal operation for composition - resolves all resolvers synchronously
134
+ * Only needed when using .from() - otherwise properties are already available
135
+ */
136
+ compose(): TAccumulated;
137
+ /**
138
+ * Convert to plain object
139
+ */
140
+ valueOf(): TAccumulated;
141
+ /**
142
+ * For JSON serialization
143
+ */
144
+ toJSON(): TAccumulated;
145
+ }
146
+ //# sourceMappingURL=builder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"builder.d.ts","sourceRoot":"","sources":["../src/builder.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EACV,QAAQ,EACR,eAAe,EAEf,iBAAiB,EACjB,cAAc,EACf,MAAM,YAAY,CAAC;AAIpB,MAAM,MAAM,YAAY,CAAC,CAAC,EAAE,CAAC,IAAI,IAAI,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC;AAUtD;;GAEG;AACH,qBAAa,UAAU,CAAC,YAAY,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAIhE,OAAO,CAAC,WAAW;IACnB,OAAO,CAAC,OAAO;IAJjB,OAAO,CAAC,MAAM,CAAwC;gBAG5C,WAAW,EAAE,eAAe,EAC5B,OAAO,GAAE,OAAO,CAAC,cAAc,CAAM;IAG/C;;;OAGG;IACH,IAAI,CAAC,IAAI,SAAS,eAAe,EAC/B,QAAQ,EAAE,QAAQ,EAClB,MAAM,EAAE,IAAI,GACX,UAAU,CAAC,YAAY,CAAC,YAAY,EAAE,iBAAiB,CAAC,IAAI,CAAC,CAAC,CAAC;IAMlE;;OAEG;IACG,OAAO,IAAI,OAAO,CAAC,YAAY,CAAC;IAqCtC;;OAEG;IACH,OAAO,CAAC,qBAAqB;CAgB9B;AAED;;GAEG;AACH,qBAAa,cAAc,CAAC,YAAY,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAIpE,OAAO,CAAC,WAAW;IACnB,OAAO,CAAC,OAAO;IAJjB,O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,IAAI,YAAY;CAGvB"}
@@ -0,0 +1 @@
1
+ import {normalizeSchema,resolveEnvInternal,resolveEnvInternalSync}from'./resolver.js';import {dotenv,processEnv}from'./resolvers.js';class v{constructor(e,s={}){this.localSchema=e;this.options=s;}layers=[];from(e,s){return this.layers.push({resolver:e,schema:s}),this}async resolve(){const e=normalizeSchema(this.localSchema);for(const l of this.layers){const c=normalizeSchema(l.schema);Object.assign(e,c);}const s=this.buildDefaultResolvers(),r=this.layers.map(l=>l.resolver),i=this.options.extend||[],n=this.options.resolvers?this.options.resolvers:[...s,...r,...i],a=this.options.policies??{};return await resolveEnvInternal(e,{...this.options,resolvers:n,policies:a,interpolate:this.options.interpolate??true,strict:this.options.strict??true})}buildDefaultResolvers(){const e=process.env.NODE_ENV==="production",s=[];return e||s.push(dotenv({expand:true})),s.push(processEnv()),s}}class p{constructor(e,s={}){this.localSchema=e;this.options=s;}layers=[];from(e,s){return this.layers.push({resolver:e,schema:s}),this}resolveSync(){const e=normalizeSchema(this.localSchema);for(const l of this.layers){const c=normalizeSchema(l.schema);Object.assign(e,c);}const s=this.buildDefaultResolvers(),r=this.layers.map(l=>l.resolver),i=this.options.extend||[],n=this.options.resolvers?this.options.resolvers:[...s,...r,...i],a=this.options.policies??{};return resolveEnvInternalSync(e,{...this.options,resolvers:n,policies:a,interpolate:this.options.interpolate??true,strict:this.options.strict??true})}buildDefaultResolvers(){const e=process.env.NODE_ENV==="production",s=[];return e||s.push(dotenv({expand:true})),s.push(processEnv()),s}}function f(t,e){return new v(t,e)}function y(t,e){return new p(t,e)}class b{builder;simpleResolve=null;constructor(e,s={}){this.builder=new v(e,s);}from(e,s){return this.builder.from(e,s),this}async compose(){return this.builder.resolve()}then(e,s){return this.simpleResolve||(this.simpleResolve=this.builder.resolve()),this.simpleResolve.then(e,s)}catch(e){return this.simpleResolve||(this.simpleResolve=this.builder.resolve()),this.simpleResolve.catch(e)}finally(e){return this.simpleResolve||(this.simpleResolve=this.builder.resolve()),this.simpleResolve.finally(e)}}class E{builder;_resolved=null;_hasComposition=false;constructor(e,s={}){Object.defineProperty(this,"builder",{value:new p(e,s),enumerable:false,writable:true}),Object.defineProperty(this,"_hasComposition",{value:false,enumerable:false,writable:true});const r=this.builder.resolveSync();Object.defineProperty(this,"_resolved",{value:r,enumerable:false,writable:true}),Object.assign(this,r);}from(e,s){return Object.defineProperty(this,"_hasComposition",{value:true,enumerable:false,writable:true}),this.builder.from(e,s),this}compose(){return this._hasComposition&&(this._resolved=this.builder.resolveSync(),Object.assign(this,this._resolved)),this._resolved}valueOf(){return this._resolved}toJSON(){return this._resolved}}export{v as EnvBuilder,p as EnvBuilderSync,b as ResolvableBuilder,E as ResolvableBuilderSync,f as env,y as envSync};
@@ -0,0 +1,7 @@
1
+ /**
2
+ * TDD Tests for Resolver Composition API
3
+ *
4
+ * Tests the new env().from().resolve() API for explicit provider composition
5
+ */
6
+ export {};
7
+ //# sourceMappingURL=composition.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"composition.test.d.ts","sourceRoot":"","sources":["../src/composition.test.ts"],"names":[],"mappings":"AAAA;;;;GAIG"}