@geekmidas/envkit 9.0.2 → 10.0.0-alpha.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 +2 -2
- package/dist/{EnvironmentBuilder-DDgLJAAo.cjs → EnvironmentBuilder-15SdFJdK.cjs} +2 -2
- package/dist/EnvironmentBuilder-15SdFJdK.cjs.map +1 -0
- package/dist/{EnvironmentBuilder-CFen3oIg.mjs → EnvironmentBuilder-C-2fViCT.mjs} +2 -2
- package/dist/EnvironmentBuilder-C-2fViCT.mjs.map +1 -0
- package/dist/{EnvironmentBuilder-DHfDXJUm.d.mts → EnvironmentBuilder-CoBQ9Xp2.d.mts} +2 -2
- package/dist/{EnvironmentBuilder-CNgcdzSR.d.cts.map → EnvironmentBuilder-CoBQ9Xp2.d.mts.map} +1 -1
- package/dist/{EnvironmentBuilder-CNgcdzSR.d.cts → EnvironmentBuilder-DeIle4QN.d.cts} +2 -2
- package/dist/{EnvironmentBuilder-DHfDXJUm.d.mts.map → EnvironmentBuilder-DeIle4QN.d.cts.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/sst.cjs +13 -6
- package/dist/sst.cjs.map +1 -1
- package/dist/sst.d.cts +15 -4
- package/dist/sst.d.cts.map +1 -1
- package/dist/sst.d.mts +15 -4
- package/dist/sst.d.mts.map +1 -1
- package/dist/sst.mjs +13 -6
- package/dist/sst.mjs.map +1 -1
- package/package.json +6 -2
- package/CHANGELOG.md +0 -115
- package/dist/EnvironmentBuilder-CFen3oIg.mjs.map +0 -1
- package/dist/EnvironmentBuilder-DDgLJAAo.cjs.map +0 -1
- package/docs/api-reference.md +0 -302
- package/docs/async-secrets-design.md +0 -355
- package/examples/basic-usage.ts +0 -386
- package/src/EnvironmentBuilder.ts +0 -192
- package/src/EnvironmentParser.ts +0 -330
- package/src/SnifferEnvironmentParser.ts +0 -334
- package/src/SstEnvValidator.ts +0 -369
- package/src/SstEnvironmentBuilder.ts +0 -343
- package/src/__tests__/ConfigParser.spec.ts +0 -394
- package/src/__tests__/EnvironmentBuilder.spec.ts +0 -254
- package/src/__tests__/EnvironmentParser.spec.ts +0 -839
- package/src/__tests__/SnifferEnvironmentParser.spec.ts +0 -644
- package/src/__tests__/SstEnvValidator.spec.ts +0 -236
- package/src/__tests__/SstEnvironmentBuilder.spec.ts +0 -397
- package/src/__tests__/credentials.integration.spec.ts +0 -239
- package/src/__tests__/credentials.spec.ts +0 -136
- package/src/__tests__/formatter.spec.ts +0 -268
- package/src/__tests__/sst.spec.ts +0 -437
- package/src/credentials.ts +0 -112
- package/src/formatter.ts +0 -146
- package/src/index.ts +0 -24
- package/src/sst.ts +0 -76
- package/sst-env.d.ts +0 -8
- package/tsconfig.json +0 -9
- package/tsdown.config.ts +0 -18
package/src/EnvironmentParser.ts
DELETED
|
@@ -1,330 +0,0 @@
|
|
|
1
|
-
import get from 'lodash.get';
|
|
2
|
-
import set from 'lodash.set';
|
|
3
|
-
import { z } from 'zod/v4';
|
|
4
|
-
import { formatParseError, isDevelopment } from './formatter.js';
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Parses and validates configuration objects against Zod schemas.
|
|
8
|
-
* Handles nested configurations and aggregates validation errors.
|
|
9
|
-
*
|
|
10
|
-
* @template TResponse - The shape of the configuration object
|
|
11
|
-
*/
|
|
12
|
-
export class ConfigParser<TResponse extends EmptyObject> {
|
|
13
|
-
/**
|
|
14
|
-
* Creates a new ConfigParser instance.
|
|
15
|
-
*
|
|
16
|
-
* @param config - The configuration object to parse
|
|
17
|
-
* @param envVars - Set of environment variable names that were accessed
|
|
18
|
-
*/
|
|
19
|
-
constructor(
|
|
20
|
-
private readonly config: TResponse,
|
|
21
|
-
private readonly envVars: Set<string> = new Set(),
|
|
22
|
-
) {}
|
|
23
|
-
/**
|
|
24
|
-
* Parses the config object and validates it against the Zod schemas
|
|
25
|
-
* @returns The parsed config object
|
|
26
|
-
*/
|
|
27
|
-
parse(): InferConfig<TResponse> {
|
|
28
|
-
const errors: z.core.$ZodIssue[] = [];
|
|
29
|
-
|
|
30
|
-
const parseDeep = <T>(config: T, path: string[] = []) => {
|
|
31
|
-
const result: EmptyObject = {};
|
|
32
|
-
|
|
33
|
-
if (config && typeof config !== 'object') {
|
|
34
|
-
return config;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
for (const key in config) {
|
|
38
|
-
const schema = config[key];
|
|
39
|
-
const currentPath = [...path, key];
|
|
40
|
-
|
|
41
|
-
if (schema instanceof z.ZodType) {
|
|
42
|
-
const parsed = schema.safeParse(undefined);
|
|
43
|
-
if (parsed.success) {
|
|
44
|
-
set(result, key, parsed.data);
|
|
45
|
-
} else {
|
|
46
|
-
// If the schema is invalid, assign the error
|
|
47
|
-
errors.push(
|
|
48
|
-
...parsed.error.issues.map((issue) => ({
|
|
49
|
-
...issue,
|
|
50
|
-
path: [...currentPath, ...(issue.path as string[])],
|
|
51
|
-
})),
|
|
52
|
-
);
|
|
53
|
-
}
|
|
54
|
-
} else if (schema) {
|
|
55
|
-
set(result, key, parseDeep(schema as EmptyObject, currentPath));
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
return result;
|
|
60
|
-
};
|
|
61
|
-
|
|
62
|
-
const parsedConfig = parseDeep(
|
|
63
|
-
this.config,
|
|
64
|
-
) as unknown as InferConfig<TResponse>;
|
|
65
|
-
|
|
66
|
-
if (errors.length > 0) {
|
|
67
|
-
const zodError = new z.ZodError(errors);
|
|
68
|
-
// In development, log a formatted error message before throwing
|
|
69
|
-
if (isDevelopment()) {
|
|
70
|
-
console.error(formatParseError(zodError));
|
|
71
|
-
}
|
|
72
|
-
throw zodError;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
return parsedConfig;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/**
|
|
79
|
-
* Returns an array of environment variable names that were accessed during config creation.
|
|
80
|
-
* This is useful for deployment and configuration management to know which env vars are required.
|
|
81
|
-
*
|
|
82
|
-
* @returns Array of environment variable names, sorted alphabetically
|
|
83
|
-
*
|
|
84
|
-
* @example
|
|
85
|
-
* ```typescript
|
|
86
|
-
* const config = envParser.create((get) => ({
|
|
87
|
-
* dbUrl: get('DATABASE_URL').string(),
|
|
88
|
-
* port: get('PORT').number()
|
|
89
|
-
* }));
|
|
90
|
-
*
|
|
91
|
-
* config.getEnvironmentVariables(); // ['DATABASE_URL', 'PORT']
|
|
92
|
-
* ```
|
|
93
|
-
*/
|
|
94
|
-
getEnvironmentVariables(): string[] {
|
|
95
|
-
return Array.from(this.envVars).sort();
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
/**
|
|
100
|
-
* Parses environment variables with type-safe validation using Zod schemas.
|
|
101
|
-
* Provides a fluent API for defining environment variable schemas with automatic
|
|
102
|
-
* error context enrichment.
|
|
103
|
-
*
|
|
104
|
-
* @template T - The type of the configuration object (typically process.env)
|
|
105
|
-
*
|
|
106
|
-
* @example
|
|
107
|
-
* ```typescript
|
|
108
|
-
* const config = new EnvironmentParser(process.env)
|
|
109
|
-
* .create((get) => ({
|
|
110
|
-
* port: get('PORT').string().transform(Number).default(3000),
|
|
111
|
-
* database: {
|
|
112
|
-
* url: get('DATABASE_URL').string().url()
|
|
113
|
-
* }
|
|
114
|
-
* }))
|
|
115
|
-
* .parse();
|
|
116
|
-
* ```
|
|
117
|
-
*/
|
|
118
|
-
export class EnvironmentParser<T extends EmptyObject> {
|
|
119
|
-
/**
|
|
120
|
-
* Set to track which environment variable names have been accessed
|
|
121
|
-
*/
|
|
122
|
-
private readonly accessedVars: Set<string> = new Set();
|
|
123
|
-
|
|
124
|
-
/**
|
|
125
|
-
* Creates a new EnvironmentParser instance.
|
|
126
|
-
*
|
|
127
|
-
* @param config - The configuration object to parse (typically process.env)
|
|
128
|
-
*/
|
|
129
|
-
constructor(private readonly config: T) {}
|
|
130
|
-
|
|
131
|
-
/**
|
|
132
|
-
* Wraps a Zod schema to intercept parse/safeParse calls and enrich error messages
|
|
133
|
-
* with environment variable context.
|
|
134
|
-
*
|
|
135
|
-
* @param schema - The Zod schema to wrap
|
|
136
|
-
* @param name - The environment variable name for error context
|
|
137
|
-
* @returns A wrapped Zod schema with enhanced error reporting
|
|
138
|
-
*/
|
|
139
|
-
private wrapSchema = (schema: z.ZodType, name: string): z.ZodType => {
|
|
140
|
-
// Create a proxy that intercepts all method calls on the schema
|
|
141
|
-
return new Proxy(schema, {
|
|
142
|
-
get: (target, prop) => {
|
|
143
|
-
if (prop === 'parse') {
|
|
144
|
-
return () => {
|
|
145
|
-
const value = get(this.config, name);
|
|
146
|
-
try {
|
|
147
|
-
return target.parse(value);
|
|
148
|
-
} catch (error) {
|
|
149
|
-
if (error instanceof z.ZodError) {
|
|
150
|
-
// Modify the error to include the environment variable name
|
|
151
|
-
const modifiedIssues = error.issues.map((issue) => ({
|
|
152
|
-
...issue,
|
|
153
|
-
message: `Environment variable "${name}": ${issue.message}`,
|
|
154
|
-
path: [name, ...issue.path],
|
|
155
|
-
}));
|
|
156
|
-
throw new z.ZodError(modifiedIssues);
|
|
157
|
-
}
|
|
158
|
-
throw error;
|
|
159
|
-
}
|
|
160
|
-
};
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
if (prop === 'safeParse') {
|
|
164
|
-
return () => {
|
|
165
|
-
const value = get(this.config, name);
|
|
166
|
-
const result = target.safeParse(value);
|
|
167
|
-
|
|
168
|
-
if (!result.success) {
|
|
169
|
-
// Modify the error to include the environment variable name
|
|
170
|
-
const modifiedIssues = result.error.issues.map(
|
|
171
|
-
(issue: z.core.$ZodIssue) => ({
|
|
172
|
-
...issue,
|
|
173
|
-
message: `Environment variable "${name}": ${issue.message}`,
|
|
174
|
-
path: [name, ...issue.path],
|
|
175
|
-
}),
|
|
176
|
-
);
|
|
177
|
-
return {
|
|
178
|
-
success: false as const,
|
|
179
|
-
error: new z.ZodError(modifiedIssues),
|
|
180
|
-
};
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
return result;
|
|
184
|
-
};
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
// For any method that returns a new schema (like transform, optional, etc.),
|
|
188
|
-
// wrap the result as well
|
|
189
|
-
const originalProp = target[prop as keyof typeof target];
|
|
190
|
-
if (typeof originalProp === 'function') {
|
|
191
|
-
return (...args: any[]) => {
|
|
192
|
-
const result = originalProp.apply(target, args);
|
|
193
|
-
// If the result is a ZodType, wrap it too
|
|
194
|
-
if (result && typeof result === 'object' && 'parse' in result) {
|
|
195
|
-
return this.wrapSchema(result, name);
|
|
196
|
-
}
|
|
197
|
-
return result;
|
|
198
|
-
};
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
return originalProp;
|
|
202
|
-
},
|
|
203
|
-
});
|
|
204
|
-
};
|
|
205
|
-
|
|
206
|
-
/**
|
|
207
|
-
* Creates a proxied version of the Zod object that wraps all schema creators
|
|
208
|
-
* to provide enhanced error messages with environment variable context.
|
|
209
|
-
*
|
|
210
|
-
* @param name - The environment variable name
|
|
211
|
-
* @returns A proxied Zod object with wrapped schema creators
|
|
212
|
-
*/
|
|
213
|
-
private getZodGetter = (name: string) => {
|
|
214
|
-
// Track that this environment variable was accessed
|
|
215
|
-
this.accessedVars.add(name);
|
|
216
|
-
|
|
217
|
-
// Return an object that has all Zod schemas but with our wrapper
|
|
218
|
-
return new Proxy(
|
|
219
|
-
{ ...z },
|
|
220
|
-
{
|
|
221
|
-
get: (target, prop) => {
|
|
222
|
-
// deno-lint-ignore ban-ts-comment
|
|
223
|
-
// @ts-expect-error
|
|
224
|
-
const value = target[prop];
|
|
225
|
-
|
|
226
|
-
if (typeof value === 'function') {
|
|
227
|
-
// Return a wrapper around each Zod schema creator
|
|
228
|
-
return (...args: any[]) => {
|
|
229
|
-
const schema = value(...args);
|
|
230
|
-
return this.wrapSchema(schema, name);
|
|
231
|
-
};
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
// Handle objects like z.coerce
|
|
235
|
-
if (value && typeof value === 'object') {
|
|
236
|
-
return new Proxy(value, {
|
|
237
|
-
get: (nestedTarget, nestedProp) => {
|
|
238
|
-
const nestedValue =
|
|
239
|
-
nestedTarget[nestedProp as keyof typeof nestedTarget];
|
|
240
|
-
if (typeof nestedValue === 'function') {
|
|
241
|
-
return (...args: any[]) => {
|
|
242
|
-
const schema = nestedValue(...args);
|
|
243
|
-
return this.wrapSchema(schema, name);
|
|
244
|
-
};
|
|
245
|
-
}
|
|
246
|
-
return nestedValue;
|
|
247
|
-
},
|
|
248
|
-
});
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
return value;
|
|
252
|
-
},
|
|
253
|
-
},
|
|
254
|
-
);
|
|
255
|
-
};
|
|
256
|
-
|
|
257
|
-
/**
|
|
258
|
-
* Creates a new ConfigParser object that can be used to parse the config object
|
|
259
|
-
*
|
|
260
|
-
* @param builder - A function that takes a getter function and returns a config object
|
|
261
|
-
* @returns A ConfigParser object that can be used to parse the config object
|
|
262
|
-
*/
|
|
263
|
-
create<TReturn extends EmptyObject>(
|
|
264
|
-
builder: (get: EnvFetcher) => TReturn,
|
|
265
|
-
): ConfigParser<TReturn> {
|
|
266
|
-
const config = builder(this.getZodGetter);
|
|
267
|
-
return new ConfigParser(config, this.accessedVars);
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
/**
|
|
271
|
-
* Returns an array of environment variable names that were accessed via the getter.
|
|
272
|
-
* This is useful for build-time analysis to determine which env vars a service needs.
|
|
273
|
-
*
|
|
274
|
-
* @returns Array of environment variable names, sorted alphabetically
|
|
275
|
-
*
|
|
276
|
-
* @example
|
|
277
|
-
* ```typescript
|
|
278
|
-
* const sniffer = new EnvironmentParser({});
|
|
279
|
-
* service.register(sniffer);
|
|
280
|
-
* const envVars = sniffer.getEnvironmentVariables(); // ['DATABASE_URL', 'PORT']
|
|
281
|
-
* ```
|
|
282
|
-
*/
|
|
283
|
-
getEnvironmentVariables(): string[] {
|
|
284
|
-
return Array.from(this.accessedVars).sort();
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
/**
|
|
289
|
-
* Infers the TypeScript type of a configuration object based on its Zod schemas.
|
|
290
|
-
* Recursively processes nested objects and extracts types from Zod schemas.
|
|
291
|
-
*
|
|
292
|
-
* @template T - The configuration object type
|
|
293
|
-
*/
|
|
294
|
-
export type InferConfig<T extends EmptyObject> = {
|
|
295
|
-
[K in keyof T]: T[K] extends z.ZodSchema
|
|
296
|
-
? z.infer<T[K]>
|
|
297
|
-
: T[K] extends Record<string, unknown>
|
|
298
|
-
? InferConfig<T[K]>
|
|
299
|
-
: T[K];
|
|
300
|
-
};
|
|
301
|
-
|
|
302
|
-
/**
|
|
303
|
-
* Function type for fetching environment variables with Zod validation.
|
|
304
|
-
* Returns a Zod object scoped to a specific environment variable.
|
|
305
|
-
*
|
|
306
|
-
* @template TPath - The environment variable path type
|
|
307
|
-
* @param name - The environment variable name
|
|
308
|
-
* @returns A Zod object for defining the schema
|
|
309
|
-
*/
|
|
310
|
-
export type EnvFetcher<TPath extends string = string> = (
|
|
311
|
-
name: TPath,
|
|
312
|
-
) => typeof z;
|
|
313
|
-
|
|
314
|
-
/**
|
|
315
|
-
* Function type for building environment configuration objects.
|
|
316
|
-
* Takes an EnvFetcher and returns a configuration object with Zod schemas.
|
|
317
|
-
*
|
|
318
|
-
* @template TResponse - The response configuration object type
|
|
319
|
-
* @param get - The environment variable fetcher function
|
|
320
|
-
* @returns The configuration object with Zod schemas
|
|
321
|
-
*/
|
|
322
|
-
export type EnvironmentBuilder<TResponse extends EmptyObject> = (
|
|
323
|
-
get: EnvFetcher,
|
|
324
|
-
) => TResponse;
|
|
325
|
-
|
|
326
|
-
/**
|
|
327
|
-
* Type alias for a generic object with unknown values.
|
|
328
|
-
* Used as a constraint for configuration objects.
|
|
329
|
-
*/
|
|
330
|
-
export type EmptyObject = Record<string | number | symbol, unknown>;
|
|
@@ -1,334 +0,0 @@
|
|
|
1
|
-
import { z } from 'zod/v4';
|
|
2
|
-
import {
|
|
3
|
-
ConfigParser,
|
|
4
|
-
type EmptyObject,
|
|
5
|
-
type EnvFetcher,
|
|
6
|
-
} from './EnvironmentParser';
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* A specialized EnvironmentParser for build-time analysis that tracks
|
|
10
|
-
* which environment variables are accessed without requiring actual values.
|
|
11
|
-
*
|
|
12
|
-
* Unlike the regular EnvironmentParser, the sniffer:
|
|
13
|
-
* - Always returns mock values from .parse() and .safeParse()
|
|
14
|
-
* - Never throws validation errors
|
|
15
|
-
* - Tracks all accessed environment variable names
|
|
16
|
-
*
|
|
17
|
-
* This allows service registration to succeed during build-time analysis
|
|
18
|
-
* even when environment variables are not set.
|
|
19
|
-
*
|
|
20
|
-
* @example
|
|
21
|
-
* ```typescript
|
|
22
|
-
* const sniffer = new SnifferEnvironmentParser();
|
|
23
|
-
* await service.register(sniffer); // Always succeeds
|
|
24
|
-
* const envVars = sniffer.getEnvironmentVariables(); // ['DATABASE_URL', 'API_KEY']
|
|
25
|
-
* ```
|
|
26
|
-
*/
|
|
27
|
-
export class SnifferEnvironmentParser<_T extends EmptyObject = EmptyObject> {
|
|
28
|
-
private readonly accessedVars: Set<string> = new Set();
|
|
29
|
-
private readonly optionalVars: Set<string> = new Set();
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Wraps a Zod schema to always return mock values.
|
|
33
|
-
* This ensures .parse() and .safeParse() never fail.
|
|
34
|
-
* Also detects when .optional() or .default() is called to track optional vars.
|
|
35
|
-
*/
|
|
36
|
-
private wrapSchema = (schema: z.ZodType, name: string): z.ZodType => {
|
|
37
|
-
return new Proxy(schema, {
|
|
38
|
-
get: (target, prop) => {
|
|
39
|
-
if (prop === 'parse') {
|
|
40
|
-
return () => this.getMockValue(target);
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
if (prop === 'safeParse') {
|
|
44
|
-
return () => ({
|
|
45
|
-
success: true as const,
|
|
46
|
-
data: this.getMockValue(target),
|
|
47
|
-
});
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
// Detect .optional() or .default() — mark the variable as optional
|
|
51
|
-
if (prop === 'optional' || prop === 'default') {
|
|
52
|
-
this.optionalVars.add(name);
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
const originalProp = target[prop as keyof typeof target];
|
|
56
|
-
if (typeof originalProp === 'function') {
|
|
57
|
-
return (...args: any[]) => {
|
|
58
|
-
const result = originalProp.apply(target, args);
|
|
59
|
-
if (result && typeof result === 'object' && 'parse' in result) {
|
|
60
|
-
return this.wrapSchema(result, name);
|
|
61
|
-
}
|
|
62
|
-
return result;
|
|
63
|
-
};
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
return originalProp;
|
|
67
|
-
},
|
|
68
|
-
});
|
|
69
|
-
};
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* Returns a mock value based on the Zod schema type.
|
|
73
|
-
*/
|
|
74
|
-
private getMockValue(schema: z.ZodType): unknown {
|
|
75
|
-
// Return type-appropriate mock values
|
|
76
|
-
if (schema instanceof z.ZodString) return '';
|
|
77
|
-
if (schema instanceof z.ZodNumber) return 0;
|
|
78
|
-
if (schema instanceof z.ZodBoolean) return false;
|
|
79
|
-
if (schema instanceof z.ZodArray) return [];
|
|
80
|
-
if (schema instanceof z.ZodOptional) return undefined;
|
|
81
|
-
if (schema instanceof z.ZodNullable) return null;
|
|
82
|
-
|
|
83
|
-
// For object schemas, build mock object from shape
|
|
84
|
-
if (schema instanceof z.ZodObject && schema.shape) {
|
|
85
|
-
const result: Record<string, unknown> = {};
|
|
86
|
-
for (const [key, value] of Object.entries(schema.shape)) {
|
|
87
|
-
if (value instanceof z.ZodType) {
|
|
88
|
-
result[key] = this.getMockValue(value);
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
return result;
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
return '';
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/**
|
|
98
|
-
* Creates a proxied Zod getter that tracks environment variable access.
|
|
99
|
-
*/
|
|
100
|
-
private getZodGetter = (name: string) => {
|
|
101
|
-
this.accessedVars.add(name);
|
|
102
|
-
|
|
103
|
-
return new Proxy(
|
|
104
|
-
{ ...z },
|
|
105
|
-
{
|
|
106
|
-
get: (target, prop) => {
|
|
107
|
-
// @ts-expect-error
|
|
108
|
-
const value = target[prop];
|
|
109
|
-
|
|
110
|
-
if (typeof value === 'function') {
|
|
111
|
-
return (...args: any[]) => {
|
|
112
|
-
const schema = value(...args);
|
|
113
|
-
return this.wrapSchema(schema, name);
|
|
114
|
-
};
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
if (value && typeof value === 'object') {
|
|
118
|
-
return new Proxy(value, {
|
|
119
|
-
get: (nestedTarget, nestedProp) => {
|
|
120
|
-
const nestedValue =
|
|
121
|
-
nestedTarget[nestedProp as keyof typeof nestedTarget];
|
|
122
|
-
if (typeof nestedValue === 'function') {
|
|
123
|
-
return (...args: any[]) => {
|
|
124
|
-
const schema = nestedValue(...args);
|
|
125
|
-
return this.wrapSchema(schema, name);
|
|
126
|
-
};
|
|
127
|
-
}
|
|
128
|
-
return nestedValue;
|
|
129
|
-
},
|
|
130
|
-
});
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
return value;
|
|
134
|
-
},
|
|
135
|
-
},
|
|
136
|
-
);
|
|
137
|
-
};
|
|
138
|
-
|
|
139
|
-
/**
|
|
140
|
-
* Creates a ConfigParser that will return mock values when parsed.
|
|
141
|
-
*/
|
|
142
|
-
create<TReturn extends EmptyObject>(
|
|
143
|
-
builder: (get: EnvFetcher) => TReturn,
|
|
144
|
-
): ConfigParser<TReturn> {
|
|
145
|
-
const config = builder(this.getZodGetter);
|
|
146
|
-
return new SnifferConfigParser(config, this.accessedVars);
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
/**
|
|
150
|
-
* Returns all environment variable names that were accessed.
|
|
151
|
-
*
|
|
152
|
-
* @param opts.markOptional - When true, optional variables (those accessed
|
|
153
|
-
* via `.optional()` or `.default()`) are suffixed with `?` (e.g. `PORT?`).
|
|
154
|
-
*/
|
|
155
|
-
getEnvironmentVariables(opts?: { markOptional?: boolean }): string[] {
|
|
156
|
-
const vars = Array.from(this.accessedVars).sort();
|
|
157
|
-
if (!opts?.markOptional) return vars;
|
|
158
|
-
return vars.map((name) =>
|
|
159
|
-
this.optionalVars.has(name) ? `${name}?` : name,
|
|
160
|
-
);
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
/**
|
|
164
|
-
* Returns all environment variable names that were accessed via
|
|
165
|
-
* `.optional()` or `.default()` — i.e. variables that are not required.
|
|
166
|
-
*/
|
|
167
|
-
getOptionalVariables(): string[] {
|
|
168
|
-
return Array.from(this.optionalVars).sort();
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
/**
|
|
173
|
-
* A ConfigParser that always succeeds with mock values.
|
|
174
|
-
*/
|
|
175
|
-
class SnifferConfigParser<
|
|
176
|
-
TResponse extends EmptyObject,
|
|
177
|
-
> extends ConfigParser<TResponse> {
|
|
178
|
-
override parse(): any {
|
|
179
|
-
return this.parseWithMocks(this.getConfig());
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
private getConfig(): TResponse {
|
|
183
|
-
// Access the private config via any cast
|
|
184
|
-
return (this as any).config;
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
private parseWithMocks<T>(config: T): any {
|
|
188
|
-
const result: EmptyObject = {};
|
|
189
|
-
|
|
190
|
-
if (config && typeof config !== 'object') {
|
|
191
|
-
return config;
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
for (const key in config) {
|
|
195
|
-
const schema = config[key];
|
|
196
|
-
|
|
197
|
-
if (schema instanceof z.ZodType) {
|
|
198
|
-
// Use safeParse which will return mock values from our wrapped schema
|
|
199
|
-
const parsed = schema.safeParse(undefined);
|
|
200
|
-
result[key] = parsed.success
|
|
201
|
-
? parsed.data
|
|
202
|
-
: this.getDefaultForSchema(schema);
|
|
203
|
-
} else if (schema && typeof schema === 'object') {
|
|
204
|
-
result[key] = this.parseWithMocks(schema as EmptyObject);
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
return result;
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
private getDefaultForSchema(schema: z.ZodType): unknown {
|
|
212
|
-
if (schema instanceof z.ZodString) return '';
|
|
213
|
-
if (schema instanceof z.ZodNumber) return 0;
|
|
214
|
-
if (schema instanceof z.ZodBoolean) return false;
|
|
215
|
-
if (schema instanceof z.ZodArray) return [];
|
|
216
|
-
if (schema instanceof z.ZodOptional) return undefined;
|
|
217
|
-
if (schema instanceof z.ZodNullable) return null;
|
|
218
|
-
|
|
219
|
-
if (schema instanceof z.ZodObject && schema.shape) {
|
|
220
|
-
const result: Record<string, unknown> = {};
|
|
221
|
-
for (const [key, value] of Object.entries(schema.shape)) {
|
|
222
|
-
if (value instanceof z.ZodType) {
|
|
223
|
-
result[key] = this.getDefaultForSchema(value);
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
return result;
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
return '';
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
/**
|
|
234
|
-
* Result of sniffing with fire-and-forget handling.
|
|
235
|
-
*/
|
|
236
|
-
export interface SniffResult {
|
|
237
|
-
/** All environment variable names that were accessed during sniffing */
|
|
238
|
-
envVars: string[];
|
|
239
|
-
/**
|
|
240
|
-
* Subset of envVars that are optional (accessed via `.optional()` or
|
|
241
|
-
* `.default()`). These do not need to be present for the app to start.
|
|
242
|
-
*/
|
|
243
|
-
optionalEnvVars: string[];
|
|
244
|
-
/** Error thrown during sniffing (env vars may still be captured) */
|
|
245
|
-
error?: Error;
|
|
246
|
-
/** Unhandled promise rejections captured during sniffing */
|
|
247
|
-
unhandledRejections: Error[];
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
/**
|
|
251
|
-
* Options for sniffing with fire-and-forget handling.
|
|
252
|
-
*/
|
|
253
|
-
export interface SniffOptions {
|
|
254
|
-
/**
|
|
255
|
-
* Time in milliseconds to wait for fire-and-forget promises to settle.
|
|
256
|
-
* Some libraries like better-auth create async operations that may reject
|
|
257
|
-
* after the initial event loop tick.
|
|
258
|
-
* @default 100
|
|
259
|
-
*/
|
|
260
|
-
settleTimeMs?: number;
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
/**
|
|
264
|
-
* Executes a sniffing operation with fire-and-forget handling.
|
|
265
|
-
*
|
|
266
|
-
* This function:
|
|
267
|
-
* 1. Captures unhandled promise rejections during the operation
|
|
268
|
-
* 2. Waits for async operations to settle before returning
|
|
269
|
-
* 3. Gracefully handles errors without throwing
|
|
270
|
-
*
|
|
271
|
-
* Use this when sniffing environment variables from code that may:
|
|
272
|
-
* - Throw synchronous errors
|
|
273
|
-
* - Create fire-and-forget promises that reject
|
|
274
|
-
* - Have async initialization that may fail
|
|
275
|
-
*
|
|
276
|
-
* @param sniffer - The SnifferEnvironmentParser instance to use
|
|
277
|
-
* @param operation - The async operation to execute (e.g., service.register)
|
|
278
|
-
* @param options - Optional configuration
|
|
279
|
-
* @returns SniffResult with env vars and any errors encountered
|
|
280
|
-
*
|
|
281
|
-
* @example
|
|
282
|
-
* ```typescript
|
|
283
|
-
* const sniffer = new SnifferEnvironmentParser();
|
|
284
|
-
* const result = await sniffWithFireAndForget(sniffer, async () => {
|
|
285
|
-
* await service.register({ envParser: sniffer });
|
|
286
|
-
* });
|
|
287
|
-
* console.log('Env vars:', result.envVars);
|
|
288
|
-
* console.log('Error:', result.error);
|
|
289
|
-
* console.log('Unhandled rejections:', result.unhandledRejections);
|
|
290
|
-
* ```
|
|
291
|
-
*/
|
|
292
|
-
export async function sniffWithFireAndForget(
|
|
293
|
-
sniffer: SnifferEnvironmentParser,
|
|
294
|
-
operation: () => unknown | Promise<unknown>,
|
|
295
|
-
options: SniffOptions = {},
|
|
296
|
-
): Promise<SniffResult> {
|
|
297
|
-
const { settleTimeMs = 100 } = options;
|
|
298
|
-
const unhandledRejections: Error[] = [];
|
|
299
|
-
|
|
300
|
-
// Capture unhandled rejections during sniffing (fire-and-forget promises)
|
|
301
|
-
// Libraries like better-auth create async operations that may reject after
|
|
302
|
-
// the initial event loop tick
|
|
303
|
-
const captureRejection = (reason: unknown) => {
|
|
304
|
-
const err = reason instanceof Error ? reason : new Error(String(reason));
|
|
305
|
-
unhandledRejections.push(err);
|
|
306
|
-
};
|
|
307
|
-
process.on('unhandledRejection', captureRejection);
|
|
308
|
-
|
|
309
|
-
let error: Error | undefined;
|
|
310
|
-
|
|
311
|
-
try {
|
|
312
|
-
const result = operation();
|
|
313
|
-
|
|
314
|
-
// Handle async result
|
|
315
|
-
if (result && typeof result === 'object' && 'then' in result) {
|
|
316
|
-
await Promise.resolve(result).catch((e) => {
|
|
317
|
-
error = e instanceof Error ? e : new Error(String(e));
|
|
318
|
-
});
|
|
319
|
-
}
|
|
320
|
-
} catch (e) {
|
|
321
|
-
error = e instanceof Error ? e : new Error(String(e));
|
|
322
|
-
} finally {
|
|
323
|
-
// Wait for fire-and-forget promises to settle
|
|
324
|
-
await new Promise((resolve) => setTimeout(resolve, settleTimeMs));
|
|
325
|
-
process.off('unhandledRejection', captureRejection);
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
return {
|
|
329
|
-
envVars: sniffer.getEnvironmentVariables(),
|
|
330
|
-
optionalEnvVars: sniffer.getOptionalVariables(),
|
|
331
|
-
error,
|
|
332
|
-
unhandledRejections,
|
|
333
|
-
};
|
|
334
|
-
}
|