node-env-resolver 4.0.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +289 -251
  2. package/dist/audit.d.cts +29 -0
  3. package/dist/audit.d.ts +8 -7
  4. package/dist/builder.cjs +1 -1
  5. package/dist/builder.d.cts +149 -0
  6. package/dist/builder.d.ts +17 -14
  7. package/dist/builder.js +1 -1
  8. package/dist/chunk-4YVXFL3I.cjs +9 -0
  9. package/dist/chunk-6FXCXA4R.cjs +11 -0
  10. package/dist/chunk-BFLXBLZ3.cjs +1 -0
  11. package/dist/chunk-BJ2QNYTS.js +11 -0
  12. package/dist/chunk-DIXI6MUB.js +9 -0
  13. package/dist/chunk-P3TTYVEW.js +16 -0
  14. package/dist/chunk-UCLEPPLS.cjs +16 -0
  15. package/dist/chunk-ZMRT37K3.js +1 -0
  16. package/dist/cli.d.cts +52 -0
  17. package/dist/cli.d.ts +9 -6
  18. package/dist/index.cjs +1 -1
  19. package/dist/index.d.cts +150 -0
  20. package/dist/index.d.ts +86 -77
  21. package/dist/index.js +1 -1
  22. package/dist/resolver.cjs +1 -1
  23. package/dist/resolver.d.cts +20 -0
  24. package/dist/resolver.d.ts +8 -5
  25. package/dist/resolver.js +1 -1
  26. package/dist/resolvers.cjs +1 -1
  27. package/dist/resolvers.d.cts +407 -0
  28. package/dist/resolvers.d.ts +289 -22
  29. package/dist/resolvers.js +1 -1
  30. package/dist/types.cjs +1 -1
  31. package/dist/types.d.cts +74 -0
  32. package/dist/types.d.ts +58 -172
  33. package/dist/types.js +1 -1
  34. package/dist/utils.cjs +1 -1
  35. package/dist/utils.d.cts +213 -0
  36. package/dist/utils.d.ts +28 -26
  37. package/dist/utils.js +1 -1
  38. package/dist/valibot.cjs +1 -1
  39. package/dist/valibot.d.cts +156 -0
  40. package/dist/valibot.d.ts +11 -8
  41. package/dist/valibot.js +1 -1
  42. package/dist/validation-types.d.cts +29 -0
  43. package/dist/validation-types.d.ts +4 -3
  44. package/dist/validators.cjs +2 -1
  45. package/dist/validators.d.cts +116 -0
  46. package/dist/validators.d.ts +46 -18
  47. package/dist/validators.js +2 -1
  48. package/dist/web.cjs +4 -4
  49. package/dist/web.d.cts +69 -0
  50. package/dist/web.d.ts +28 -10
  51. package/dist/web.js +4 -4
  52. package/dist/zod.cjs +1 -1
  53. package/dist/zod.d.cts +135 -0
  54. package/dist/zod.d.ts +11 -8
  55. package/dist/zod.js +1 -1
  56. package/package.json +7 -7
  57. package/dist/advanced-features.test.d.ts +0 -2
  58. package/dist/advanced-features.test.d.ts.map +0 -1
  59. package/dist/audit.d.ts.map +0 -1
  60. package/dist/audit.test.d.ts +0 -2
  61. package/dist/audit.test.d.ts.map +0 -1
  62. package/dist/builder.d.ts.map +0 -1
  63. package/dist/chunk-54OHKWZJ.js +0 -1
  64. package/dist/chunk-FCFDGYTF.cjs +0 -15
  65. package/dist/chunk-HCVTYYLE.js +0 -9
  66. package/dist/chunk-IU5TG3HL.js +0 -15
  67. package/dist/chunk-J7ZHEMRP.js +0 -9
  68. package/dist/chunk-NKPXKLF7.js +0 -1
  69. package/dist/chunk-P3ZWKKKW.cjs +0 -1
  70. package/dist/chunk-THFGEKYL.cjs +0 -9
  71. package/dist/chunk-ULL4WKTV.cjs +0 -9
  72. package/dist/chunk-XPGSWVRT.cjs +0 -1
  73. package/dist/cli.d.ts.map +0 -1
  74. package/dist/cli.test.d.ts +0 -2
  75. package/dist/cli.test.d.ts.map +0 -1
  76. package/dist/composition.test.d.ts +0 -7
  77. package/dist/composition.test.d.ts.map +0 -1
  78. package/dist/computed.test.d.ts +0 -2
  79. package/dist/computed.test.d.ts.map +0 -1
  80. package/dist/index.d.ts.map +0 -1
  81. package/dist/index.test.d.ts +0 -2
  82. package/dist/index.test.d.ts.map +0 -1
  83. package/dist/nested.test.d.ts +0 -2
  84. package/dist/nested.test.d.ts.map +0 -1
  85. package/dist/performance.test.d.ts +0 -7
  86. package/dist/performance.test.d.ts.map +0 -1
  87. package/dist/priority.test.d.ts +0 -6
  88. package/dist/priority.test.d.ts.map +0 -1
  89. package/dist/providers.d.ts +0 -11
  90. package/dist/providers.d.ts.map +0 -1
  91. package/dist/resolver.d.ts.map +0 -1
  92. package/dist/resolvers.d.ts.map +0 -1
  93. package/dist/resolvers.test.d.ts +0 -2
  94. package/dist/resolvers.test.d.ts.map +0 -1
  95. package/dist/sync-resolvers.test.d.ts +0 -2
  96. package/dist/sync-resolvers.test.d.ts.map +0 -1
  97. package/dist/type-inference.test.d.ts +0 -2
  98. package/dist/type-inference.test.d.ts.map +0 -1
  99. package/dist/type-override.test.d.ts +0 -2
  100. package/dist/type-override.test.d.ts.map +0 -1
  101. package/dist/types.d.ts.map +0 -1
  102. package/dist/utils.d.ts.map +0 -1
  103. package/dist/utils.test.d.ts +0 -2
  104. package/dist/utils.test.d.ts.map +0 -1
  105. package/dist/valibot.d.ts.map +0 -1
  106. package/dist/validation-types.d.ts.map +0 -1
  107. package/dist/validators.d.ts.map +0 -1
  108. package/dist/web.d.ts.map +0 -1
  109. package/dist/zod.d.ts.map +0 -1
