@pawells/config 2.1.6-rc1
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 +200 -0
- package/dist/errors.d.ts +70 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +79 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/manager.d.ts +73 -0
- package/dist/manager.d.ts.map +1 -0
- package/dist/manager.js +141 -0
- package/dist/schema.factory.d.ts +66 -0
- package/dist/schema.factory.d.ts.map +1 -0
- package/dist/schema.factory.js +128 -0
- package/package.json +38 -0
package/README.md
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
# @pawells/config
|
|
2
|
+
|
|
3
|
+
[](https://github.com/PhillipAWells/common/actions/workflows/ci.yml)
|
|
4
|
+
[](https://nodejs.org)
|
|
5
|
+
[](https://www.npmjs.com/package/@pawells/config)
|
|
6
|
+
[](./LICENSE)
|
|
7
|
+
|
|
8
|
+
## Description
|
|
9
|
+
|
|
10
|
+
Runtime configuration manager with Zod schema validation. Provides a singleton `ConfigManager` class for registering typed configuration schemas, setting values from multiple sources (defaults and runtime overrides), and retrieving strongly-typed configuration values with automatic validation. Supports environment variables, CLI arguments, and programmatic configuration.
|
|
11
|
+
|
|
12
|
+
## Requirements
|
|
13
|
+
|
|
14
|
+
- **Node.js**: 22.0.0 or later
|
|
15
|
+
- **TypeScript**: 6.0.0 or later (if consuming from source)
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
Install from npm:
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
npm install @pawells/config
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Or with yarn:
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
yarn add @pawells/config
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Quick Start
|
|
32
|
+
|
|
33
|
+
### Using CreateConfigSchema (Recommended)
|
|
34
|
+
|
|
35
|
+
The `CreateConfigSchema` factory is the recommended pattern for most use cases. It provides automatic environment variable parsing with a prefix and strongly-typed access to configuration values.
|
|
36
|
+
|
|
37
|
+
```typescript
|
|
38
|
+
import { z } from 'zod/v4';
|
|
39
|
+
import { CreateConfigSchema } from '@pawells/config';
|
|
40
|
+
|
|
41
|
+
// Define your configuration schema
|
|
42
|
+
const SERVICE_CONFIG_SCHEMA = z.object({
|
|
43
|
+
PORT: z.coerce.number().int().positive().default(3000),
|
|
44
|
+
HOST: z.string().default('localhost'),
|
|
45
|
+
DEBUG: z.boolean().default(false),
|
|
46
|
+
DATABASE_URL: z.string().url(),
|
|
47
|
+
API_TIMEOUT: z.coerce.number().int().positive().default(30000),
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
// Create a typed config object with 'SERVICE_' prefix
|
|
51
|
+
export const ServiceConfig = CreateConfigSchema(SERVICE_CONFIG_SCHEMA, 'SERVICE_');
|
|
52
|
+
|
|
53
|
+
// Register all schemas
|
|
54
|
+
ServiceConfig.Register();
|
|
55
|
+
|
|
56
|
+
// Parse environment variables (SERVICE_PORT, SERVICE_HOST, SERVICE_DEBUG, etc.)
|
|
57
|
+
ServiceConfig.ParseENV();
|
|
58
|
+
|
|
59
|
+
// Get typed values
|
|
60
|
+
const port = ServiceConfig.Get('PORT'); // number, typed
|
|
61
|
+
const host = ServiceConfig.Get('HOST'); // string, typed
|
|
62
|
+
const debug = ServiceConfig.Get('DEBUG'); // boolean, typed
|
|
63
|
+
|
|
64
|
+
console.log(`Server running on ${host}:${port}`);
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### Retrieving and Validating Values
|
|
68
|
+
|
|
69
|
+
```typescript
|
|
70
|
+
// Get a typed configuration value (guaranteed type-safe)
|
|
71
|
+
const timeout = ServiceConfig.Get('API_TIMEOUT'); // number
|
|
72
|
+
|
|
73
|
+
// Validate a value before setting it
|
|
74
|
+
const isValid = ServiceConfig.Validate('PORT', '8080'); // true if valid
|
|
75
|
+
|
|
76
|
+
// Set configuration values at runtime
|
|
77
|
+
ServiceConfig.Set('DEBUG', true, 'OVERRIDE');
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### Advanced: Using ConfigManager Directly
|
|
81
|
+
|
|
82
|
+
For advanced scenarios where you need direct schema control or custom management, use `ConfigManager`:
|
|
83
|
+
|
|
84
|
+
```typescript
|
|
85
|
+
import { ConfigManager } from '@pawells/config';
|
|
86
|
+
import { z } from 'zod/v4';
|
|
87
|
+
|
|
88
|
+
// Register individual schemas
|
|
89
|
+
ConfigManager.Register('DATABASE_URL', z.string().url(), 'postgresql://localhost/mydb');
|
|
90
|
+
ConfigManager.Register('API_KEY', z.string().min(32), 'default-key');
|
|
91
|
+
|
|
92
|
+
// Set and retrieve values
|
|
93
|
+
ConfigManager.Set('DATABASE_URL', process.env.DATABASE_URL);
|
|
94
|
+
const dbUrl = ConfigManager.Get('DATABASE_URL');
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### Error Handling
|
|
98
|
+
|
|
99
|
+
```typescript
|
|
100
|
+
import {
|
|
101
|
+
ConfigurationNotRegisteredError,
|
|
102
|
+
ConfigurationNotSetError,
|
|
103
|
+
ConfigurationError,
|
|
104
|
+
} from '@pawells/config';
|
|
105
|
+
|
|
106
|
+
try {
|
|
107
|
+
// Attempt to retrieve a value
|
|
108
|
+
const value = ServiceConfig.Get('UNKNOWN_KEY');
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (error instanceof ConfigurationNotRegisteredError) {
|
|
111
|
+
console.error('Configuration key not registered:', error.message);
|
|
112
|
+
}
|
|
113
|
+
if (error instanceof ConfigurationNotSetError) {
|
|
114
|
+
console.error('Configuration value not set:', error.message);
|
|
115
|
+
}
|
|
116
|
+
if (error instanceof ConfigurationError) {
|
|
117
|
+
console.error('Validation failed:', error.message);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## API Reference
|
|
123
|
+
|
|
124
|
+
### CreateConfigSchema Factory (Recommended)
|
|
125
|
+
|
|
126
|
+
The `CreateConfigSchema` factory is the primary recommended API for most use cases. It creates a strongly-typed configuration schema object from a Zod schema.
|
|
127
|
+
|
|
128
|
+
**Signature:**
|
|
129
|
+
```typescript
|
|
130
|
+
CreateConfigSchema<TSchema extends z.ZodRawShape>(
|
|
131
|
+
schema: z.ZodObject<TSchema>,
|
|
132
|
+
prefix: string
|
|
133
|
+
): IConfigSchemaObject<z.infer<typeof schema>>
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
**Parameters:**
|
|
137
|
+
- `schema` — A Zod object schema defining your configuration structure
|
|
138
|
+
- `prefix` — Environment variable prefix (e.g., `'SERVICE_'` for `SERVICE_PORT`, `SERVICE_HOST`)
|
|
139
|
+
|
|
140
|
+
**Returns:** An `IConfigSchemaObject` with strongly-typed methods for configuration management.
|
|
141
|
+
|
|
142
|
+
### IConfigSchemaObject Methods
|
|
143
|
+
|
|
144
|
+
These methods are returned by `CreateConfigSchema` and provide a strongly-typed interface to your configuration.
|
|
145
|
+
|
|
146
|
+
| Method | Signature | Description |
|
|
147
|
+
|--------|-----------|-------------|
|
|
148
|
+
| `Register` | `Register(): void` | Register all schema fields with `ConfigManager`, extracting default values from the schema. Call once at application startup. |
|
|
149
|
+
| `Get` | `Get<K extends TKeys>(key: K): TConfig[K]` | Retrieve a typed configuration value by key. The return type is automatically inferred from your schema. |
|
|
150
|
+
| `Set` | `Set<K extends TKeys>(key: K, value: TConfig[K], source?: TConfigSource): void` | Set a configuration value with optional source (`'DEFAULT'` or `'OVERRIDE'`, defaults to `'OVERRIDE'`). Validates the value against the schema. |
|
|
151
|
+
| `Validate` | `Validate<K extends TKeys>(key: K, value: unknown): boolean` | Validate a value against its schema without setting it. Returns `true` if valid, `false` otherwise. |
|
|
152
|
+
| `ParseENV` | `ParseENV(): void` | Parse environment variables matching the configured prefix and set them as overrides. Prefixed variables are automatically discovered and parsed according to the schema. |
|
|
153
|
+
|
|
154
|
+
### ConfigManager (Advanced)
|
|
155
|
+
|
|
156
|
+
For advanced scenarios requiring direct schema control or custom configuration management, use `ConfigManager` directly:
|
|
157
|
+
|
|
158
|
+
| Method | Signature | Description |
|
|
159
|
+
|--------|-----------|-------------|
|
|
160
|
+
| `Register` | `Register(key: string, schema: ZodType, defaultValue: unknown): void` | Register a configuration key with a Zod schema and default value. Validates the default value against the schema. |
|
|
161
|
+
| `Set` | `Set<T>(key: string, value: T, target?: 'DEFAULT' \| 'OVERRIDE'): void` | Set a configuration value and validate against its schema. Default target is 'OVERRIDE'. |
|
|
162
|
+
| `Get` | `Get(key: string, source?: 'DEFAULT' \| 'OVERRIDE'): TConfigValueTypes` | Retrieve a configuration value by key, validated against its schema. Returns resolved value merging defaults and overrides. |
|
|
163
|
+
| `GetSchema` | `GetSchema(key: string): ZodTypeAny` | Retrieve the Zod schema for a configuration key for custom validation. |
|
|
164
|
+
| `Reset` | `Reset(): void` | Clear all registered schemas and values (for testing). Internal API. |
|
|
165
|
+
|
|
166
|
+
### Error Types
|
|
167
|
+
|
|
168
|
+
| Error | Description |
|
|
169
|
+
|-------|-------------|
|
|
170
|
+
| `ConfigurationAlreadyRegisteredError` | Thrown when attempting to register a key that already exists with a different schema. |
|
|
171
|
+
| `ConfigurationNotRegisteredError` | Thrown when accessing or setting a key that was not registered with a schema. |
|
|
172
|
+
| `ConfigurationError` | Thrown when configuration validation fails during registration, set, or get operations. Includes cause chain from Zod validation errors. |
|
|
173
|
+
| `ConfigurationNotSetError` | Thrown when retrieving a configuration value that was never set. |
|
|
174
|
+
|
|
175
|
+
### Type Exports
|
|
176
|
+
|
|
177
|
+
| Type | Description |
|
|
178
|
+
|------|-------------|
|
|
179
|
+
| `TConfigValueTypes` | Union type of all supported configuration value types: `string`, `number`, `boolean`, `Date`, `string[]`, `number[]`, `boolean[]`, `undefined`, or `null`. |
|
|
180
|
+
| `TConfig` | Internal map type: `Map<string, TConfigValueTypes>`. |
|
|
181
|
+
| `TConfigSource` | Literal union type: `'DEFAULT'` or `'OVERRIDE'`. Controls which source layer a value is stored in or retrieved from. |
|
|
182
|
+
|
|
183
|
+
> **⚠️ Security Warning**
|
|
184
|
+
>
|
|
185
|
+
> Do not store sensitive values (API keys, database passwords, tokens, PII) directly as string literals in your code. Always load sensitive configuration from environment variables or secure vaults at startup.
|
|
186
|
+
>
|
|
187
|
+
> When storing environment variable overrides, ensure the process environment itself is protected from inspection (e.g., via debugger or memory dumps).
|
|
188
|
+
>
|
|
189
|
+
> Example:
|
|
190
|
+
> ```typescript
|
|
191
|
+
> // ✓ Good: Load from environment at startup
|
|
192
|
+
> ConfigManager.Set('DATABASE_PASSWORD', process.env.DB_PASSWORD);
|
|
193
|
+
>
|
|
194
|
+
> // ✗ Bad: Hardcoded secrets
|
|
195
|
+
> ConfigManager.Register('DATABASE_PASSWORD', z.string(), 'hardcoded-password');
|
|
196
|
+
> ```
|
|
197
|
+
|
|
198
|
+
## License
|
|
199
|
+
|
|
200
|
+
MIT — See [LICENSE](../../LICENSE) for details.
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Custom error classes for configuration management.
|
|
3
|
+
*
|
|
4
|
+
* @throws {ConfigurationAlreadyRegisteredError} When a configuration key is registered twice
|
|
5
|
+
* @throws {ConfigurationNotRegisteredError} When accessing an unregistered configuration key
|
|
6
|
+
* @throws {ConfigurationError} When configuration validation fails
|
|
7
|
+
* @throws {ConfigurationNotSetError} When a required configuration value is not set
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* Abstract base class for configuration errors.
|
|
11
|
+
* Automatically sets the error name to the class constructor name.
|
|
12
|
+
*/
|
|
13
|
+
declare abstract class ConfigurationBaseError extends Error {
|
|
14
|
+
abstract readonly Code: string;
|
|
15
|
+
constructor(message: string);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Error thrown when attempting to register a configuration key that already exists.
|
|
19
|
+
*
|
|
20
|
+
* @param key - The configuration key that was already registered
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* throw new ConfigurationAlreadyRegisteredError('DATABASE_URL');
|
|
24
|
+
*/
|
|
25
|
+
export declare class ConfigurationAlreadyRegisteredError extends ConfigurationBaseError {
|
|
26
|
+
readonly Code = "CONFIGURATION_ALREADY_REGISTERED";
|
|
27
|
+
constructor(key: string);
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Error thrown when attempting to access a configuration key that was not registered.
|
|
31
|
+
*
|
|
32
|
+
* @param key - The configuration key that is not registered
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* throw new ConfigurationNotRegisteredError('UNKNOWN_KEY');
|
|
36
|
+
*/
|
|
37
|
+
export declare class ConfigurationNotRegisteredError extends ConfigurationBaseError {
|
|
38
|
+
readonly Code = "CONFIGURATION_NOT_REGISTERED";
|
|
39
|
+
constructor(key: string);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Error thrown when configuration validation fails.
|
|
43
|
+
*
|
|
44
|
+
* @param key - The configuration key that failed validation
|
|
45
|
+
* @param message - Detailed error message about the validation failure
|
|
46
|
+
* @param options - Optional options object with cause
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* throw new ConfigurationError('PORT', 'Must be a positive number');
|
|
50
|
+
*/
|
|
51
|
+
export declare class ConfigurationError extends ConfigurationBaseError {
|
|
52
|
+
readonly Code = "CONFIGURATION_ERROR";
|
|
53
|
+
constructor(key: string, message: string, options?: {
|
|
54
|
+
cause?: Error;
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Error thrown when a required configuration value is not set.
|
|
59
|
+
*
|
|
60
|
+
* @param key - The configuration key that is not set
|
|
61
|
+
*
|
|
62
|
+
* @example
|
|
63
|
+
* throw new ConfigurationNotSetError('DATABASE_URL');
|
|
64
|
+
*/
|
|
65
|
+
export declare class ConfigurationNotSetError extends ConfigurationBaseError {
|
|
66
|
+
readonly Code = "CONFIGURATION_NOT_SET";
|
|
67
|
+
constructor(key: string);
|
|
68
|
+
}
|
|
69
|
+
export {};
|
|
70
|
+
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH;;;GAGG;AACH,uBAAe,sBAAuB,SAAQ,KAAK;IAClD,kBAAyB,IAAI,EAAE,MAAM,CAAC;gBAE1B,OAAO,EAAE,MAAM;CAI3B;AAED;;;;;;;GAOG;AACH,qBAAa,mCAAoC,SAAQ,sBAAsB;IAC9E,SAAgB,IAAI,sCAAsC;gBAE9C,GAAG,EAAE,MAAM;CAGvB;AAED;;;;;;;GAOG;AACH,qBAAa,+BAAgC,SAAQ,sBAAsB;IAC1E,SAAgB,IAAI,kCAAkC;gBAE1C,GAAG,EAAE,MAAM;CAGvB;AAED;;;;;;;;;GASG;AACH,qBAAa,kBAAmB,SAAQ,sBAAsB;IAC7D,SAAgB,IAAI,yBAAyB;gBAEjC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,KAAK,CAAA;KAAE;CAMrE;AAED;;;;;;;GAOG;AACH,qBAAa,wBAAyB,SAAQ,sBAAsB;IACnE,SAAgB,IAAI,2BAA2B;gBAEnC,GAAG,EAAE,MAAM;CAGvB"}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Custom error classes for configuration management.
|
|
3
|
+
*
|
|
4
|
+
* @throws {ConfigurationAlreadyRegisteredError} When a configuration key is registered twice
|
|
5
|
+
* @throws {ConfigurationNotRegisteredError} When accessing an unregistered configuration key
|
|
6
|
+
* @throws {ConfigurationError} When configuration validation fails
|
|
7
|
+
* @throws {ConfigurationNotSetError} When a required configuration value is not set
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* Abstract base class for configuration errors.
|
|
11
|
+
* Automatically sets the error name to the class constructor name.
|
|
12
|
+
*/
|
|
13
|
+
class ConfigurationBaseError extends Error {
|
|
14
|
+
constructor(message) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = this.constructor.name;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Error thrown when attempting to register a configuration key that already exists.
|
|
21
|
+
*
|
|
22
|
+
* @param key - The configuration key that was already registered
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* throw new ConfigurationAlreadyRegisteredError('DATABASE_URL');
|
|
26
|
+
*/
|
|
27
|
+
export class ConfigurationAlreadyRegisteredError extends ConfigurationBaseError {
|
|
28
|
+
Code = 'CONFIGURATION_ALREADY_REGISTERED';
|
|
29
|
+
constructor(key) {
|
|
30
|
+
super(`Configuration key "${key}" is already registered with a different schema.`);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Error thrown when attempting to access a configuration key that was not registered.
|
|
35
|
+
*
|
|
36
|
+
* @param key - The configuration key that is not registered
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* throw new ConfigurationNotRegisteredError('UNKNOWN_KEY');
|
|
40
|
+
*/
|
|
41
|
+
export class ConfigurationNotRegisteredError extends ConfigurationBaseError {
|
|
42
|
+
Code = 'CONFIGURATION_NOT_REGISTERED';
|
|
43
|
+
constructor(key) {
|
|
44
|
+
super(`Configuration key "${key}" is not registered.`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Error thrown when configuration validation fails.
|
|
49
|
+
*
|
|
50
|
+
* @param key - The configuration key that failed validation
|
|
51
|
+
* @param message - Detailed error message about the validation failure
|
|
52
|
+
* @param options - Optional options object with cause
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
* throw new ConfigurationError('PORT', 'Must be a positive number');
|
|
56
|
+
*/
|
|
57
|
+
export class ConfigurationError extends ConfigurationBaseError {
|
|
58
|
+
Code = 'CONFIGURATION_ERROR';
|
|
59
|
+
constructor(key, message, options) {
|
|
60
|
+
super(`Validation failed for configuration "${key}": ${message}`);
|
|
61
|
+
if (options?.cause) {
|
|
62
|
+
this.cause = options.cause;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Error thrown when a required configuration value is not set.
|
|
68
|
+
*
|
|
69
|
+
* @param key - The configuration key that is not set
|
|
70
|
+
*
|
|
71
|
+
* @example
|
|
72
|
+
* throw new ConfigurationNotSetError('DATABASE_URL');
|
|
73
|
+
*/
|
|
74
|
+
export class ConfigurationNotSetError extends ConfigurationBaseError {
|
|
75
|
+
Code = 'CONFIGURATION_NOT_SET';
|
|
76
|
+
constructor(key) {
|
|
77
|
+
super(`Configuration key "${key}" is not set.`);
|
|
78
|
+
}
|
|
79
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,cAAc,CAAC;AAC7B,cAAc,qBAAqB,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { z } from 'zod/v4';
|
|
2
|
+
export declare const CONFIG_VALUES_TYPES_SCHEMA: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodDate, z.ZodArray<z.ZodString>, z.ZodArray<z.ZodNumber>, z.ZodArray<z.ZodBoolean>, z.ZodUndefined]>>>;
|
|
3
|
+
export declare function AssertConfigValueType(value: unknown): asserts value is TConfigValueTypes;
|
|
4
|
+
export type TConfigValueTypes = z.infer<typeof CONFIG_VALUES_TYPES_SCHEMA>;
|
|
5
|
+
export type TConfig = Map<string, TConfigValueTypes>;
|
|
6
|
+
export type TConfigSource = 'DEFAULT' | 'OVERRIDE';
|
|
7
|
+
/**
|
|
8
|
+
* Runtime configuration manager with Zod schema validation.
|
|
9
|
+
* Provides a singleton instance to register and retrieve typed configuration values.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ConfigManager.Register('DATABASE_URL', z.string().url(), 'postgresql://localhost/mydb');
|
|
13
|
+
* ConfigManager.Set('DEFAULT', 'DATABASE_URL', 'postgresql://localhost/mydb');
|
|
14
|
+
* const url = ConfigManager.Get('DATABASE_URL');
|
|
15
|
+
*/
|
|
16
|
+
export declare class ConfigManager {
|
|
17
|
+
private static readonly _Schemas;
|
|
18
|
+
private static readonly _DataDefaults;
|
|
19
|
+
private static readonly _DataOverrides;
|
|
20
|
+
private static get _Data();
|
|
21
|
+
/**
|
|
22
|
+
* Reset the singleton instance (for testing).
|
|
23
|
+
* @internal
|
|
24
|
+
*/
|
|
25
|
+
static Reset(): void;
|
|
26
|
+
private constructor();
|
|
27
|
+
/**
|
|
28
|
+
* Register a configuration schema.
|
|
29
|
+
* @param key - Unique configuration key
|
|
30
|
+
* @param schema - Zod schema for runtime validation
|
|
31
|
+
* @param defaultValue - Initial value for the configuration key, must satisfy the schema
|
|
32
|
+
* @throws {ConfigurationAlreadyRegisteredError} If key is already registered
|
|
33
|
+
* @example
|
|
34
|
+
* manager.register('PORT', z.coerce.number().positive());
|
|
35
|
+
* manager.register('JWT_SECRET', z.string().min(32));
|
|
36
|
+
*/
|
|
37
|
+
static Register(key: string, schema: z.ZodType<TConfigValueTypes>, defaultValue: unknown): void;
|
|
38
|
+
/**
|
|
39
|
+
* Set a configuration value and validate against its schema.
|
|
40
|
+
* @param key - Configuration key
|
|
41
|
+
* @param value - Value to set and validate
|
|
42
|
+
* @throws {ConfigurationNotRegisteredError} If schema is not registered for key
|
|
43
|
+
* @throws {ConfigurationError} If validation fails
|
|
44
|
+
* @example
|
|
45
|
+
* manager.set('PORT', 3000);
|
|
46
|
+
* manager.set('JWT_SECRET', process.env.SECRET);
|
|
47
|
+
*/
|
|
48
|
+
static Set<T extends TConfigValueTypes>(key: string, value: T, target?: TConfigSource): void;
|
|
49
|
+
/**
|
|
50
|
+
* Retrieve a configuration value by key.
|
|
51
|
+
* Returns the value parsed by its registered schema.
|
|
52
|
+
* @param key - Configuration key
|
|
53
|
+
* @returns The typed configuration value
|
|
54
|
+
* @throws {ConfigurationNotSetError} If value was not set
|
|
55
|
+
* @throws {ConfigurationNotRegisteredError} If schema is not registered
|
|
56
|
+
* @throws {ConfigurationError} If validation fails on retrieval
|
|
57
|
+
* @example
|
|
58
|
+
* const port = manager.get('PORT'); // Returns number, guaranteed by schema
|
|
59
|
+
* const secret = manager.get('JWT_SECRET'); // Returns string
|
|
60
|
+
*/
|
|
61
|
+
static Get(key: string, source?: TConfigSource): TConfigValueTypes;
|
|
62
|
+
/**
|
|
63
|
+
* Retrieve the schema for a configuration key.
|
|
64
|
+
* @param key - Configuration key
|
|
65
|
+
* @returns The Zod schema for this configuration
|
|
66
|
+
* @throws {ConfigurationNotRegisteredError} If schema is not registered for key
|
|
67
|
+
* @example
|
|
68
|
+
* const schema = manager.getSchema('PORT');
|
|
69
|
+
* const parsed = schema.safeParse(value);
|
|
70
|
+
*/
|
|
71
|
+
static GetSchema(key: string): z.ZodTypeAny;
|
|
72
|
+
}
|
|
73
|
+
//# sourceMappingURL=manager.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"manager.d.ts","sourceRoot":"","sources":["../src/manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,QAAQ,CAAC;AAG3B,eAAO,MAAM,0BAA0B,oMASf,CAAC;AACzB,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,KAAK,IAAI,iBAAiB,CAExF;AAED,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,0BAA0B,CAAC,CAAC;AAC3E,MAAM,MAAM,OAAO,GAAG,GAAG,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC;AACrD,MAAM,MAAM,aAAa,GAAG,SAAS,GAAG,UAAU,CAAC;AAEnD;;;;;;;;GAQG;AACH,qBAAa,aAAa;IACzB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAwC;IAGxE,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,aAAa,CAAsB;IAG3D,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,cAAc,CAAsB;IAG5D,OAAO,CAAC,MAAM,KAAK,KAAK,GAMvB;IAED;;;OAGG;WACW,KAAK,IAAI,IAAI;IAM3B,OAAO;IAEP;;;;;;;;;OASG;WACW,QAAQ,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC,OAAO,CAAC,iBAAiB,CAAC,EAAE,YAAY,EAAE,OAAO,GAAG,IAAI;IAUtG;;;;;;;;;OASG;WACW,GAAG,CAAC,CAAC,SAAS,iBAAiB,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,GAAE,aAA0B,GAAG,IAAI;IAkB/G;;;;;;;;;;;OAWG;WACW,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,aAAa,GAAG,iBAAiB;IAgBzE;;;;;;;;OAQG;WACW,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,CAAC,CAAC,UAAU;CAKlD"}
|
package/dist/manager.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { z } from 'zod/v4';
|
|
2
|
+
import { ConfigurationAlreadyRegisteredError, ConfigurationNotRegisteredError, ConfigurationError, ConfigurationNotSetError } from './errors.js';
|
|
3
|
+
export const CONFIG_VALUES_TYPES_SCHEMA = z.union([
|
|
4
|
+
z.string(),
|
|
5
|
+
z.number(),
|
|
6
|
+
z.boolean(),
|
|
7
|
+
z.date(),
|
|
8
|
+
z.array(z.string()),
|
|
9
|
+
z.array(z.number()),
|
|
10
|
+
z.array(z.boolean()),
|
|
11
|
+
z.undefined(),
|
|
12
|
+
]).nullable().optional();
|
|
13
|
+
export function AssertConfigValueType(value) {
|
|
14
|
+
CONFIG_VALUES_TYPES_SCHEMA.parse(value);
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Runtime configuration manager with Zod schema validation.
|
|
18
|
+
* Provides a singleton instance to register and retrieve typed configuration values.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ConfigManager.Register('DATABASE_URL', z.string().url(), 'postgresql://localhost/mydb');
|
|
22
|
+
* ConfigManager.Set('DEFAULT', 'DATABASE_URL', 'postgresql://localhost/mydb');
|
|
23
|
+
* const url = ConfigManager.Get('DATABASE_URL');
|
|
24
|
+
*/
|
|
25
|
+
export class ConfigManager {
|
|
26
|
+
static _Schemas = new Map();
|
|
27
|
+
// Populated at Registration
|
|
28
|
+
static _DataDefaults = new Map();
|
|
29
|
+
// Overriden at Runtime from various sources
|
|
30
|
+
static _DataOverrides = new Map();
|
|
31
|
+
// Resolved Data
|
|
32
|
+
static get _Data() {
|
|
33
|
+
const resolved = new Map(this._DataDefaults);
|
|
34
|
+
for (const [key, value] of this._DataOverrides) {
|
|
35
|
+
resolved.set(key, value);
|
|
36
|
+
}
|
|
37
|
+
return resolved;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Reset the singleton instance (for testing).
|
|
41
|
+
* @internal
|
|
42
|
+
*/
|
|
43
|
+
static Reset() {
|
|
44
|
+
this._Schemas.clear();
|
|
45
|
+
this._DataDefaults.clear();
|
|
46
|
+
this._DataOverrides.clear();
|
|
47
|
+
}
|
|
48
|
+
constructor() { }
|
|
49
|
+
/**
|
|
50
|
+
* Register a configuration schema.
|
|
51
|
+
* @param key - Unique configuration key
|
|
52
|
+
* @param schema - Zod schema for runtime validation
|
|
53
|
+
* @param defaultValue - Initial value for the configuration key, must satisfy the schema
|
|
54
|
+
* @throws {ConfigurationAlreadyRegisteredError} If key is already registered
|
|
55
|
+
* @example
|
|
56
|
+
* manager.register('PORT', z.coerce.number().positive());
|
|
57
|
+
* manager.register('JWT_SECRET', z.string().min(32));
|
|
58
|
+
*/
|
|
59
|
+
static Register(key, schema, defaultValue) {
|
|
60
|
+
// Ensure key is unique, but it's fine when the schemas match.
|
|
61
|
+
if (this._Schemas.has(key) && this._Schemas.get(key) !== schema)
|
|
62
|
+
throw new ConfigurationAlreadyRegisteredError(key);
|
|
63
|
+
const result = schema.safeParse(defaultValue);
|
|
64
|
+
if (!result.success)
|
|
65
|
+
throw new ConfigurationError('Registration', `Default value for configuration "${key}" does not match the provided schema.`, { cause: result.error });
|
|
66
|
+
const parsed = result.data;
|
|
67
|
+
this._Schemas.set(key, schema);
|
|
68
|
+
this.Set(key, parsed, 'DEFAULT');
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Set a configuration value and validate against its schema.
|
|
72
|
+
* @param key - Configuration key
|
|
73
|
+
* @param value - Value to set and validate
|
|
74
|
+
* @throws {ConfigurationNotRegisteredError} If schema is not registered for key
|
|
75
|
+
* @throws {ConfigurationError} If validation fails
|
|
76
|
+
* @example
|
|
77
|
+
* manager.set('PORT', 3000);
|
|
78
|
+
* manager.set('JWT_SECRET', process.env.SECRET);
|
|
79
|
+
*/
|
|
80
|
+
static Set(key, value, target = 'OVERRIDE') {
|
|
81
|
+
const schema = this._Schemas.get(key);
|
|
82
|
+
if (!schema)
|
|
83
|
+
throw new ConfigurationNotRegisteredError(key);
|
|
84
|
+
try {
|
|
85
|
+
const parsed = schema.parse(value);
|
|
86
|
+
AssertConfigValueType(parsed);
|
|
87
|
+
if (target === 'DEFAULT') {
|
|
88
|
+
this._DataDefaults.set(key, parsed);
|
|
89
|
+
}
|
|
90
|
+
else {
|
|
91
|
+
this._DataOverrides.set(key, parsed);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
catch (cause) {
|
|
95
|
+
throw new ConfigurationError(key, cause instanceof Error ? cause.message : String(cause), { cause: cause instanceof Error ? cause : undefined });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Retrieve a configuration value by key.
|
|
100
|
+
* Returns the value parsed by its registered schema.
|
|
101
|
+
* @param key - Configuration key
|
|
102
|
+
* @returns The typed configuration value
|
|
103
|
+
* @throws {ConfigurationNotSetError} If value was not set
|
|
104
|
+
* @throws {ConfigurationNotRegisteredError} If schema is not registered
|
|
105
|
+
* @throws {ConfigurationError} If validation fails on retrieval
|
|
106
|
+
* @example
|
|
107
|
+
* const port = manager.get('PORT'); // Returns number, guaranteed by schema
|
|
108
|
+
* const secret = manager.get('JWT_SECRET'); // Returns string
|
|
109
|
+
*/
|
|
110
|
+
static Get(key, source) {
|
|
111
|
+
const value = source === 'DEFAULT' ? this._DataDefaults.get(key) : source === 'OVERRIDE' ? this._DataOverrides.get(key) : this._Data.get(key);
|
|
112
|
+
if (value === undefined)
|
|
113
|
+
throw new ConfigurationNotSetError(key);
|
|
114
|
+
const schema = this.GetSchema(key);
|
|
115
|
+
try {
|
|
116
|
+
// TODO: This will re-parse the value on every retrieval, which may have performance implications. Consider caching parsed values if this becomes an issue.
|
|
117
|
+
// TODO: Also consider how to handle complex types that may not be easily represented as strings in ENV or CLI (e.g. arrays, objects). We may need to support custom parsing logic or conventions for these cases.
|
|
118
|
+
const rvalue = schema.parse(value);
|
|
119
|
+
AssertConfigValueType(rvalue);
|
|
120
|
+
return rvalue;
|
|
121
|
+
}
|
|
122
|
+
catch (cause) {
|
|
123
|
+
throw new ConfigurationError(key, cause instanceof Error ? cause.message : String(cause), { cause: cause instanceof Error ? cause : undefined });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Retrieve the schema for a configuration key.
|
|
128
|
+
* @param key - Configuration key
|
|
129
|
+
* @returns The Zod schema for this configuration
|
|
130
|
+
* @throws {ConfigurationNotRegisteredError} If schema is not registered for key
|
|
131
|
+
* @example
|
|
132
|
+
* const schema = manager.getSchema('PORT');
|
|
133
|
+
* const parsed = schema.safeParse(value);
|
|
134
|
+
*/
|
|
135
|
+
static GetSchema(key) {
|
|
136
|
+
const schema = this._Schemas.get(key);
|
|
137
|
+
if (!schema)
|
|
138
|
+
throw new ConfigurationNotRegisteredError(key);
|
|
139
|
+
return schema;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { z } from 'zod';
|
|
2
|
+
import { type TConfigSource } from './manager.js';
|
|
3
|
+
/**
|
|
4
|
+
* Configuration schema object with static-like methods for managing config values.
|
|
5
|
+
* Provides Register, Get, Set, Validate, and ParseENV methods for a specific config namespace.
|
|
6
|
+
*
|
|
7
|
+
* @template TConfig - The inferred type of the Zod schema
|
|
8
|
+
* @template TKeys - Union of config keys from the schema shape
|
|
9
|
+
*/
|
|
10
|
+
export interface IConfigSchemaObject<TConfig extends Record<string, unknown>, TKeys extends keyof TConfig = keyof TConfig> {
|
|
11
|
+
/**
|
|
12
|
+
* Register all schema fields with ConfigManager.
|
|
13
|
+
* Extracts default values and registers each field as a schema.
|
|
14
|
+
*/
|
|
15
|
+
Register(): void;
|
|
16
|
+
/**
|
|
17
|
+
* Get a typed config value by key.
|
|
18
|
+
*
|
|
19
|
+
* @param key - Configuration key to retrieve
|
|
20
|
+
* @returns The typed config value
|
|
21
|
+
* @template K - Specific config key type
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* const host = MongoDBConfig.Get('HOST');
|
|
25
|
+
* // host is typed as string
|
|
26
|
+
*/
|
|
27
|
+
Get<K extends TKeys>(key: K): TConfig[K];
|
|
28
|
+
/**
|
|
29
|
+
* Set a config value with optional source.
|
|
30
|
+
*
|
|
31
|
+
* @param key - Configuration key to set
|
|
32
|
+
* @param value - Typed value matching the key
|
|
33
|
+
* @param source - Override source ('DEFAULT' or 'OVERRIDE'), defaults to 'OVERRIDE'
|
|
34
|
+
* @template K - Specific config key type
|
|
35
|
+
* @throws Error if the value fails validation
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* MongoDBConfig.Set('HOST', 'localhost:27017', 'OVERRIDE');
|
|
39
|
+
*/
|
|
40
|
+
Set<K extends TKeys>(key: K, value: TConfig[K], source?: TConfigSource): void;
|
|
41
|
+
/**
|
|
42
|
+
* Validate a value against its schema without setting it.
|
|
43
|
+
*
|
|
44
|
+
* @param key - Configuration key whose schema is used for validation
|
|
45
|
+
* @param value - Unknown value to validate
|
|
46
|
+
* @returns true if the value is valid for this key, false otherwise
|
|
47
|
+
* @template K - Specific config key type
|
|
48
|
+
*
|
|
49
|
+
* @example
|
|
50
|
+
* if (MongoDBConfig.Validate('PORT', '27017')) {
|
|
51
|
+
* // value is valid for PORT
|
|
52
|
+
* }
|
|
53
|
+
*/
|
|
54
|
+
Validate<K extends TKeys>(key: K, value: unknown): boolean;
|
|
55
|
+
/**
|
|
56
|
+
* Parse environment variables matching the prefix and set them as overrides.
|
|
57
|
+
* Logs warnings for invalid values but continues processing remaining vars.
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* MongoDBConfig.ParseENV();
|
|
61
|
+
* // Reads MONGODB_HOST, MONGODB_PORT, etc. from process.env
|
|
62
|
+
*/
|
|
63
|
+
ParseENV(): void;
|
|
64
|
+
}
|
|
65
|
+
export declare function CreateConfigSchema<TSchema extends z.ZodRawShape>(schema: z.ZodObject<TSchema>, prefix: string): IConfigSchemaObject<z.infer<typeof schema>>;
|
|
66
|
+
//# sourceMappingURL=schema.factory.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema.factory.d.ts","sourceRoot":"","sources":["../src/schema.factory.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAC7B,OAAO,EAAiB,KAAK,aAAa,EAAE,MAAM,cAAc,CAAC;AA0BjE;;;;;;GAMG;AACH,MAAM,WAAW,mBAAmB,CACnC,OAAO,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACvC,KAAK,SAAS,MAAM,OAAO,GAAG,MAAM,OAAO;IAE3C;;;OAGG;IACH,QAAQ,IAAI,IAAI,CAAC;IAEjB;;;;;;;;;;OAUG;IACH,GAAG,CAAC,CAAC,SAAS,KAAK,EAAE,GAAG,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IAEzC;;;;;;;;;;;OAWG;IACH,GAAG,CAAC,CAAC,SAAS,KAAK,EAAE,GAAG,EAAE,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,EAAE,aAAa,GAAG,IAAI,CAAC;IAE9E;;;;;;;;;;;;OAYG;IACH,QAAQ,CAAC,CAAC,SAAS,KAAK,EAAE,GAAG,EAAE,CAAC,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC;IAE3D;;;;;;;OAOG;IACH,QAAQ,IAAI,IAAI,CAAC;CACjB;AA+CD,wBAAgB,kBAAkB,CAAC,OAAO,SAAS,CAAC,CAAC,WAAW,EAAE,MAAM,EAAE,CAAC,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,MAAM,GAAG,mBAAmB,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,MAAM,CAAC,CAAC,CAkE3J"}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { ConfigManager } from './manager.js';
|
|
2
|
+
/**
|
|
3
|
+
* Intelligently parse an environment variable string to a JSON-compatible value.
|
|
4
|
+
* Attempts to parse as JSON first (handles objects, arrays, booleans, null, numbers).
|
|
5
|
+
* Falls back to treating as a plain string if JSON parsing fails.
|
|
6
|
+
*
|
|
7
|
+
* @param envVarValue - Environment variable value (always a string from process.env)
|
|
8
|
+
* @returns Parsed value (JSON-parsed if applicable, otherwise the original string)
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* parseEnvVarValue('true') → true (boolean)
|
|
12
|
+
* parseEnvVarValue('123') → 123 (number)
|
|
13
|
+
* parseEnvVarValue('["a","b"]') → ['a', 'b'] (array)
|
|
14
|
+
* parseEnvVarValue('hello') → 'hello' (string, unchanged)
|
|
15
|
+
*/
|
|
16
|
+
function ParseEnvVarValue(envVarValue) {
|
|
17
|
+
try {
|
|
18
|
+
return JSON.parse(envVarValue);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
// If JSON parsing fails, treat as a plain string
|
|
22
|
+
return envVarValue;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Creates a configuration schema object from a Zod schema and prefix.
|
|
27
|
+
*
|
|
28
|
+
* Generic factory that eliminates duplication between concrete config classes.
|
|
29
|
+
* Returns an object with Register, Get, Set, Validate, and ParseENV methods
|
|
30
|
+
* that manage config values for a specific namespace.
|
|
31
|
+
*
|
|
32
|
+
* @param schema - Zod schema defining the config shape and validation rules
|
|
33
|
+
* @param prefix - Prefix for environment variable names (e.g., 'MONGODB_')
|
|
34
|
+
* @returns ConfigSchemaObject with static-like methods for the config namespace
|
|
35
|
+
* @template TSchema - The Zod schema shape
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```typescript
|
|
39
|
+
* const MONGODB_SCHEMA = z.object({
|
|
40
|
+
* HOST: z.string().default('localhost'),
|
|
41
|
+
* PORT: z.number().default(27017),
|
|
42
|
+
* });
|
|
43
|
+
*
|
|
44
|
+
* export const MongoDBConfig = createConfigSchema(MONGODB_SCHEMA, 'MONGODB_');
|
|
45
|
+
* // Usage:
|
|
46
|
+
* // MongoDBConfig.Register();
|
|
47
|
+
* // const host = MongoDBConfig.Get('HOST');
|
|
48
|
+
* // MongoDBConfig.Set('PORT', 27018);
|
|
49
|
+
* // MongoDBConfig.ParseENV();
|
|
50
|
+
* ```
|
|
51
|
+
*/
|
|
52
|
+
/**
|
|
53
|
+
* Safely extracts the default value from a Zod schema, handling both
|
|
54
|
+
* lazy defaults (functions) and eager defaults (plain values).
|
|
55
|
+
*
|
|
56
|
+
* @param schema - The field schema to extract the default from
|
|
57
|
+
* @returns The evaluated default value, or undefined if not present
|
|
58
|
+
*/
|
|
59
|
+
function extractDefaultValue(schema) {
|
|
60
|
+
const _def = schema._def;
|
|
61
|
+
if (!_def || typeof _def !== 'object')
|
|
62
|
+
return undefined;
|
|
63
|
+
const dv = _def.defaultValue;
|
|
64
|
+
if (dv === undefined)
|
|
65
|
+
return undefined;
|
|
66
|
+
// Handle both lazy (function) and eager (plain value) defaults
|
|
67
|
+
return typeof dv === 'function' ? dv() : dv;
|
|
68
|
+
}
|
|
69
|
+
export function CreateConfigSchema(schema, prefix) {
|
|
70
|
+
// Build a map of key -> prefixed name
|
|
71
|
+
const prefixedNames = {};
|
|
72
|
+
for (const key in schema.shape) {
|
|
73
|
+
if (Object.prototype.hasOwnProperty.call(schema.shape, key)) {
|
|
74
|
+
prefixedNames[key] = `${prefix}${key}`;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return {
|
|
78
|
+
Register() {
|
|
79
|
+
for (const key in schema.shape) {
|
|
80
|
+
if (Object.prototype.hasOwnProperty.call(schema.shape, key)) {
|
|
81
|
+
const fieldSchema = schema.shape[key];
|
|
82
|
+
// Safely extract default value from Zod's internal structure
|
|
83
|
+
const defaultValue = extractDefaultValue(fieldSchema);
|
|
84
|
+
// @ts-expect-error Zod schema shape types don't align with ConfigManager.Register signature, but this is safe at runtime
|
|
85
|
+
ConfigManager.Register(prefixedNames[key], fieldSchema, defaultValue);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
Get(key) {
|
|
90
|
+
return ConfigManager.Get(prefixedNames[key]);
|
|
91
|
+
},
|
|
92
|
+
Set(key, value, source = 'OVERRIDE') {
|
|
93
|
+
// @ts-expect-error TConfig may contain values that don't match TConfigValueTypes, but we trust the schema validation
|
|
94
|
+
ConfigManager.Set(prefixedNames[key], value, source);
|
|
95
|
+
},
|
|
96
|
+
Validate(key, value) {
|
|
97
|
+
const fieldSchema = schema.shape[key];
|
|
98
|
+
try {
|
|
99
|
+
fieldSchema.parse(value);
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
},
|
|
106
|
+
ParseENV(throwOnError = false) {
|
|
107
|
+
for (const key in schema.shape) {
|
|
108
|
+
if (Object.prototype.hasOwnProperty.call(schema.shape, key)) {
|
|
109
|
+
const envVarName = prefixedNames[key];
|
|
110
|
+
const envVarValue = process.env[envVarName];
|
|
111
|
+
if (envVarValue !== undefined) {
|
|
112
|
+
try {
|
|
113
|
+
const fieldSchema = schema.shape[key];
|
|
114
|
+
// Pre-process env var string: try JSON parsing first, fall back to plain string
|
|
115
|
+
const preProcessedValue = ParseEnvVarValue(envVarValue);
|
|
116
|
+
const parsedValue = fieldSchema.parse(preProcessedValue);
|
|
117
|
+
this.Set(key, parsedValue, 'OVERRIDE');
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
if (throwOnError)
|
|
121
|
+
throw error;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@pawells/config",
|
|
3
|
+
"version": "2.1.6-rc1",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"author": {
|
|
6
|
+
"name": "Phillip Aaron Wells",
|
|
7
|
+
"email": "phillip.aaron.wells@gmail.com"
|
|
8
|
+
},
|
|
9
|
+
"homepage": "https://github.com/PhillipAWells/common",
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "https://github.com/PhillipAWells/common.git"
|
|
13
|
+
},
|
|
14
|
+
"funding": {
|
|
15
|
+
"type": "github",
|
|
16
|
+
"url": "https://github.com/sponsors/PhillipAWells"
|
|
17
|
+
},
|
|
18
|
+
"type": "module",
|
|
19
|
+
"main": "./dist/index.js",
|
|
20
|
+
"module": "./dist/index.js",
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"exports": {
|
|
23
|
+
"./package.json": "./package.json",
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"import": "./dist/index.js",
|
|
27
|
+
"default": "./dist/index.js"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"dist",
|
|
32
|
+
"!**/*.tsbuildinfo"
|
|
33
|
+
],
|
|
34
|
+
"dependencies": {
|
|
35
|
+
"tslib": "^2.3.0",
|
|
36
|
+
"zod": "^4.4.3"
|
|
37
|
+
}
|
|
38
|
+
}
|