node-env-resolver 4.0.0 → 5.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/README.md +493 -376
- package/dist/audit.d.cts +29 -0
- package/dist/audit.d.ts +8 -7
- package/dist/builder.cjs +1 -1
- package/dist/builder.d.cts +149 -0
- package/dist/builder.d.ts +17 -14
- package/dist/builder.js +1 -1
- package/dist/chunk-4QOKRJ3F.cjs +1 -0
- package/dist/chunk-4YVXFL3I.cjs +9 -0
- package/dist/chunk-6D5APQIG.cjs +1 -0
- package/dist/chunk-DIXI6MUB.js +9 -0
- package/dist/chunk-FH54ESWI.cjs +9 -0
- package/dist/chunk-HHOS5S5T.js +1 -0
- package/dist/chunk-TAX63ALN.js +16 -0
- package/dist/chunk-WKIPEKF6.js +1 -0
- package/dist/chunk-XJLMVSPN.js +9 -0
- package/dist/chunk-XPL5XLTA.cjs +16 -0
- package/dist/cli.d.cts +52 -0
- package/dist/cli.d.ts +9 -6
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +148 -0
- package/dist/index.d.ts +99 -92
- package/dist/index.js +1 -1
- package/dist/resolver.cjs +1 -1
- package/dist/resolver.d.cts +20 -0
- package/dist/resolver.d.ts +8 -5
- package/dist/resolver.js +1 -1
- package/dist/resolvers.cjs +1 -1
- package/dist/resolvers.d.cts +412 -0
- package/dist/resolvers.d.ts +294 -22
- package/dist/resolvers.js +1 -1
- package/dist/types.cjs +1 -1
- package/dist/types.d.cts +106 -0
- package/dist/types.d.ts +90 -172
- package/dist/types.js +1 -1
- package/dist/utils.cjs +1 -1
- package/dist/utils.d.cts +213 -0
- package/dist/utils.d.ts +28 -26
- package/dist/utils.js +1 -1
- package/dist/valibot.cjs +1 -1
- package/dist/valibot.d.cts +156 -0
- package/dist/valibot.d.ts +11 -8
- package/dist/valibot.js +1 -1
- package/dist/validation-types.d.cts +29 -0
- package/dist/validation-types.d.ts +4 -3
- package/dist/validators.cjs +2 -1
- package/dist/validators.d.cts +116 -0
- package/dist/validators.d.ts +46 -18
- package/dist/validators.js +2 -1
- package/dist/web.cjs +3 -3
- package/dist/web.d.cts +69 -0
- package/dist/web.d.ts +28 -10
- package/dist/web.js +3 -3
- package/dist/zod.cjs +1 -1
- package/dist/zod.d.cts +135 -0
- package/dist/zod.d.ts +11 -8
- package/dist/zod.js +1 -1
- package/package.json +7 -7
- package/dist/advanced-features.test.d.ts +0 -2
- package/dist/advanced-features.test.d.ts.map +0 -1
- package/dist/audit.d.ts.map +0 -1
- package/dist/audit.test.d.ts +0 -2
- package/dist/audit.test.d.ts.map +0 -1
- package/dist/builder.d.ts.map +0 -1
- package/dist/chunk-54OHKWZJ.js +0 -1
- package/dist/chunk-FCFDGYTF.cjs +0 -15
- package/dist/chunk-HCVTYYLE.js +0 -9
- package/dist/chunk-IU5TG3HL.js +0 -15
- package/dist/chunk-J7ZHEMRP.js +0 -9
- package/dist/chunk-NKPXKLF7.js +0 -1
- package/dist/chunk-P3ZWKKKW.cjs +0 -1
- package/dist/chunk-THFGEKYL.cjs +0 -9
- package/dist/chunk-ULL4WKTV.cjs +0 -9
- package/dist/chunk-XPGSWVRT.cjs +0 -1
- package/dist/cli.d.ts.map +0 -1
- package/dist/cli.test.d.ts +0 -2
- package/dist/cli.test.d.ts.map +0 -1
- package/dist/composition.test.d.ts +0 -7
- package/dist/composition.test.d.ts.map +0 -1
- package/dist/computed.test.d.ts +0 -2
- package/dist/computed.test.d.ts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.test.d.ts +0 -2
- package/dist/index.test.d.ts.map +0 -1
- package/dist/nested.test.d.ts +0 -2
- package/dist/nested.test.d.ts.map +0 -1
- package/dist/performance.test.d.ts +0 -7
- package/dist/performance.test.d.ts.map +0 -1
- package/dist/priority.test.d.ts +0 -6
- package/dist/priority.test.d.ts.map +0 -1
- package/dist/providers.d.ts +0 -11
- package/dist/providers.d.ts.map +0 -1
- package/dist/resolver.d.ts.map +0 -1
- package/dist/resolvers.d.ts.map +0 -1
- package/dist/resolvers.test.d.ts +0 -2
- package/dist/resolvers.test.d.ts.map +0 -1
- package/dist/sync-resolvers.test.d.ts +0 -2
- package/dist/sync-resolvers.test.d.ts.map +0 -1
- package/dist/type-inference.test.d.ts +0 -2
- package/dist/type-inference.test.d.ts.map +0 -1
- package/dist/type-override.test.d.ts +0 -2
- package/dist/type-override.test.d.ts.map +0 -1
- package/dist/types.d.ts.map +0 -1
- package/dist/utils.d.ts.map +0 -1
- package/dist/utils.test.d.ts +0 -2
- package/dist/utils.test.d.ts.map +0 -1
- package/dist/valibot.d.ts.map +0 -1
- package/dist/validation-types.d.ts.map +0 -1
- package/dist/validators.d.ts.map +0 -1
- package/dist/web.d.ts.map +0 -1
- package/dist/zod.d.ts.map +0 -1
package/dist/types.d.ts
CHANGED
|
@@ -1,188 +1,106 @@
|
|
|
1
|
-
|
|
2
|
-
* Shared types for node-env-resolver
|
|
3
|
-
*/
|
|
4
|
-
export interface EnvDefinition {
|
|
5
|
-
/**
|
|
6
|
-
* Type of the environment variable
|
|
7
|
-
*
|
|
8
|
-
* Basic types (inline validation, ~2KB core):
|
|
9
|
-
* - 'string': Any string value (default)
|
|
10
|
-
* - 'number': Coerced to number
|
|
11
|
-
* - 'boolean': Coerced to boolean
|
|
12
|
-
* - 'custom': Custom validator function
|
|
13
|
-
*
|
|
14
|
-
* Array types (comma-separated by default):
|
|
15
|
-
* - 'string[]': Array of strings (e.g., 'a,b,c' → ['a', 'b', 'c'])
|
|
16
|
-
* - 'number[]': Array of numbers (e.g., '1,2,3' → [1, 2, 3])
|
|
17
|
-
* - 'url[]': Array of URLs
|
|
18
|
-
*
|
|
19
|
-
* Advanced types (lazy-loaded validators, tree-shakeable):
|
|
20
|
-
* - 'postgres'/'postgresql': PostgreSQL connection URL
|
|
21
|
-
* - 'mysql': MySQL connection URL
|
|
22
|
-
* - 'mongodb': MongoDB connection URL (supports replica sets)
|
|
23
|
-
* - 'redis': Redis connection URL
|
|
24
|
-
* - 'http': HTTP or HTTPS URL
|
|
25
|
-
* - 'https': HTTPS-only URL
|
|
26
|
-
* - 'url': Generic URL
|
|
27
|
-
* - 'email': Email address
|
|
28
|
-
* - 'port': Port number 1-65535
|
|
29
|
-
* - 'json': JSON value (returns parsed object)
|
|
30
|
-
* - 'date': ISO 8601 date
|
|
31
|
-
* - 'timestamp': Unix timestamp (seconds)
|
|
32
|
-
* - 'duration': Time duration (e.g., '5s', '2h', '30m' → milliseconds)
|
|
33
|
-
* - 'file': Read content from file path
|
|
34
|
-
*/
|
|
35
|
-
type?: 'string' | 'number' | 'boolean' | 'custom' | 'string[]' | 'number[]' | 'url[]' | 'postgres' | 'postgresql' | 'mysql' | 'mongodb' | 'redis' | 'http' | 'https' | 'url' | 'email' | 'port' | 'json' | 'date' | 'timestamp' | 'duration' | 'file';
|
|
36
|
-
enum?: readonly string[];
|
|
37
|
-
default?: string | number | boolean | string[] | number[];
|
|
1
|
+
type Validator<T> = ((value: string) => T) & {
|
|
38
2
|
optional?: boolean;
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
3
|
+
default?: T;
|
|
4
|
+
};
|
|
5
|
+
type SimpleEnvSchema = Record<string, Validator<unknown> | string | number | boolean | readonly string[]>;
|
|
6
|
+
type InferSimpleValue<V> = V extends Validator<infer R> ? V extends {
|
|
7
|
+
optional: true;
|
|
8
|
+
} ? R | undefined : R : V extends number ? number : V extends boolean ? boolean : V extends readonly (infer U)[] ? U : V extends string ? string : never;
|
|
9
|
+
type InferSimpleSchema<T extends SimpleEnvSchema> = {
|
|
10
|
+
[K in keyof T]: InferSimpleValue<T[K]>;
|
|
11
|
+
};
|
|
12
|
+
type InferNestedSchema<T extends SimpleEnvSchema> = InferSimpleSchema<T>;
|
|
13
|
+
type InferResolveResult<T extends SimpleEnvSchema, O extends ResolveOptions | undefined> = O extends {
|
|
14
|
+
nestedDelimiter: string;
|
|
15
|
+
} ? InferNestedSchema<T> : InferSimpleSchema<T>;
|
|
16
|
+
interface SyncResolver {
|
|
17
|
+
loadSync(): Record<string, string>;
|
|
18
|
+
load?(): Promise<Record<string, string>>;
|
|
19
|
+
name?: string;
|
|
20
|
+
metadata?: Record<string, unknown>;
|
|
53
21
|
}
|
|
54
|
-
|
|
55
|
-
name: string;
|
|
22
|
+
interface AsyncResolver {
|
|
56
23
|
load(): Promise<Record<string, string>>;
|
|
57
24
|
loadSync?(): Record<string, string>;
|
|
25
|
+
name?: string;
|
|
58
26
|
metadata?: Record<string, unknown>;
|
|
59
27
|
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
loadSync?: never;
|
|
65
|
-
}
|
|
66
|
-
export declare function isSyncResolver(resolver: Resolver): resolver is SyncResolver;
|
|
67
|
-
export declare function isAsyncOnlyResolver(resolver: Resolver): resolver is AsyncOnlyResolver;
|
|
68
|
-
export interface ResolveOptions {
|
|
69
|
-
interpolate?: boolean;
|
|
70
|
-
strict?: boolean;
|
|
71
|
-
policies?: PolicyOptions;
|
|
72
|
-
enableAudit?: boolean;
|
|
73
|
-
/**
|
|
74
|
-
* Control merge behavior when multiple resolvers provide the same variable.
|
|
75
|
-
*
|
|
76
|
-
* - `'last'` (default): Later resolvers override earlier ones
|
|
77
|
-
* - `'first'`: Earlier resolvers take precedence, later ones are skipped if value already set
|
|
78
|
-
*
|
|
79
|
-
* @example
|
|
80
|
-
* // Local .env overrides AWS secrets (for development)
|
|
81
|
-
* resolve.async(
|
|
82
|
-
* [dotenv(), { DATABASE_URL: 'url' }],
|
|
83
|
-
* [awsSecrets(), { DATABASE_URL: 'url' }],
|
|
84
|
-
* { priority: 'first' } // dotenv wins
|
|
85
|
-
* );
|
|
86
|
-
*
|
|
87
|
-
* @example
|
|
88
|
-
* // AWS secrets override process.env (for production, default)
|
|
89
|
-
* resolve.async(
|
|
90
|
-
* [processEnv(), { DATABASE_URL: 'url' }],
|
|
91
|
-
* [awsSecrets(), { DATABASE_URL: 'url' }]
|
|
92
|
-
* // priority: 'last' is default - AWS wins
|
|
93
|
-
* );
|
|
94
|
-
*/
|
|
28
|
+
type Resolver = SyncResolver | AsyncResolver;
|
|
29
|
+
declare const isSyncResolver: (resolver: Resolver) => resolver is SyncResolver;
|
|
30
|
+
declare const isAsyncOnlyResolver: (resolver: Resolver) => resolver is AsyncResolver;
|
|
31
|
+
interface ResolveOptions {
|
|
95
32
|
priority?: 'first' | 'last';
|
|
96
|
-
/**
|
|
97
|
-
* Transform flat environment variables into nested objects using a delimiter.
|
|
98
|
-
*
|
|
99
|
-
* When specified, keys like `DATABASE__HOST` become nested as `{ database: { host: '...' } }`
|
|
100
|
-
*
|
|
101
|
-
* @example
|
|
102
|
-
* ```ts
|
|
103
|
-
* // With delimiter '__'
|
|
104
|
-
* process.env.DATABASE__HOST = 'localhost';
|
|
105
|
-
* process.env.DATABASE__PORT = '5432';
|
|
106
|
-
*
|
|
107
|
-
* const config = resolve({
|
|
108
|
-
* 'DATABASE__HOST': 'string',
|
|
109
|
-
* 'DATABASE__PORT': 'port'
|
|
110
|
-
* }, { nestedDelimiter: '__' });
|
|
111
|
-
*
|
|
112
|
-
* // Result: { database: { host: 'localhost', port: 5432 } }
|
|
113
|
-
* ```
|
|
114
|
-
*/
|
|
115
33
|
nestedDelimiter?: string;
|
|
116
|
-
/**
|
|
117
|
-
* Validate default values using the same validators as environment values.
|
|
118
|
-
*
|
|
119
|
-
* When `true`, default values are validated to ensure they match the specified type.
|
|
120
|
-
* This catches configuration errors at startup instead of runtime.
|
|
121
|
-
*
|
|
122
|
-
* @default false
|
|
123
|
-
*
|
|
124
|
-
* @example
|
|
125
|
-
* ```ts
|
|
126
|
-
* const config = resolve({
|
|
127
|
-
* PORT: 99999, // Invalid port number!
|
|
128
|
-
* DATABASE_URL: 'not-a-url' // Invalid URL!
|
|
129
|
-
* }, { validateDefaults: true });
|
|
130
|
-
* // Throws: Port must be between 1 and 65535
|
|
131
|
-
* ```
|
|
132
|
-
*/
|
|
133
34
|
validateDefaults?: boolean;
|
|
134
|
-
/**
|
|
135
|
-
* Global secrets directory for file reading (type: 'file').
|
|
136
|
-
*
|
|
137
|
-
* When specified, variables with `type: 'file'` will read from `secretsDir/lowercase_key_name`
|
|
138
|
-
* if no env var value is provided. Useful for Docker/Kubernetes secrets.
|
|
139
|
-
*
|
|
140
|
-
* Can be overridden per-field using the `secretsDir` property in EnvDefinition.
|
|
141
|
-
*
|
|
142
|
-
* @example
|
|
143
|
-
* ```ts
|
|
144
|
-
* const config = resolve({
|
|
145
|
-
* DB_PASSWORD: 'file', // Reads from /run/secrets/db_password
|
|
146
|
-
* API_KEY: 'file' // Reads from /run/secrets/api_key
|
|
147
|
-
* }, { secretsDir: '/run/secrets' });
|
|
148
|
-
* ```
|
|
149
|
-
*/
|
|
150
35
|
secretsDir?: string;
|
|
36
|
+
arraySeparator?: string;
|
|
37
|
+
interpolate?: boolean;
|
|
38
|
+
strict?: boolean;
|
|
39
|
+
policies?: Record<string, unknown>;
|
|
40
|
+
enableAudit?: boolean;
|
|
151
41
|
}
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
42
|
+
type SafeResolveResultType<T> = {
|
|
43
|
+
success: true;
|
|
44
|
+
data: T;
|
|
45
|
+
} | {
|
|
46
|
+
success: false;
|
|
47
|
+
error: string;
|
|
48
|
+
details?: unknown;
|
|
49
|
+
};
|
|
50
|
+
type InferMergedSchema<T extends readonly [unknown, SimpleEnvSchema][]> = T extends readonly [
|
|
51
|
+
unknown,
|
|
52
|
+
infer S1,
|
|
53
|
+
...infer Rest
|
|
54
|
+
] ? Rest extends readonly [unknown, SimpleEnvSchema][] ? S1 & InferMergedSchema<Rest> : S1 : T extends readonly [unknown, infer S] ? S : Record<string, never>;
|
|
55
|
+
|
|
56
|
+
interface ResolveConfig<T extends SimpleEnvSchema = SimpleEnvSchema> {
|
|
57
|
+
schema?: T;
|
|
58
|
+
resolvers?: readonly [SyncResolver, SimpleEnvSchema][];
|
|
59
|
+
options?: Partial<ResolveOptions>;
|
|
60
|
+
}
|
|
61
|
+
interface ResolveAsyncConfig<T extends SimpleEnvSchema = SimpleEnvSchema> {
|
|
62
|
+
schema?: T;
|
|
63
|
+
resolvers?: readonly [Resolver, SimpleEnvSchema][];
|
|
64
|
+
options?: Partial<ResolveOptions>;
|
|
65
|
+
}
|
|
66
|
+
interface ResolveConfigWithSchema<T extends SimpleEnvSchema> {
|
|
67
|
+
schema: T;
|
|
68
|
+
options?: Partial<ResolveOptions>;
|
|
69
|
+
}
|
|
70
|
+
interface ResolveConfigWithResolvers<T extends readonly [SyncResolver, SimpleEnvSchema][]> {
|
|
71
|
+
resolvers: T;
|
|
72
|
+
options?: Partial<ResolveOptions>;
|
|
156
73
|
}
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
*
|
|
161
|
-
* - `undefined` (default): .env files completely ignored in production (secure default)
|
|
162
|
-
* - `true`: Allow all vars from .env in production (NOT recommended)
|
|
163
|
-
* - `string[]`: Allow only specific vars from .env in production
|
|
164
|
-
*
|
|
165
|
-
* Note: `process.env` is ALWAYS used regardless of this setting.
|
|
166
|
-
* Production platforms (Vercel, AWS, Docker, etc.) inject via process.env, NOT .env files.
|
|
167
|
-
*
|
|
168
|
-
* @example allowDotenvInProduction: true // Allow all (not recommended)
|
|
169
|
-
* @example allowDotenvInProduction: ['PORT', 'NODE_ENV'] // Allow specific vars
|
|
170
|
-
*/
|
|
171
|
-
allowDotenvInProduction?: boolean | string[];
|
|
172
|
-
enforceAllowedSources?: Record<string, string[]>;
|
|
74
|
+
interface ResolveAsyncConfigWithSchema<T extends SimpleEnvSchema> {
|
|
75
|
+
schema: T;
|
|
76
|
+
options?: Partial<ResolveOptions>;
|
|
173
77
|
}
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
78
|
+
interface ResolveAsyncConfigWithResolvers<T extends readonly [Resolver, SimpleEnvSchema][]> {
|
|
79
|
+
resolvers: T;
|
|
80
|
+
options?: Partial<ResolveOptions>;
|
|
177
81
|
}
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
82
|
+
type Provenance = {
|
|
83
|
+
source: string;
|
|
84
|
+
timestamp: number;
|
|
85
|
+
metadata?: Record<string, unknown>;
|
|
86
|
+
cached?: boolean;
|
|
181
87
|
};
|
|
182
|
-
type
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
88
|
+
type PolicyOptions = {
|
|
89
|
+
allowDotenvInProduction?: boolean;
|
|
90
|
+
requireSecretsForSensitive?: boolean;
|
|
91
|
+
blockInsecureProtocols?: boolean;
|
|
92
|
+
enforceAllowedSources?: boolean;
|
|
186
93
|
};
|
|
187
|
-
|
|
188
|
-
|
|
94
|
+
type SimpleEnvValue = Validator<unknown> | string | number | boolean | readonly string[];
|
|
95
|
+
type EnvSchema = Record<string, unknown>;
|
|
96
|
+
interface EnvDefinition {
|
|
97
|
+
type?: string;
|
|
98
|
+
validator?: (value: string, key?: string) => unknown;
|
|
99
|
+
default?: unknown;
|
|
100
|
+
optional?: boolean;
|
|
101
|
+
secretsDir?: string;
|
|
102
|
+
}
|
|
103
|
+
type InferType = unknown;
|
|
104
|
+
type InferSchema = unknown;
|
|
105
|
+
|
|
106
|
+
export { type AsyncResolver, type EnvDefinition, type EnvSchema, type InferMergedSchema, type InferNestedSchema, type InferResolveResult, type InferSchema, type InferSimpleSchema, type InferSimpleValue, type InferType, type PolicyOptions, type Provenance, type ResolveAsyncConfig, type ResolveAsyncConfigWithResolvers, type ResolveAsyncConfigWithSchema, type ResolveConfig, type ResolveConfigWithResolvers, type ResolveConfigWithSchema, type ResolveOptions, type Resolver, type SafeResolveResultType, type SimpleEnvSchema, type SimpleEnvValue, type SyncResolver, type Validator, isAsyncOnlyResolver, isSyncResolver };
|
package/dist/types.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{b as isAsyncOnlyResolver,a as isSyncResolver}from'./chunk-
|
|
1
|
+
export{b as isAsyncOnlyResolver,a as isSyncResolver}from'./chunk-HHOS5S5T.js';import'./chunk-5PELJRUQ.js';
|
package/dist/utils.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var chunkKIQXH265_cjs=require('./chunk-KIQXH265.cjs');function
|
|
1
|
+
'use strict';var chunkFH54ESWI_cjs=require('./chunk-FH54ESWI.cjs');require('./chunk-4YVXFL3I.cjs'),require('./chunk-4ZOF2PI4.cjs'),require('./chunk-4QOKRJ3F.cjs'),require('./chunk-6D5APQIG.cjs');var chunkKIQXH265_cjs=require('./chunk-KIQXH265.cjs');function T(e,n={}){let{ttl:r=3e5,maxAge:s=36e5,staleWhileRevalidate:o=false}=n,t=null,a={name:`cached(${e.name})`,metadata:{},async load(){let i=Date.now();if(!t||i-t.timestamp>s){let l=e.load?await e.load():{};return t={data:l,timestamp:i},a.metadata={cached:false},l}if(i-t.timestamp<r)return a.metadata={cached:true},t.data;if(o&&!t.refreshPromise){let l=Promise.resolve(e.load?e.load():Promise.resolve({}));return t.refreshPromise=l.then(u=>(t.data=u,t.timestamp=Date.now(),t.refreshPromise=void 0,u)).catch(()=>(t.refreshPromise=void 0,t.data)),a.metadata={cached:true,stale:true},t.data}let d=e.load?await e.load():{};return t={data:d,timestamp:i},a.metadata={cached:false},d}};return a}var p={short:30*1e3,minute:60*1e3,minutes5:300*1e3,minutes15:900*1e3,hour:3600*1e3,hours6:360*60*1e3,day:1440*60*1e3};function C(e={}){return {ttl:e.ttl??p.minutes5,maxAge:e.maxAge??p.hour,staleWhileRevalidate:e.staleWhileRevalidate??true,key:"aws-secrets"}}function b(e,n=3,r=1e3){return {name:`retry(${e.name})`,async load(){let s;for(let o=0;o<=n;o++)try{return e.load?await e.load():{}}catch(t){s=t instanceof Error?t:new Error(String(t)),o<n&&await new Promise(a=>setTimeout(a,r*Math.pow(2,o)));}throw s}}}function x(e,n){let r=n.toUpperCase();return {name:`withPrefix(${e.name}, ${n})`,async load(){let s=e.load?await e.load():{},o={};for(let[t,a]of Object.entries(s))if(t.toUpperCase().startsWith(r)){let i=t.slice(n.length);o[i]=a;}else o[t]=a;return o},loadSync(){if(!e.loadSync)throw new Error(`Resolver ${e.name} does not support sync loading`);let s=e.loadSync(),o={};for(let[t,a]of Object.entries(s))if(t.toUpperCase().startsWith(r)){let i=t.slice(n.length);o[i]=a;}else o[t]=a;return o}}}function P(e,n){let r={...e};for(let[s,o]of Object.entries(n))Object.defineProperty(r,s,{get(){return o(e)},enumerable:true,configurable:true});return r}function $(e,n){return {name:`withAliases(${e.name})`,async load(){let r=e.load?await e.load():{};return g(r,n)},loadSync(){if(!e.loadSync)throw new Error(`Resolver ${e.name} does not support sync loading`);let r=e.loadSync();return g(r,n)}}}function g(e,n){let r={...e};for(let[s,o]of Object.entries(n))for(let t of o)if(e[t]!==void 0){r[s]=e[t];break}return r}function S(e,n){return {name:`withTransform(${e.name})`,async load(){let r=e.load?await e.load():{};return h(r,n)},loadSync(){if(!e.loadSync)throw new Error(`Resolver ${e.name} does not support sync loading`);let r=e.loadSync();return h(r,n)}}}function h(e,n){let r={...e};for(let[s,o]of Object.entries(n))if(e[s]!==void 0)try{r[s]=o(e[s]);}catch(t){throw new Error(`Transform failed for ${s}: ${t instanceof Error?t.message:String(t)}`)}return r}function k(e,n){let s=`${n.toUpperCase()}_`;return {name:`withNamespace(${e.name}, ${n})`,async load(){let o=e.load?await e.load():{},t={};for(let[a,i]of Object.entries(o))if(a.toUpperCase().startsWith(s)){let d=a.slice(s.length);t[d]=i;}return t},loadSync(){if(!e.loadSync)throw new Error(`Resolver ${e.name} does not support sync loading`);let o=e.loadSync(),t={};for(let[a,i]of Object.entries(o))if(a.toUpperCase().startsWith(s)){let d=a.slice(s.length);t[d]=i;}return t}}}function v(e,n){let{onChange:r,debounce:s=100,files:o=[".env"]}=n??{},t,a=null,i=[],d=async()=>{try{return await import('./index.cjs'),t=await chunkFH54ESWI_cjs.b(e),t}catch(c){throw console.error("[watch] Failed to load config:",c),c}},l=()=>{a&&clearTimeout(a),a=setTimeout(async()=>{try{let c=await d();r?.(c);}catch(c){console.error("[watch] Failed to reload config:",c);}},s);},{watch:u}=chunkKIQXH265_cjs.a("fs"),{join:y}=chunkKIQXH265_cjs.a("path");for(let c of o)try{let w=u(y(process.cwd(),c),l);i.push(w);}catch{}return d().catch(console.error),{getConfig:()=>t,stop:()=>{a&&clearTimeout(a);for(let c of i)c.close();}}}exports.TTL=p;exports.awsCache=C;exports.cached=T;exports.retry=b;exports.watch=v;exports.withAliases=$;exports.withComputed=P;exports.withNamespace=k;exports.withPrefix=x;exports.withTransform=S;
|
package/dist/utils.d.cts
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { resolveAsync } from './index.cjs';
|
|
2
|
+
import { Resolver } from './types.cjs';
|
|
3
|
+
import './validation-types.cjs';
|
|
4
|
+
import './audit.cjs';
|
|
5
|
+
|
|
6
|
+
interface CacheOptions {
|
|
7
|
+
/** Time to live in milliseconds (default: 5 minutes) */
|
|
8
|
+
ttl?: number;
|
|
9
|
+
/** Maximum age in milliseconds before forcing refresh (default: 1 hour) */
|
|
10
|
+
maxAge?: number;
|
|
11
|
+
/** Enable stale-while-revalidate: serve stale data while refreshing in background */
|
|
12
|
+
staleWhileRevalidate?: boolean;
|
|
13
|
+
/** Custom cache key (useful for debugging or manual cache invalidation) */
|
|
14
|
+
key?: string;
|
|
15
|
+
}
|
|
16
|
+
declare function cached(resolver: Resolver, options?: CacheOptions): Resolver;
|
|
17
|
+
declare const TTL: {
|
|
18
|
+
/** 30 seconds */
|
|
19
|
+
readonly short: number;
|
|
20
|
+
/** 1 minute */
|
|
21
|
+
readonly minute: number;
|
|
22
|
+
/** 5 minutes */
|
|
23
|
+
readonly minutes5: number;
|
|
24
|
+
/** 15 minutes */
|
|
25
|
+
readonly minutes15: number;
|
|
26
|
+
/** 1 hour */
|
|
27
|
+
readonly hour: number;
|
|
28
|
+
/** 6 hours */
|
|
29
|
+
readonly hours6: number;
|
|
30
|
+
/** 24 hours */
|
|
31
|
+
readonly day: number;
|
|
32
|
+
};
|
|
33
|
+
declare function awsCache(options?: {
|
|
34
|
+
/** Cache duration for AWS secrets/parameters (default: 5 minutes) */
|
|
35
|
+
ttl?: number;
|
|
36
|
+
/** Maximum age before forcing refresh (default: 1 hour) */
|
|
37
|
+
maxAge?: number;
|
|
38
|
+
/** Enable stale-while-revalidate for better performance (default: true) */
|
|
39
|
+
staleWhileRevalidate?: boolean;
|
|
40
|
+
}): CacheOptions;
|
|
41
|
+
declare function retry(resolver: Resolver, maxRetries?: number, delayMs?: number): Resolver;
|
|
42
|
+
/**
|
|
43
|
+
* Wrap a resolver to strip a prefix from environment variable names
|
|
44
|
+
* Useful for scoping environment variables (e.g., APP_PORT → PORT)
|
|
45
|
+
*
|
|
46
|
+
* @param resolver The resolver to wrap
|
|
47
|
+
* @param prefix The prefix to strip (case-insensitive)
|
|
48
|
+
* @returns Wrapped resolver that strips the prefix
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* ```ts
|
|
52
|
+
* import { resolve, processEnv } from 'node-env-resolver';
|
|
53
|
+
* import { withPrefix } from 'node-env-resolver/utils';
|
|
54
|
+
*
|
|
55
|
+
* // Maps APP_PORT → PORT, APP_DATABASE_URL → DATABASE_URL
|
|
56
|
+
* const config = await resolveAsync(
|
|
57
|
+
* [withPrefix(processEnv(), 'APP_'), { PORT: 3000, DATABASE_URL: postgres() }]
|
|
58
|
+
* );
|
|
59
|
+
* ```
|
|
60
|
+
*/
|
|
61
|
+
declare function withPrefix(resolver: Resolver, prefix: string): Resolver;
|
|
62
|
+
/**
|
|
63
|
+
* Add computed/derived properties to resolved config
|
|
64
|
+
*
|
|
65
|
+
* Useful for deriving values from multiple config fields (e.g., building URLs,
|
|
66
|
+
* computing feature flags, creating connection objects).
|
|
67
|
+
*
|
|
68
|
+
* @param config Resolved configuration object
|
|
69
|
+
* @param computed Map of computed property names to functions that derive values
|
|
70
|
+
* @returns Config with computed properties as getters
|
|
71
|
+
*
|
|
72
|
+
* @example
|
|
73
|
+
* ```ts
|
|
74
|
+
* import { resolve } from 'node-env-resolver';
|
|
75
|
+
* import { withComputed } from 'node-env-resolver/utils';
|
|
76
|
+
*
|
|
77
|
+
* const config = withComputed(
|
|
78
|
+
* resolve({ HOST: 'localhost', PORT: 3000, NODE_ENV: 'development' }),
|
|
79
|
+
* {
|
|
80
|
+
* url: (c) => `http://${c.HOST}:${c.PORT}`,
|
|
81
|
+
* isDev: (c) => c.NODE_ENV === 'development',
|
|
82
|
+
* isSecure: (c) => c.HOST !== 'localhost'
|
|
83
|
+
* }
|
|
84
|
+
* );
|
|
85
|
+
*
|
|
86
|
+
* console.log(config.url); // 'http://localhost:3000'
|
|
87
|
+
* console.log(config.isDev); // true
|
|
88
|
+
* console.log(config.isSecure); // false
|
|
89
|
+
* ```
|
|
90
|
+
*/
|
|
91
|
+
declare function withComputed<TConfig extends Record<string, unknown>, TComputed extends Record<string, (config: TConfig) => unknown>>(config: TConfig, computed: TComputed): TConfig & {
|
|
92
|
+
[K in keyof TComputed]: ReturnType<TComputed[K]>;
|
|
93
|
+
};
|
|
94
|
+
/**
|
|
95
|
+
* Wrap a resolver to support field aliases (multiple possible names for a config value)
|
|
96
|
+
* Tries each alias in order and uses the first one found
|
|
97
|
+
*
|
|
98
|
+
* @param resolver The resolver to wrap
|
|
99
|
+
* @param aliases Map of canonical key to array of possible aliases
|
|
100
|
+
* @returns Wrapped resolver that supports aliases
|
|
101
|
+
*
|
|
102
|
+
* @example
|
|
103
|
+
* ```ts
|
|
104
|
+
* import { resolve, processEnv } from 'node-env-resolver';
|
|
105
|
+
* import { withAliases } from 'node-env-resolver/utils';
|
|
106
|
+
*
|
|
107
|
+
* // Tries PORT, then HTTP_PORT, then SERVER_PORT (first found wins)
|
|
108
|
+
* const config = await resolveAsync(
|
|
109
|
+
* [withAliases(processEnv(), {
|
|
110
|
+
* PORT: ['PORT', 'HTTP_PORT', 'SERVER_PORT'],
|
|
111
|
+
* DATABASE_URL: ['DATABASE_URL', 'DB_URL', 'POSTGRES_URL']
|
|
112
|
+
* }), { PORT: 3000, DATABASE_URL: postgres() }]
|
|
113
|
+
* );
|
|
114
|
+
* ```
|
|
115
|
+
*/
|
|
116
|
+
declare function withAliases(resolver: Resolver, aliases: Record<string, string[]>): Resolver;
|
|
117
|
+
/**
|
|
118
|
+
* Wrap a resolver to apply custom transformations to values
|
|
119
|
+
* Powerful utility for parsing, coercing, or enriching config values
|
|
120
|
+
*
|
|
121
|
+
* @param resolver The resolver to wrap
|
|
122
|
+
* @param transforms Map of keys to transformation functions
|
|
123
|
+
* @returns Wrapped resolver that applies transforms
|
|
124
|
+
*
|
|
125
|
+
* @example
|
|
126
|
+
* ```ts
|
|
127
|
+
* import { resolve, processEnv } from 'node-env-resolver';
|
|
128
|
+
* import { withTransform } from 'node-env-resolver/utils';
|
|
129
|
+
*
|
|
130
|
+
* const config = await resolveAsync(
|
|
131
|
+
* [withTransform(processEnv(), {
|
|
132
|
+
* // Parse comma-separated values
|
|
133
|
+
* TAGS: (val) => val.split(',').map(s => s.trim()),
|
|
134
|
+
* // Convert to URL object
|
|
135
|
+
* API_URL: (val) => new URL(val),
|
|
136
|
+
* // Custom parsing
|
|
137
|
+
* MAX_RETRIES: (val) => Math.min(parseInt(val, 10), 10)
|
|
138
|
+
* }), {
|
|
139
|
+
* TAGS: string(),
|
|
140
|
+
* API_URL: url(),
|
|
141
|
+
* MAX_RETRIES: 'number'
|
|
142
|
+
* }]
|
|
143
|
+
* );
|
|
144
|
+
* ```
|
|
145
|
+
*/
|
|
146
|
+
declare function withTransform(resolver: Resolver, transforms: Record<string, (value: string) => string>): Resolver;
|
|
147
|
+
/**
|
|
148
|
+
* Wrap a resolver to scope all keys to a namespace/prefix
|
|
149
|
+
* Similar to withPrefix but adds the namespace instead of removing it
|
|
150
|
+
*
|
|
151
|
+
* @param resolver The resolver to wrap
|
|
152
|
+
* @param namespace The namespace to scope keys under
|
|
153
|
+
* @returns Wrapped resolver with scoped keys
|
|
154
|
+
*
|
|
155
|
+
* @example
|
|
156
|
+
* ```ts
|
|
157
|
+
* import { resolve, processEnv } from 'node-env-resolver';
|
|
158
|
+
* import { withNamespace } from 'node-env-resolver/utils';
|
|
159
|
+
*
|
|
160
|
+
* // Reads DATABASE_HOST, DATABASE_PORT from env
|
|
161
|
+
* // But schema only needs HOST, PORT
|
|
162
|
+
* const dbConfig = await resolveAsync(
|
|
163
|
+
* [withNamespace(processEnv(), 'DATABASE'), {
|
|
164
|
+
* HOST: string(),
|
|
165
|
+
* PORT: 'port'
|
|
166
|
+
* }]
|
|
167
|
+
* );
|
|
168
|
+
* // dbConfig: { HOST: '...', PORT: ... }
|
|
169
|
+
* ```
|
|
170
|
+
*/
|
|
171
|
+
declare function withNamespace(resolver: Resolver, namespace: string): Resolver;
|
|
172
|
+
/**
|
|
173
|
+
* Watch configuration files and reload automatically
|
|
174
|
+
* Perfect for development - auto-reload when .env files change
|
|
175
|
+
*
|
|
176
|
+
* @param schema Environment schema definition
|
|
177
|
+
* @param resolvers Array of resolvers to use
|
|
178
|
+
* @param options Watch options
|
|
179
|
+
* @returns Function to get current config + cleanup function
|
|
180
|
+
*
|
|
181
|
+
* @example
|
|
182
|
+
* ```ts
|
|
183
|
+
* import { watch } from 'node-env-resolver/utils';
|
|
184
|
+
* import { dotenv, processEnv } from 'node-env-resolver/resolvers';
|
|
185
|
+
*
|
|
186
|
+
* const { getConfig, stop } = watch(
|
|
187
|
+
* { PORT: 3000, API_KEY: string() },
|
|
188
|
+
* [processEnv(), dotenv()],
|
|
189
|
+
* {
|
|
190
|
+
* onChange: (config) => console.log('Config reloaded!', config)
|
|
191
|
+
* }
|
|
192
|
+
* );
|
|
193
|
+
*
|
|
194
|
+
* // Use in your app
|
|
195
|
+
* app.get('/config', () => getConfig());
|
|
196
|
+
*
|
|
197
|
+
* // Cleanup when done
|
|
198
|
+
* process.on('SIGINT', () => stop());
|
|
199
|
+
* ```
|
|
200
|
+
*/
|
|
201
|
+
declare function watch<T>(config: Parameters<typeof resolveAsync>[0], options?: {
|
|
202
|
+
/** Callback when config changes */
|
|
203
|
+
onChange?: (config: T) => void;
|
|
204
|
+
/** Debounce delay in ms (default: 100) */
|
|
205
|
+
debounce?: number;
|
|
206
|
+
/** Files to watch (default: ['.env']) */
|
|
207
|
+
files?: string[];
|
|
208
|
+
}): {
|
|
209
|
+
getConfig: () => T;
|
|
210
|
+
stop: () => void;
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
export { type CacheOptions, TTL, awsCache, cached, retry, watch, withAliases, withComputed, withNamespace, withPrefix, withTransform };
|