package/dist/types.d.ts CHANGED
@@ -1,188 +1,74 @@
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
- description?: string;
40
- pattern?: string;
41
- min?: number;
42
- max?: number;
43
- validator?: (value: string) => unknown;
44
- /** Allow empty strings (default: false - empty strings are rejected) */
45
- allowEmpty?: boolean;
46
- /** Separator for array types (default: ',') */
47
- separator?: string;
48
- /** Per-field secrets directory (overrides global secretsDir option) */
49
- secretsDir?: string;
50
- }
51
- export interface EnvSchema {
52
- [key: string]: EnvDefinition;
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
- export interface Resolver {
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
- export interface SyncResolver extends Resolver {
61
- loadSync(): Record<string, string>;
62
- }
63
- export interface AsyncOnlyResolver extends Resolver {
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
- export interface Provenance {
42
+ type SafeResolveResultType<T> = {
43
+ success: true;
44
+ data: T;
45
+ } | {
46
+ success: false;
47
+ error: string;
48
+ details?: unknown;
49
+ };
50
+ type Provenance = {
153
51
  source: string;
154
52
  timestamp: number;
53
+ metadata?: Record<string, unknown>;
155
54
  cached?: boolean;
156
- }
157
- export interface PolicyOptions {
158
- /**
159
- * Control loading from .env files in production.
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[]>;
173
- }
174
- export type SimpleEnvValue = string | number | boolean | readonly string[] | EnvDefinition | ((value: string) => unknown);
175
- export interface SimpleEnvSchema {
176
- [key: string]: SimpleEnvValue;
177
- }
178
- export type InferType<T extends EnvDefinition> = T['enum'] extends readonly (infer U)[] ? U : T['type'] extends 'number' ? number : T['type'] extends 'boolean' ? boolean : T['type'] extends 'port' ? number : T['type'] extends 'timestamp' ? number : T['type'] extends 'duration' ? number : T['type'] extends 'string[]' ? string[] : T['type'] extends 'number[]' ? number[] : T['type'] extends 'url[]' ? string[] : T['type'] extends 'custom' ? unknown : string;
179
- export type InferSchema<T extends EnvSchema> = {
180
- [K in keyof T]: T[K]['optional'] extends true ? InferType<T[K]> | undefined : T[K]['default'] extends unknown ? InferType<T[K]> : InferType<T[K]>;
181
55
  };
182
- type InferSimpleValue<V> = V extends EnvDefinition ? InferType<V> : V extends (value: string) => infer R ? R : V extends number ? number : V extends boolean ? boolean : V extends readonly (infer U)[] ? U : V extends 'number' | `number?` | `number:${string}` | 'port' | `port?` | `port:${string}` | 'timestamp' | `timestamp?` | `timestamp:${string}` | 'duration' | `duration?` | `duration:${string}` ? number : V extends 'boolean' | `boolean?` | `boolean:${string}` ? boolean : V extends 'string[]' | `string[]?` | `string[]:${string}` ? string[] : V extends 'number[]' | `number[]?` | `number[]:${string}` ? number[] : V extends 'url[]' | `url[]?` | `url[]:${string}` ? string[] : V extends string ? string : never;
183
- type InferOptional<V> = V extends string ? V extends `${string}?` ? true : false : V extends EnvDefinition ? V['optional'] extends true ? true : false : false;
184
- export type InferSimpleSchema<T extends SimpleEnvSchema> = {
185
- [K in keyof T]: InferOptional<T[K]> extends true ? InferSimpleValue<T[K]> | undefined : InferSimpleValue<T[K]>;
56
+ type PolicyOptions = {
57
+ allowDotenvInProduction?: boolean;
58
+ requireSecretsForSensitive?: boolean;
59
+ blockInsecureProtocols?: boolean;
60
+ enforceAllowedSources?: boolean;
186
61
  };
187
- export {};
188
- //# sourceMappingURL=types.d.ts.map
62
+ type SimpleEnvValue = Validator<unknown> | string | number | boolean | readonly string[];
63
+ type EnvSchema = Record<string, unknown>;
64
+ interface EnvDefinition {
65
+ type?: string;
66
+ validator?: (value: string, key?: string) => unknown;
67
+ default?: unknown;
68
+ optional?: boolean;
69
+ secretsDir?: string;
70
+ }
71
+ type InferType = unknown;
72
+ type InferSchema = unknown;
73
+
74
+ export { type AsyncResolver, type EnvDefinition, type EnvSchema, type InferNestedSchema, type InferResolveResult, type InferSchema, type InferSimpleSchema, type InferSimpleValue, type InferType, type PolicyOptions, type Provenance, 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-54OHKWZJ.js';import'./chunk-5PELJRUQ.js';
1
+ export{b as isAsyncOnlyResolver,a as isSyncResolver}from'./chunk-ZMRT37K3.js';import'./chunk-5PELJRUQ.js';
package/dist/utils.cjs CHANGED
@@ -1 +1 @@
1
- 'use strict';var chunkKIQXH265_cjs=require('./chunk-KIQXH265.cjs');function R(e,n={}){let{ttl:r=3e5,maxAge:a=36e5,staleWhileRevalidate:o=false}=n,t=null,s={name:`cached(${e.name})`,metadata:{},async load(){let i=Date.now();if(!t||i-t.timestamp>a){let l=await e.load();return t={data:l,timestamp:i},s.metadata={cached:false},l}if(i-t.timestamp<r)return s.metadata={cached:true},t.data;if(o&&!t.refreshPromise)return t.refreshPromise=e.load().then(l=>(t.data=l,t.timestamp=Date.now(),t.refreshPromise=void 0,l)).catch(()=>(t.refreshPromise=void 0,t.data)),s.metadata={cached:true,stale:true},t.data;let d=await e.load();return t={data:d,timestamp:i},s.metadata={cached:false},d}};return s}var f={short:30*1e3,minute:60*1e3,minutes5:300*1e3,minutes15:900*1e3,hour:3600*1e3,hours6:360*60*1e3,day:1440*60*1e3};function T(e={}){return {ttl:e.ttl??f.minutes5,maxAge:e.maxAge??f.hour,staleWhileRevalidate:e.staleWhileRevalidate??true,key:"aws-secrets"}}function C(e,n=3,r=1e3){return {name:`retry(${e.name})`,async load(){let a;for(let o=0;o<=n;o++)try{return await e.load()}catch(t){a=t instanceof Error?t:new Error(String(t)),o<n&&await new Promise(s=>setTimeout(s,r*Math.pow(2,o)));}throw a}}}function b(e,n){let r=n.toUpperCase();return {name:`withPrefix(${e.name}, ${n})`,async load(){let a=await e.load(),o={};for(let[t,s]of Object.entries(a))if(t.toUpperCase().startsWith(r)){let i=t.slice(n.length);o[i]=s;}else o[t]=s;return o},loadSync(){if(!e.loadSync)throw new Error(`Resolver ${e.name} does not support sync loading`);let a=e.loadSync(),o={};for(let[t,s]of Object.entries(a))if(t.toUpperCase().startsWith(r)){let i=t.slice(n.length);o[i]=s;}else o[t]=s;return o}}}function x(e,n){let r={...e};for(let[a,o]of Object.entries(n))Object.defineProperty(r,a,{get(){return o(e)},enumerable:true,configurable:true});return r}function v(e,n){return {name:`withAliases(${e.name})`,async load(){let r=await e.load();return p(r,n)},loadSync(){if(!e.loadSync)throw new Error(`Resolver ${e.name} does not support sync loading`);let r=e.loadSync();return p(r,n)}}}function p(e,n){let r={...e};for(let[a,o]of Object.entries(n))for(let t of o)if(e[t]!==void 0){r[a]=e[t];break}return r}function $(e,n){return {name:`withTransform(${e.name})`,async load(){let r=await e.load();return m(r,n)},loadSync(){if(!e.loadSync)throw new Error(`Resolver ${e.name} does not support sync loading`);let r=e.loadSync();return m(r,n)}}}function m(e,n){let r={...e};for(let[a,o]of Object.entries(n))if(e[a]!==void 0)try{r[a]=o(e[a]);}catch(t){throw new Error(`Transform failed for ${a}: ${t instanceof Error?t.message:String(t)}`)}return r}function S(e,n){let a=`${n.toUpperCase()}_`;return {name:`withNamespace(${e.name}, ${n})`,async load(){let o=await e.load(),t={};for(let[s,i]of Object.entries(o))if(s.toUpperCase().startsWith(a)){let d=s.slice(a.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[s,i]of Object.entries(o))if(s.toUpperCase().startsWith(a)){let d=s.slice(a.length);t[d]=i;}return t}}}function k(e,n,r){let{onChange:a,debounce:o=100,files:t=[".env"]}=r??{},s,i=null,d=[],l=async()=>{try{let{resolve:c}=await import('./index.cjs');return s=await c.async(e,n),s}catch(c){throw console.error("[watch] Failed to load config:",c),c}},g=()=>{i&&clearTimeout(i),i=setTimeout(async()=>{try{let c=await l();a?.(c);}catch(c){console.error("[watch] Failed to reload config:",c);}},o);},{watch:h}=chunkKIQXH265_cjs.a("fs"),{join:y}=chunkKIQXH265_cjs.a("path");for(let c of t)try{let w=h(y(process.cwd(),c),g);d.push(w);}catch{}return l().catch(console.error),{getConfig:()=>s,stop:()=>{i&&clearTimeout(i);for(let c of d)c.close();}}}exports.TTL=f;exports.awsCache=T;exports.cached=R;exports.retry=C;exports.watch=k;exports.withAliases=v;exports.withComputed=x;exports.withNamespace=S;exports.withPrefix=b;exports.withTransform=$;
1
+ 'use strict';var chunk6FXCXA4R_cjs=require('./chunk-6FXCXA4R.cjs');require('./chunk-4YVXFL3I.cjs'),require('./chunk-4ZOF2PI4.cjs'),require('./chunk-BFLXBLZ3.cjs');var chunkKIQXH265_cjs=require('./chunk-KIQXH265.cjs');function C(e,n={}){let{ttl:r=3e5,maxAge:a=36e5,staleWhileRevalidate:o=false}=n,t=null,s={name:`cached(${e.name})`,metadata:{},async load(){let i=Date.now();if(!t||i-t.timestamp>a){let l=e.load?await e.load():{};return t={data:l,timestamp:i},s.metadata={cached:false},l}if(i-t.timestamp<r)return s.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)),s.metadata={cached:true,stale:true},t.data}let d=e.load?await e.load():{};return t={data:d,timestamp:i},s.metadata={cached:false},d}};return s}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 b(e={}){return {ttl:e.ttl??p.minutes5,maxAge:e.maxAge??p.hour,staleWhileRevalidate:e.staleWhileRevalidate??true,key:"aws-secrets"}}function x(e,n=3,r=1e3){return {name:`retry(${e.name})`,async load(){let a;for(let o=0;o<=n;o++)try{return e.load?await e.load():{}}catch(t){a=t instanceof Error?t:new Error(String(t)),o<n&&await new Promise(s=>setTimeout(s,r*Math.pow(2,o)));}throw a}}}function P(e,n){let r=n.toUpperCase();return {name:`withPrefix(${e.name}, ${n})`,async load(){let a=e.load?await e.load():{},o={};for(let[t,s]of Object.entries(a))if(t.toUpperCase().startsWith(r)){let i=t.slice(n.length);o[i]=s;}else o[t]=s;return o},loadSync(){if(!e.loadSync)throw new Error(`Resolver ${e.name} does not support sync loading`);let a=e.loadSync(),o={};for(let[t,s]of Object.entries(a))if(t.toUpperCase().startsWith(r)){let i=t.slice(n.length);o[i]=s;}else o[t]=s;return o}}}function $(e,n){let r={...e};for(let[a,o]of Object.entries(n))Object.defineProperty(r,a,{get(){return o(e)},enumerable:true,configurable:true});return r}function S(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[a,o]of Object.entries(n))for(let t of o)if(e[t]!==void 0){r[a]=e[t];break}return r}function k(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[a,o]of Object.entries(n))if(e[a]!==void 0)try{r[a]=o(e[a]);}catch(t){throw new Error(`Transform failed for ${a}: ${t instanceof Error?t.message:String(t)}`)}return r}function v(e,n){let a=`${n.toUpperCase()}_`;return {name:`withNamespace(${e.name}, ${n})`,async load(){let o=e.load?await e.load():{},t={};for(let[s,i]of Object.entries(o))if(s.toUpperCase().startsWith(a)){let d=s.slice(a.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[s,i]of Object.entries(o))if(s.toUpperCase().startsWith(a)){let d=s.slice(a.length);t[d]=i;}return t}}}function A(e,n,r){let{onChange:a,debounce:o=100,files:t=[".env"]}=r??{},s,i=null,d=[],l=async()=>{try{return await import('./index.cjs'),s=await chunk6FXCXA4R_cjs.c(e,n),s}catch(c){throw console.error("[watch] Failed to load config:",c),c}},u=()=>{i&&clearTimeout(i),i=setTimeout(async()=>{try{let c=await l();a?.(c);}catch(c){console.error("[watch] Failed to reload config:",c);}},o);},{watch:y}=chunkKIQXH265_cjs.a("fs"),{join:w}=chunkKIQXH265_cjs.a("path");for(let c of t)try{let R=y(w(process.cwd(),c),u);d.push(R);}catch{}return l().catch(console.error),{getConfig:()=>s,stop:()=>{i&&clearTimeout(i);for(let c of d)c.close();}}}exports.TTL=p;exports.awsCache=b;exports.cached=C;exports.retry=x;exports.watch=A;exports.withAliases=S;exports.withComputed=$;exports.withNamespace=v;exports.withPrefix=P;exports.withTransform=k;
@@ -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>(schema: Parameters<typeof resolveAsync>[0], resolvers: Parameters<typeof resolveAsync>[1], 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 };
package/dist/utils.d.ts CHANGED
@@ -1,8 +1,9 @@
1
- /**
2
- * Core utility resolvers and wrappers
3
- */
4
- import type { Resolver } from './types';
5
- export interface CacheOptions {
1
+ import { resolveAsync } from './index.js';
2
+ import { Resolver } from './types.js';
3
+ import './validation-types.js';
4
+ import './audit.js';
5
+
6
+ interface CacheOptions {
6
7
  /** Time to live in milliseconds (default: 5 minutes) */
7
8
  ttl?: number;
8
9
  /** Maximum age in milliseconds before forcing refresh (default: 1 hour) */
@@ -12,8 +13,8 @@ export interface CacheOptions {
12
13
  /** Custom cache key (useful for debugging or manual cache invalidation) */
13
14
  key?: string;
14
15
  }
15
- export declare function cached(resolver: Resolver, options?: CacheOptions): Resolver;
16
- export declare const TTL: {
16
+ declare function cached(resolver: Resolver, options?: CacheOptions): Resolver;
17
+ declare const TTL: {
17
18
  /** 30 seconds */
18
19
  readonly short: number;
19
20
  /** 1 minute */
@@ -29,7 +30,7 @@ export declare const TTL: {
29
30
  /** 24 hours */
30
31
  readonly day: number;
31
32
  };
32
- export declare function awsCache(options?: {
33
+ declare function awsCache(options?: {
33
34
  /** Cache duration for AWS secrets/parameters (default: 5 minutes) */
34
35
  ttl?: number;
35
36
  /** Maximum age before forcing refresh (default: 1 hour) */
@@ -37,7 +38,7 @@ export declare function awsCache(options?: {
37
38
  /** Enable stale-while-revalidate for better performance (default: true) */
38
39
  staleWhileRevalidate?: boolean;
39
40
  }): CacheOptions;
40
- export declare function retry(resolver: Resolver, maxRetries?: number, delayMs?: number): Resolver;
41
+ declare function retry(resolver: Resolver, maxRetries?: number, delayMs?: number): Resolver;
41
42
  /**
42
43
  * Wrap a resolver to strip a prefix from environment variable names
43
44
  * Useful for scoping environment variables (e.g., APP_PORT → PORT)
@@ -52,12 +53,12 @@ export declare function retry(resolver: Resolver, maxRetries?: number, delayMs?:
52
53
  * import { withPrefix } from 'node-env-resolver/utils';
53
54
  *
54
55
  * // Maps APP_PORT → PORT, APP_DATABASE_URL → DATABASE_URL
55
- * const config = await resolve.async(
56
- * [withPrefix(processEnv(), 'APP_'), { PORT: 3000, DATABASE_URL: 'postgres' }]
56
+ * const config = await resolveAsync(
57
+ * [withPrefix(processEnv(), 'APP_'), { PORT: 3000, DATABASE_URL: postgres() }]
57
58
  * );
58
59
  * ```
59
60
  */
60
- export declare function withPrefix(resolver: Resolver, prefix: string): Resolver;
61
+ declare function withPrefix(resolver: Resolver, prefix: string): Resolver;
61
62
  /**
62
63
  * Add computed/derived properties to resolved config
63
64
  *
@@ -87,7 +88,7 @@ export declare function withPrefix(resolver: Resolver, prefix: string): Resolver
87
88
  * console.log(config.isSecure); // false
88
89
  * ```
89
90
  */
90
- export declare function withComputed<TConfig extends Record<string, unknown>, TComputed extends Record<string, (config: TConfig) => unknown>>(config: TConfig, computed: TComputed): TConfig & {
91
+ declare function withComputed<TConfig extends Record<string, unknown>, TComputed extends Record<string, (config: TConfig) => unknown>>(config: TConfig, computed: TComputed): TConfig & {
91
92
  [K in keyof TComputed]: ReturnType<TComputed[K]>;
92
93
  };
93
94
  /**
@@ -104,15 +105,15 @@ export declare function withComputed<TConfig extends Record<string, unknown>, TC
104
105
  * import { withAliases } from 'node-env-resolver/utils';
105
106
  *
106
107
  * // Tries PORT, then HTTP_PORT, then SERVER_PORT (first found wins)
107
- * const config = await resolve.async(
108
+ * const config = await resolveAsync(
108
109
  * [withAliases(processEnv(), {
109
110
  * PORT: ['PORT', 'HTTP_PORT', 'SERVER_PORT'],
110
111
  * DATABASE_URL: ['DATABASE_URL', 'DB_URL', 'POSTGRES_URL']
111
- * }), { PORT: 3000, DATABASE_URL: 'postgres' }]
112
+ * }), { PORT: 3000, DATABASE_URL: postgres() }]
112
113
  * );
113
114
  * ```
114
115
  */
115
- export declare function withAliases(resolver: Resolver, aliases: Record<string, string[]>): Resolver;
116
+ declare function withAliases(resolver: Resolver, aliases: Record<string, string[]>): Resolver;
116
117
  /**
117
118
  * Wrap a resolver to apply custom transformations to values
118
119
  * Powerful utility for parsing, coercing, or enriching config values
@@ -126,7 +127,7 @@ export declare function withAliases(resolver: Resolver, aliases: Record<string,
126
127
  * import { resolve, processEnv } from 'node-env-resolver';
127
128
  * import { withTransform } from 'node-env-resolver/utils';
128
129
  *
129
- * const config = await resolve.async(
130
+ * const config = await resolveAsync(
130
131
  * [withTransform(processEnv(), {
131
132
  * // Parse comma-separated values
132
133
  * TAGS: (val) => val.split(',').map(s => s.trim()),
@@ -135,14 +136,14 @@ export declare function withAliases(resolver: Resolver, aliases: Record<string,
135
136
  * // Custom parsing
136
137
  * MAX_RETRIES: (val) => Math.min(parseInt(val, 10), 10)
137
138
  * }), {
138
- * TAGS: 'string',
139
- * API_URL: 'url',
139
+ * TAGS: string(),
140
+ * API_URL: url(),
140
141
  * MAX_RETRIES: 'number'
141
142
  * }]
142
143
  * );
143
144
  * ```
144
145
  */
145
- export declare function withTransform(resolver: Resolver, transforms: Record<string, (value: string) => string>): Resolver;
146
+ declare function withTransform(resolver: Resolver, transforms: Record<string, (value: string) => string>): Resolver;
146
147
  /**
147
148
  * Wrap a resolver to scope all keys to a namespace/prefix
148
149
  * Similar to withPrefix but adds the namespace instead of removing it
@@ -158,16 +159,16 @@ export declare function withTransform(resolver: Resolver, transforms: Record<str
158
159
  *
159
160
  * // Reads DATABASE_HOST, DATABASE_PORT from env
160
161
  * // But schema only needs HOST, PORT
161
- * const dbConfig = await resolve.async(
162
+ * const dbConfig = await resolveAsync(
162
163
  * [withNamespace(processEnv(), 'DATABASE'), {
163
- * HOST: 'string',
164
+ * HOST: string(),
164
165
  * PORT: 'port'
165
166
  * }]
166
167
  * );
167
168
  * // dbConfig: { HOST: '...', PORT: ... }
168
169
  * ```
169
170
  */
170
- export declare function withNamespace(resolver: Resolver, namespace: string): Resolver;
171
+ declare function withNamespace(resolver: Resolver, namespace: string): Resolver;
171
172
  /**
172
173
  * Watch configuration files and reload automatically
173
174
  * Perfect for development - auto-reload when .env files change
@@ -183,7 +184,7 @@ export declare function withNamespace(resolver: Resolver, namespace: string): Re
183
184
  * import { dotenv, processEnv } from 'node-env-resolver/resolvers';
184
185
  *
185
186
  * const { getConfig, stop } = watch(
186
- * { PORT: 3000, API_KEY: 'string' },
187
+ * { PORT: 3000, API_KEY: string() },
187
188
  * [processEnv(), dotenv()],
188
189
  * {
189
190
  * onChange: (config) => console.log('Config reloaded!', config)
@@ -197,7 +198,7 @@ export declare function withNamespace(resolver: Resolver, namespace: string): Re
197
198
  * process.on('SIGINT', () => stop());
198
199
  * ```
199
200
  */
200
- export declare function watch<T>(schema: Parameters<typeof import('./index').resolve.async>[0], resolvers: Parameters<typeof import('./index').resolve.async>[1], options?: {
201
+ declare function watch<T>(schema: Parameters<typeof resolveAsync>[0], resolvers: Parameters<typeof resolveAsync>[1], options?: {
201
202
  /** Callback when config changes */
202
203
  onChange?: (config: T) => void;
203
204
  /** Debounce delay in ms (default: 100) */
@@ -208,4 +209,5 @@ export declare function watch<T>(schema: Parameters<typeof import('./index').res
208
209
  getConfig: () => T;
209
210
  stop: () => void;
210
211
  };
211
- //# sourceMappingURL=utils.d.ts.map
212
+
213
+ export { type CacheOptions, TTL, awsCache, cached, retry, watch, withAliases, withComputed, withNamespace, withPrefix, withTransform };