@maroonedsoftware/appconfig 1.2.0 → 1.4.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.
- package/README.md +89 -0
- package/dist/helpers.d.ts +28 -0
- package/dist/helpers.d.ts.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +44 -14
- package/dist/index.js.map +1 -1
- package/dist/sources/app.config.source.dotenv.d.ts +37 -2
- package/dist/sources/app.config.source.dotenv.d.ts.map +1 -1
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -8,6 +8,7 @@ A flexible, type-safe configuration management library with support for multiple
|
|
|
8
8
|
- **Multiple sources** - Load configuration from JSON files, YAML files, `.env` files, and more
|
|
9
9
|
- **Value transformation** - Resolve environment variables and GCP secrets in configuration values
|
|
10
10
|
- **Deep merging** - Combine configurations from multiple sources with predictable override behavior
|
|
11
|
+
- **Flat key grouping** - Collapse `KEY__sub=val` dotenv entries into nested objects automatically
|
|
11
12
|
- **Extensible** - Create custom sources and providers for your specific needs
|
|
12
13
|
|
|
13
14
|
## Installation
|
|
@@ -220,8 +221,66 @@ const source = new AppConfigSourceDotenv();
|
|
|
220
221
|
|
|
221
222
|
// Load from custom path
|
|
222
223
|
const source = new AppConfigSourceDotenv('./config/.env.local');
|
|
224
|
+
|
|
225
|
+
// Group keys with __ separator into nested objects
|
|
226
|
+
const source = new AppConfigSourceDotenv('./.env', { groupSeparator: '__' });
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
##### `groupSeparator` option
|
|
230
|
+
|
|
231
|
+
When set, any key containing the separator is split into path segments and written into a nested object. Keys without the separator are passed through unchanged. Arbitrary nesting depth is supported.
|
|
232
|
+
|
|
233
|
+
**.env:**
|
|
234
|
+
|
|
235
|
+
```
|
|
236
|
+
MODERN_TREASURY_WEBHOOK__secret=blah
|
|
237
|
+
MODERN_TREASURY_WEBHOOK__header=X-Signature
|
|
238
|
+
MODERN_TREASURY_WEBHOOK__algorithm=sha256
|
|
239
|
+
MODERN_TREASURY_WEBHOOK__digest=hex
|
|
240
|
+
DATABASE_URL=postgres://localhost/db
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
**app.ts:**
|
|
244
|
+
|
|
245
|
+
```typescript
|
|
246
|
+
const source = new AppConfigSourceDotenv('./.env', { groupSeparator: '__' });
|
|
247
|
+
const config = await source.load();
|
|
248
|
+
// →
|
|
249
|
+
// {
|
|
250
|
+
// MODERN_TREASURY_WEBHOOK: {
|
|
251
|
+
// secret: 'blah',
|
|
252
|
+
// header: 'X-Signature',
|
|
253
|
+
// algorithm: 'sha256',
|
|
254
|
+
// digest: 'hex',
|
|
255
|
+
// },
|
|
256
|
+
// DATABASE_URL: 'postgres://localhost/db',
|
|
257
|
+
// }
|
|
223
258
|
```
|
|
224
259
|
|
|
260
|
+
The `groupSeparator` option also integrates naturally with the builder. Because grouping happens at the source level, all downstream providers (e.g. `AppConfigProviderDotenv`) see the already-nested object:
|
|
261
|
+
|
|
262
|
+
```typescript
|
|
263
|
+
const config = await new AppConfigBuilder()
|
|
264
|
+
.addSource(new AppConfigSourceJson('./config.json'))
|
|
265
|
+
.addSource(new AppConfigSourceDotenv('./.env', { groupSeparator: '__' }))
|
|
266
|
+
.addProvider(new AppConfigProviderDotenv())
|
|
267
|
+
.build<MyConfig>();
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
You can also call `nestKeys` directly if you need to transform a plain record outside of a source:
|
|
271
|
+
|
|
272
|
+
```typescript
|
|
273
|
+
import { nestKeys } from '@maroonedsoftware/appconfig';
|
|
274
|
+
|
|
275
|
+
const nested = nestKeys(process.env as Record<string, unknown>, '__');
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
##### AppConfigSourceDotenvOptions
|
|
279
|
+
|
|
280
|
+
| Option | Type | Description |
|
|
281
|
+
| ---------------- | -------- | ------------------------------------------------------------------------------------------------------- |
|
|
282
|
+
| `groupSeparator` | `string` | Optional. When set, keys containing this string are split into nested objects (e.g. `'__'`). |
|
|
283
|
+
|
|
225
284
|
### Providers
|
|
226
285
|
|
|
227
286
|
#### AppConfigProviderDotenv
|
|
@@ -262,6 +321,36 @@ The provider:
|
|
|
262
321
|
- Requires valid GCP credentials (uses Application Default Credentials)
|
|
263
322
|
- Is decorated with `@Injectable()` for dependency injection support
|
|
264
323
|
|
|
324
|
+
## Utilities
|
|
325
|
+
|
|
326
|
+
### nestKeys
|
|
327
|
+
|
|
328
|
+
Transforms a flat key/value record into a nested object by splitting keys on a separator. Exported as a standalone utility for use outside of sources.
|
|
329
|
+
|
|
330
|
+
```typescript
|
|
331
|
+
import { nestKeys } from '@maroonedsoftware/appconfig';
|
|
332
|
+
|
|
333
|
+
nestKeys(
|
|
334
|
+
{
|
|
335
|
+
WEBHOOK__secret: 'abc',
|
|
336
|
+
WEBHOOK__header: 'X-Sig',
|
|
337
|
+
WEBHOOK__signing__algorithm: 'sha256', // deep nesting
|
|
338
|
+
DATABASE_URL: 'postgres://localhost/db',
|
|
339
|
+
},
|
|
340
|
+
'__',
|
|
341
|
+
);
|
|
342
|
+
// →
|
|
343
|
+
// {
|
|
344
|
+
// WEBHOOK: { secret: 'abc', header: 'X-Sig', signing: { algorithm: 'sha256' } },
|
|
345
|
+
// DATABASE_URL: 'postgres://localhost/db',
|
|
346
|
+
// }
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
| Parameter | Type | Description |
|
|
350
|
+
| ----------- | -------------------------- | ----------------------------------------------- |
|
|
351
|
+
| `record` | `Record<string, unknown>` | The flat key/value record to transform |
|
|
352
|
+
| `separator` | `string` | The string used to delimit path segments |
|
|
353
|
+
|
|
265
354
|
## Custom Sources and Providers
|
|
266
355
|
|
|
267
356
|
### Creating a Custom Source
|
package/dist/helpers.d.ts
CHANGED
|
@@ -5,4 +5,32 @@
|
|
|
5
5
|
* @returns The parsed JSON value, or the original text if parsing fails.
|
|
6
6
|
*/
|
|
7
7
|
export declare function tryParseJson(text: string): unknown;
|
|
8
|
+
/**
|
|
9
|
+
* Transforms a flat key/value record into a nested object by splitting keys on a
|
|
10
|
+
* separator string.
|
|
11
|
+
*
|
|
12
|
+
* Each key is split into path segments. Intermediate objects are created as needed.
|
|
13
|
+
* If a path segment collides with an existing non-object value it is replaced by the
|
|
14
|
+
* new object. Keys that do not contain the separator are passed through unchanged.
|
|
15
|
+
*
|
|
16
|
+
* Supports arbitrary nesting depth — a key with N separators produces N+1 levels.
|
|
17
|
+
*
|
|
18
|
+
* @param record - The flat key/value record to transform.
|
|
19
|
+
* @param separator - The string used to delimit path segments (e.g. `'__'`).
|
|
20
|
+
* @returns A new nested object.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```typescript
|
|
24
|
+
* nestKeys(
|
|
25
|
+
* {
|
|
26
|
+
* WEBHOOK__secret: 'abc',
|
|
27
|
+
* WEBHOOK__header: 'X-Sig',
|
|
28
|
+
* DATABASE_URL: 'postgres://localhost/db',
|
|
29
|
+
* },
|
|
30
|
+
* '__',
|
|
31
|
+
* );
|
|
32
|
+
* // → { WEBHOOK: { secret: 'abc', header: 'X-Sig' }, DATABASE_URL: 'postgres://localhost/db' }
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
35
|
+
export declare function nestKeys(record: Record<string, unknown>, separator: string): Record<string, unknown>;
|
|
8
36
|
//# sourceMappingURL=helpers.d.ts.map
|
package/dist/helpers.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAMlD"}
|
|
1
|
+
{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAMlD;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAsBpG"}
|
package/dist/index.d.ts
CHANGED
|
@@ -3,8 +3,10 @@ export { AppConfigBuilder } from './app.config.builder.js';
|
|
|
3
3
|
export type { AppConfigProvider } from './app.config.provider.js';
|
|
4
4
|
export type { AppConfigSource } from './app.config.source.js';
|
|
5
5
|
export { AppConfigSourceDotenv } from './sources/app.config.source.dotenv.js';
|
|
6
|
+
export type { AppConfigSourceDotenvOptions } from './sources/app.config.source.dotenv.js';
|
|
6
7
|
export { AppConfigSourceJson } from './sources/app.config.source.json.js';
|
|
7
8
|
export { AppConfigSourceYaml } from './sources/app.config.source.yaml.js';
|
|
8
9
|
export { AppConfigProviderDotenv } from './providers/app.config.provider.dotenv.js';
|
|
9
10
|
export { AppConfigProviderGcpSecrets } from './providers/app.config.provider.gcp.secrets.js';
|
|
11
|
+
export { nestKeys } from './helpers.js';
|
|
10
12
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,YAAY,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAClE,YAAY,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAC9E,OAAO,EAAE,mBAAmB,EAAE,MAAM,qCAAqC,CAAC;AAC1E,OAAO,EAAE,mBAAmB,EAAE,MAAM,qCAAqC,CAAC;AAC1E,OAAO,EAAE,uBAAuB,EAAE,MAAM,2CAA2C,CAAC;AACpF,OAAO,EAAE,2BAA2B,EAAE,MAAM,gDAAgD,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,YAAY,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAClE,YAAY,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAC9E,YAAY,EAAE,4BAA4B,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAAE,mBAAmB,EAAE,MAAM,qCAAqC,CAAC;AAC1E,OAAO,EAAE,mBAAmB,EAAE,MAAM,qCAAqC,CAAC;AAC1E,OAAO,EAAE,uBAAuB,EAAE,MAAM,2CAA2C,CAAC;AACpF,OAAO,EAAE,2BAA2B,EAAE,MAAM,gDAAgD,CAAC;AAC7F,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -261,6 +261,37 @@ var AppConfigBuilder = class {
|
|
|
261
261
|
}
|
|
262
262
|
};
|
|
263
263
|
|
|
264
|
+
// src/helpers.ts
|
|
265
|
+
function tryParseJson(text) {
|
|
266
|
+
try {
|
|
267
|
+
return JSON.parse(text, (_, value) => value);
|
|
268
|
+
} catch {
|
|
269
|
+
return text;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
__name(tryParseJson, "tryParseJson");
|
|
273
|
+
function nestKeys(record, separator) {
|
|
274
|
+
const result = {};
|
|
275
|
+
for (const [key, value] of Object.entries(record)) {
|
|
276
|
+
const parts = key.split(separator);
|
|
277
|
+
if (parts.length === 1) {
|
|
278
|
+
result[key] = value;
|
|
279
|
+
} else {
|
|
280
|
+
let current = result;
|
|
281
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
282
|
+
const part = parts[i];
|
|
283
|
+
if (typeof current[part] !== "object" || current[part] === null) {
|
|
284
|
+
current[part] = {};
|
|
285
|
+
}
|
|
286
|
+
current = current[part];
|
|
287
|
+
}
|
|
288
|
+
current[parts[parts.length - 1]] = value;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
return result;
|
|
292
|
+
}
|
|
293
|
+
__name(nestKeys, "nestKeys");
|
|
294
|
+
|
|
264
295
|
// src/sources/app.config.source.dotenv.ts
|
|
265
296
|
import dotenv from "dotenv";
|
|
266
297
|
var AppConfigSourceDotenv = class {
|
|
@@ -268,20 +299,24 @@ var AppConfigSourceDotenv = class {
|
|
|
268
299
|
__name(this, "AppConfigSourceDotenv");
|
|
269
300
|
}
|
|
270
301
|
filePath;
|
|
302
|
+
options;
|
|
271
303
|
/**
|
|
272
304
|
* Creates a new AppConfigSourceDotenv instance.
|
|
273
305
|
*
|
|
274
306
|
* @param filePath - Optional path to the `.env` file. If not provided, `dotenv` will
|
|
275
307
|
* look for a `.env` file in the current working directory.
|
|
308
|
+
* @param options - Optional configuration options.
|
|
276
309
|
*/
|
|
277
|
-
constructor(filePath) {
|
|
310
|
+
constructor(filePath, options) {
|
|
278
311
|
this.filePath = filePath;
|
|
312
|
+
this.options = options;
|
|
279
313
|
}
|
|
280
314
|
/**
|
|
281
315
|
* Loads environment variables from the `.env` file.
|
|
282
316
|
*
|
|
283
317
|
* Uses `dotenv.config()` to parse the file and load variables into the returned object.
|
|
284
|
-
* If
|
|
318
|
+
* If `options.groupSeparator` is set the flat keys are transformed into a nested object
|
|
319
|
+
* before being returned.
|
|
285
320
|
*
|
|
286
321
|
* @returns A promise that resolves to an object containing the parsed environment variables.
|
|
287
322
|
* @throws {Error} If there's an error reading or parsing the `.env` file.
|
|
@@ -294,7 +329,11 @@ var AppConfigSourceDotenv = class {
|
|
|
294
329
|
if (result.error) {
|
|
295
330
|
throw result.error;
|
|
296
331
|
}
|
|
297
|
-
|
|
332
|
+
const parsed = result.parsed ?? {};
|
|
333
|
+
if (this.options?.groupSeparator) {
|
|
334
|
+
return nestKeys(parsed, this.options.groupSeparator);
|
|
335
|
+
}
|
|
336
|
+
return parsed;
|
|
298
337
|
}
|
|
299
338
|
};
|
|
300
339
|
|
|
@@ -387,16 +426,6 @@ var AppConfigSourceYaml = class {
|
|
|
387
426
|
}
|
|
388
427
|
};
|
|
389
428
|
|
|
390
|
-
// src/helpers.ts
|
|
391
|
-
function tryParseJson(text) {
|
|
392
|
-
try {
|
|
393
|
-
return JSON.parse(text, (_, value) => value);
|
|
394
|
-
} catch {
|
|
395
|
-
return text;
|
|
396
|
-
}
|
|
397
|
-
}
|
|
398
|
-
__name(tryParseJson, "tryParseJson");
|
|
399
|
-
|
|
400
429
|
// src/providers/app.config.provider.dotenv.ts
|
|
401
430
|
var AppConfigProviderDotenv = class {
|
|
402
431
|
static {
|
|
@@ -601,6 +630,7 @@ export {
|
|
|
601
630
|
AppConfigProviderGcpSecrets,
|
|
602
631
|
AppConfigSourceDotenv,
|
|
603
632
|
AppConfigSourceJson,
|
|
604
|
-
AppConfigSourceYaml
|
|
633
|
+
AppConfigSourceYaml,
|
|
634
|
+
nestKeys
|
|
605
635
|
};
|
|
606
636
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/app.config.ts","../src/app.config.builder.ts","../src/object.visitor.ts","../src/sources/app.config.source.dotenv.ts","../src/sources/app.config.source.json.ts","../src/sources/app.config.source.yaml.ts","../src/helpers.ts","../src/providers/app.config.provider.dotenv.ts","../src/providers/app.config.provider.gcp.secrets.ts"],"sourcesContent":["/**\n * Configuration container that provides type-safe access to configuration values.\n *\n * @template T - The type of the configuration object. Defaults to `Record<string, unknown>`.\n *\n * @example\n * ```typescript\n * const config = new AppConfig({\n * database: { host: 'localhost', port: 5432 },\n * api: { timeout: 5000 }\n * });\n *\n * const host = config.get('database').host; // Type-safe access\n * ```\n */\nexport class AppConfig<T = Record<string, unknown>> {\n /**\n * Creates a new AppConfig instance with the provided configuration.\n *\n * @param config - The configuration object to wrap.\n */\n constructor(private readonly config: T) {}\n\n /**\n * Retrieves a configuration value by key.\n *\n * @template K - The key type, must be a key of T.\n * @param key - The configuration key to retrieve.\n * @returns The configuration value for the given key.\n *\n * @example\n * ```typescript\n * const config = new AppConfig({ port: 3000, host: 'localhost' });\n * const port = config.get('port'); // Returns 3000, typed as number\n * ```\n */\n get(key: keyof T): T[keyof T] {\n return this.config[key];\n }\n\n /**\n * Retrieves a configuration value cast to a specific type.\n *\n * Unlike `get()`, which returns `T[keyof T]`, this method lets you cast the\n * value to an arbitrary type `U`. Use this when the TypeScript type of the\n * stored value differs from what you need at the call site — for example,\n * when reading a nested object as a typed interface.\n *\n * @template U - The type to cast the value to.\n * @param key - The configuration key to retrieve.\n * @returns The configuration value cast to `U`.\n *\n * @example\n * ```typescript\n * interface DbConfig { host: string; port: number }\n *\n * const config = new AppConfig({ database: { host: 'localhost', port: 5432 } });\n * const db = config.getAs<DbConfig>('database');\n * console.log(db.host); // 'localhost'\n * ```\n */\n getAs<U>(key: keyof T): U {\n return this.config[key] as U;\n }\n\n /**\n * Retrieves a configuration value as a string.\n *\n * The value is converted to a string using `String()`. This is useful when\n * you need to ensure a value is a string regardless of its original type.\n *\n * @template K - The key type, must be a key of T.\n * @param key - The configuration key to retrieve.\n * @returns The configuration value converted to a string.\n *\n * @example\n * ```typescript\n * const config = new AppConfig({ port: 3000, enabled: true });\n * const portStr = config.getString('port'); // Returns \"3000\"\n * const enabledStr = config.getString('enabled'); // Returns \"true\"\n * ```\n */\n getString(key: keyof T): string {\n return String(this.get(key));\n }\n\n /**\n * Retrieves a configuration value as a number.\n *\n * The value is converted to a number using `Number()`. This is useful when\n * you need to ensure a value is a number regardless of its original type.\n * Note: Invalid conversions will result in `NaN`.\n *\n * @template K - The key type, must be a key of T.\n * @param key - The configuration key to retrieve.\n * @returns The configuration value converted to a number.\n *\n * @example\n * ```typescript\n * const config = new AppConfig({ port: '3000', timeout: '5000' });\n * const port = config.getNumber('port'); // Returns 3000\n * const timeout = config.getNumber('timeout'); // Returns 5000\n * ```\n */\n getNumber(key: keyof T): number {\n return Number(this.config[key]);\n }\n\n /**\n * Retrieves a configuration value as a boolean.\n *\n * The value is converted to a boolean using `Boolean()`. This is useful when\n * you need to ensure a value is a boolean regardless of its original type.\n * Note: Only falsy values (false, 0, '', null, undefined, NaN) become false.\n *\n * @template K - The key type, must be a key of T.\n * @param key - The configuration key to retrieve.\n * @returns The configuration value converted to a boolean.\n *\n * @example\n * ```typescript\n * const config = new AppConfig({ enabled: 'true', debug: 1 });\n * const enabled = config.getBoolean('enabled'); // Returns true\n * const debug = config.getBoolean('debug'); // Returns true\n * ```\n */\n getBoolean(key: keyof T): boolean {\n return Boolean(this.config[key]);\n }\n\n /**\n * Retrieves a configuration value as an object.\n *\n * The value is cast to an object type. This is useful when you know a value\n * is an object and want to access it with object methods.\n *\n * @template K - The key type, must be a key of T.\n * @param key - The configuration key to retrieve.\n * @returns The configuration value cast as an object.\n *\n * @example\n * ```typescript\n * const config = new AppConfig({\n * database: { host: 'localhost', port: 5432 }\n * });\n * const db = config.getObject('database'); // Returns { host: 'localhost', port: 5432 }\n * ```\n */\n getObject(key: keyof T): object {\n return this.config[key] as object;\n }\n}\n","import { deepmerge } from 'deepmerge-ts';\nimport { AppConfig } from './app.config.js';\nimport { AppConfigProvider } from './app.config.provider.js';\nimport { AppConfigSource } from './app.config.source.js';\nimport { objectVisitor, ObjectVisitorMeta } from './object.visitor.js';\n\n/**\n * Builder for constructing AppConfig instances from multiple sources with value transformation.\n *\n * The builder allows you to:\n * - Load configuration from multiple sources (files, environment variables, etc.)\n * - Merge configurations with later sources overriding earlier ones\n * - Transform string values using providers (e.g., resolving environment variable references)\n *\n * @example\n * ```typescript\n * const config = await new AppConfigBuilder()\n * .addSource(new AppConfigSourceJson('./config.json'))\n * .addSource(new AppConfigSourceDotenv())\n * .addProvider(new AppConfigProviderDotenv())\n * .build();\n * ```\n */\nexport class AppConfigBuilder {\n private readonly sources: AppConfigSource[] = [];\n private readonly providers: AppConfigProvider[] = [];\n\n /**\n * Adds a configuration source to the builder.\n *\n * Sources are loaded in the order they are added, and later sources override earlier ones\n * when merging configurations.\n *\n * @param source - The configuration source to add.\n * @returns The builder instance for method chaining.\n *\n * @example\n * ```typescript\n * builder\n * .addSource(new AppConfigSourceJson('./default.json'))\n * .addSource(new AppConfigSourceJson('./local.json'));\n * ```\n */\n addSource(source: AppConfigSource) {\n this.sources.push(source);\n return this;\n }\n\n /**\n * Adds a provider to transform string values during configuration building.\n *\n * Providers are applied to all string values found in the merged configuration.\n * The first provider that can parse a value will be used to transform it.\n *\n * @param provider - The provider to add.\n * @returns The builder instance for method chaining.\n *\n * @example\n * ```typescript\n * builder.addProvider(new AppConfigProviderDotenv());\n * ```\n */\n addProvider(provider: AppConfigProvider) {\n this.providers.push(provider);\n return this;\n }\n\n /**\n * Builds the AppConfig instance by loading all sources, merging them, and applying providers.\n *\n * The build process:\n * 1. Loads all sources in parallel\n * 2. Merges configurations (later sources override earlier ones)\n * 3. Traverses the merged configuration and applies providers to string values\n * 4. Returns the final AppConfig instance\n *\n * @template T - The type of the configuration object. Defaults to `Record<string, unknown>`.\n * @returns A promise that resolves to the built AppConfig instance.\n *\n * @example\n * ```typescript\n * const config = await builder.build<MyConfigType>();\n * const value = config.get('someKey');\n * ```\n */\n async build<T = Record<string, unknown>>(): Promise<AppConfig<T>> {\n const sourceTasks = await Promise.all(this.sources.map(x => x.load()));\n const mergedConfig = deepmerge(...sourceTasks) as T;\n\n const tasks: Promise<void>[] = [];\n const parse = (value: unknown, meta: ObjectVisitorMeta) => {\n if (typeof value === 'string') {\n const provider = this.providers.find(x => x.canParse(value));\n if (provider) {\n tasks.push(provider.parse(value, meta));\n }\n }\n };\n\n objectVisitor(mergedConfig, parse);\n await Promise.all(tasks);\n\n return new AppConfig<T>(mergedConfig);\n }\n}\n","/**\n * Metadata about a value's location within an object structure.\n */\nexport type ObjectVisitorMeta = {\n /** The full path to the value (e.g., \"database.host\" or \"items[0]\"). */\n path: string;\n /** The object that owns this property. */\n owner: object;\n /** The property name or array index path (e.g., \"host\" or \"items[0]\"). */\n propertyPath: string;\n /** The type of the property value. */\n propertyType: 'string' | 'number' | 'bigint' | 'boolean' | 'symbol' | 'undefined' | 'object' | 'function';\n /** The array index if the value is in an array, undefined otherwise. */\n arrayIndex?: number;\n};\n\n/**\n * Callback function invoked for each primitive value found during object traversal.\n *\n * @param value - The primitive value found.\n * @param meta - Metadata about the value's location in the object structure.\n */\nexport type ObjectVisitorCallback = (value: unknown, meta: ObjectVisitorMeta) => void;\n\n/**\n * Traverses an object structure and invokes a callback for each primitive value found.\n *\n * The visitor recursively traverses objects and arrays, calling the callback for each\n * primitive value (string, number, boolean, bigint) encountered. It skips functions,\n * symbols, null, and undefined values.\n *\n * @param obj - The object to traverse. Can be any value.\n * @param callback - The callback function to invoke for each primitive value.\n *\n * @example\n * ```typescript\n * const config = {\n * database: { host: 'localhost', port: 5432 },\n * items: ['a', 'b', 'c']\n * };\n *\n * objectVisitor(config, (value, meta) => {\n * console.log(`${meta.path} = ${value}`);\n * });\n * // Output:\n * // database.host = localhost\n * // database.port = 5432\n * // items[0] = a\n * // items[1] = b\n * // items[2] = c\n * ```\n */\nexport const objectVisitor = (obj: unknown, callback: ObjectVisitorCallback): void => {\n const visit = (\n obj: unknown,\n callback: ObjectVisitorCallback,\n path: string = '',\n owner: object = {},\n propertyPath: string = '',\n arrayIndex?: number,\n ): void => {\n if (!obj) {\n return;\n }\n\n switch (typeof obj) {\n case 'object':\n if (Array.isArray(obj)) {\n obj.forEach((item, index) => {\n visit(item, callback, path + `[${index}]`, obj, propertyPath + `[${index}]`, index);\n });\n } else {\n const entries = Object.entries(obj);\n for (const entry of entries) {\n visit(entry[1], callback, path + (path.length > 0 ? '.' : '') + entry[0], obj, entry[0]);\n }\n }\n break;\n case 'function':\n case 'symbol':\n case 'undefined':\n break;\n default:\n callback(obj, {\n owner,\n propertyPath,\n path,\n propertyType: typeof obj,\n arrayIndex,\n });\n break;\n }\n };\n\n visit(obj, callback);\n};\n","import { AppConfigSource } from '../app.config.source.js';\nimport dotenv from 'dotenv';\n\n/**\n * Configuration source that loads environment variables from a `.env` file.\n *\n * This source uses the `dotenv` package to load environment variables from a `.env` file.\n * If no file path is provided, it will look for a `.env` file in the current working directory.\n * All values are strings as provided by the environment file.\n *\n * @example\n * ```typescript\n * // Load from default .env file\n * const source1 = new AppConfigSourceDotenv();\n * const config1 = await source1.load();\n *\n * // Load from custom path\n * const source2 = new AppConfigSourceDotenv('./config/.env.local');\n * const config2 = await source2.load();\n * ```\n */\nexport class AppConfigSourceDotenv implements AppConfigSource {\n /**\n * Creates a new AppConfigSourceDotenv instance.\n *\n * @param filePath - Optional path to the `.env` file. If not provided, `dotenv` will\n * look for a `.env` file in the current working directory.\n */\n constructor(private readonly filePath?: string) {}\n\n /**\n * Loads environment variables from the `.env` file.\n *\n * Uses `dotenv.config()` to parse the file and load variables into the returned object.\n * If the file doesn't exist or there's an error, an error will be thrown.\n *\n * @returns A promise that resolves to an object containing the parsed environment variables.\n * @throws {Error} If there's an error reading or parsing the `.env` file.\n */\n async load(): Promise<Record<string, unknown>> {\n const result = dotenv.config({ path: this.filePath, quiet: true });\n if (result.error) {\n throw result.error;\n }\n return Promise.resolve(result.parsed ?? {});\n }\n}\n","import { existsSync } from 'node:fs';\nimport { AppConfigSource } from '../app.config.source.js';\nimport { readFile } from 'node:fs/promises';\nimport { AppConfigSourceFileOptions } from '../app.config.source.options.js';\n\n/**\n * Configuration source that loads configuration from a JSON file.\n *\n * This source reads a JSON file from the filesystem and parses it as a configuration object.\n * By default, it will return an empty object if the file doesn't exist instead of throwing an error.\n *\n * @example\n * ```typescript\n * // Load from JSON file, ignore if missing\n * const source1 = new AppConfigSourceJson('./config.json');\n *\n * // Load from JSON file, throw error if missing\n * const source2 = new AppConfigSourceJson('./config.json', {\n * ignoreMissingFile: false\n * });\n *\n * // Load with custom encoding\n * const source3 = new AppConfigSourceJson('./config.json', {\n * encoding: 'utf16le'\n * });\n * ```\n */\nexport class AppConfigSourceJson implements AppConfigSource {\n private readonly options: AppConfigSourceFileOptions;\n\n /**\n * Creates a new AppConfigSourceJson instance.\n *\n * @param filePath - The path to the JSON file to load.\n * @param options - Optional configuration for the source behavior.\n */\n constructor(\n private readonly filePath: string,\n options?: AppConfigSourceFileOptions,\n ) {\n this.options = {\n ignoreMissingFile: true,\n encoding: 'utf8',\n ...(options ?? {}),\n };\n }\n\n /**\n * Loads configuration from the JSON file.\n *\n * If the file doesn't exist and `ignoreMissingFile` is `true`, returns an empty object.\n * Otherwise, reads and parses the JSON file.\n *\n * @returns A promise that resolves to the parsed JSON configuration object.\n * @throws {Error} If the file doesn't exist and `ignoreMissingFile` is `false`,\n * or if the file contains invalid JSON.\n */\n async load(): Promise<Record<string, unknown>> {\n if (!existsSync(this.filePath) && this.options.ignoreMissingFile) {\n return {};\n }\n\n const file = await readFile(this.filePath, {\n encoding: this.options.encoding,\n });\n return JSON.parse(file.toString());\n }\n}\n","import { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport YAML from 'yaml';\nimport { AppConfigSource } from '../app.config.source.js';\nimport { AppConfigSourceFileOptions } from '../app.config.source.options.js';\n\n/**\n * Configuration source that loads configuration from a YAML file.\n *\n * This source reads a YAML file from the filesystem and parses it as a configuration object.\n * By default, it will return an empty object if the file doesn't exist instead of throwing an error.\n * Supports both `.yaml` and `.yml` file extensions.\n *\n * @example\n * ```typescript\n * // Load from YAML file, ignore if missing\n * const source1 = new AppConfigSourceYaml('./config.yaml');\n *\n * // Load from YAML file, throw error if missing\n * const source2 = new AppConfigSourceYaml('./config.yaml', {\n * ignoreMissingFile: false\n * });\n *\n * // Load with custom encoding\n * const source3 = new AppConfigSourceYaml('./config.yaml', {\n * encoding: 'utf16le'\n * });\n * ```\n */\nexport class AppConfigSourceYaml implements AppConfigSource {\n private readonly options: AppConfigSourceFileOptions;\n\n /**\n * Creates a new AppConfigSourceYaml instance.\n *\n * @param filePath - The path to the YAML file to load.\n * @param options - Optional configuration for the source behavior.\n */\n constructor(\n private readonly filePath: string,\n options?: AppConfigSourceFileOptions,\n ) {\n this.options = {\n ignoreMissingFile: true,\n encoding: 'utf8',\n ...(options ?? {}),\n };\n }\n\n /**\n * Loads configuration from the YAML file.\n *\n * If the file doesn't exist and `ignoreMissingFile` is `true`, returns an empty object.\n * Otherwise, reads and parses the YAML file.\n *\n * @returns A promise that resolves to the parsed YAML configuration object.\n * @throws {Error} If the file doesn't exist and `ignoreMissingFile` is `false`,\n * or if the file contains invalid YAML.\n */\n async load(): Promise<Record<string, unknown>> {\n if (!existsSync(this.filePath) && this.options.ignoreMissingFile) {\n return {};\n }\n\n const file = await readFile(this.filePath, {\n encoding: this.options.encoding,\n });\n return YAML.parse(file.toString());\n }\n}\n","/**\n * Attempts to parse a string as JSON, returning the original string if parsing fails.\n *\n * @param text - The text to parse.\n * @returns The parsed JSON value, or the original text if parsing fails.\n */\nexport function tryParseJson(text: string): unknown {\n try {\n return JSON.parse(text, (_, value) => value);\n } catch {\n return text;\n }\n}\n","import { AppConfigProvider } from '../app.config.provider.js';\nimport { ObjectVisitorMeta } from '../object.visitor.js';\nimport { tryParseJson } from '../helpers.js';\n\n/**\n * Provider that resolves environment variable references in configuration values.\n *\n * This provider matches string values using a regex pattern and replaces them with\n * values from `process.env`. The default pattern matches `${env:KEY}` and extracts\n * the key part to look up in the environment.\n *\n * After replacement, the result is attempted to be parsed as JSON. If parsing succeeds,\n * the parsed value is used; otherwise, the string value is used.\n *\n * @example\n * ```typescript\n * // With default pattern /\\$\\{env:(.+)\\}/g\n * // Value: \"${env:DATABASE_URL}\"\n * // Looks up: process.env.DATABASE_URL\n *\n * // Custom pattern\n * const provider = new AppConfigProviderDotenv(/\\$\\{([^}]+)\\}/g);\n * // Value: \"${DATABASE_URL}\"\n * // Looks up: process.env.DATABASE_URL\n * ```\n */\nexport class AppConfigProviderDotenv implements AppConfigProvider {\n private readonly prefix: RegExp;\n\n /**\n * Creates a new AppConfigProviderDotenv instance.\n *\n * @param prefix - A regex pattern or string to match environment variable references.\n * If a string is provided, it will be converted to a RegExp. The regex must have\n * at least one capture group that extracts the environment variable key.\n * Defaults to `/\\$\\{env:(.+)\\}/g` which matches `${env:KEY}` patterns.\n *\n * @example\n * ```typescript\n * // Default pattern\n * const provider1 = new AppConfigProviderDotenv();\n *\n * // Custom regex pattern\n * const provider2 = new AppConfigProviderDotenv(/\\$\\{([^}]+)\\}/g);\n *\n * // String pattern (converted to RegExp)\n * const provider3 = new AppConfigProviderDotenv('env:');\n * ```\n */\n constructor(prefix: string | RegExp = /\\$\\{env:(.+)\\}/g) {\n this.prefix = typeof prefix === 'string' ? new RegExp(prefix) : prefix;\n }\n\n /**\n * Checks if this provider can parse the given value.\n *\n * @param value - The string value to check.\n * @returns `true` if the value matches the provider's regex pattern, `false` otherwise.\n */\n canParse(value: string): boolean {\n this.prefix.lastIndex = 0;\n return this.prefix.test(value);\n }\n\n /**\n * Parses the value by replacing environment variable references with actual values.\n *\n * The method:\n * 1. Finds all matches of the regex pattern in the value\n * 2. Replaces each match with the corresponding value from `process.env`\n * 3. Attempts to parse the result as JSON\n * 4. Updates the configuration object with the final value\n *\n * @param value - The string value containing environment variable references.\n * @param meta - Metadata about the value's location in the configuration object.\n * @returns A promise that resolves when the transformation is complete.\n *\n * @example\n * ```typescript\n * // If process.env.DATABASE_URL = \"postgres://localhost/db\"\n * // Value: \"${env:DATABASE_URL}\"\n * // Result: \"postgres://localhost/db\"\n *\n * // If process.env.PORT = \"3000\"\n * // Value: \"${env:PORT}\"\n * // Result: 3000 (parsed as JSON number)\n * ```\n */\n async parse(value: string, meta: ObjectVisitorMeta): Promise<void> {\n const matches = value.matchAll(this.prefix);\n\n let result = value;\n for (const [found, key] of matches) {\n result = result.replaceAll(found, process.env[key!] ?? '');\n }\n\n if (meta.arrayIndex !== undefined && Array.isArray(meta.owner)) {\n meta.owner[meta.arrayIndex] = tryParseJson(result ?? '');\n } else {\n (meta.owner as Record<string, unknown>)[meta.propertyPath] = tryParseJson(result ?? '');\n }\n }\n}\n","import { Injectable } from 'injectkit';\nimport { AppConfigProvider } from '../app.config.provider.js';\nimport { ObjectVisitorMeta } from '../object.visitor.js';\nimport { SecretManagerServiceClient } from '@google-cloud/secret-manager';\nimport { tryParseJson } from '../helpers.js';\n\n/**\n * Provider that resolves Google Cloud Platform Secret Manager references in configuration values.\n *\n * This provider matches string values using a regex pattern and replaces them with\n * secrets fetched from GCP Secret Manager. The default pattern matches `${gcp:SECRET_NAME}`\n * and extracts the secret name to look up in Secret Manager.\n *\n * After retrieval, the secret value is attempted to be parsed as JSON. If parsing succeeds,\n * the parsed value is used; otherwise, the string value is used.\n *\n * @remarks\n * This provider requires valid GCP credentials to be configured. It uses the\n * `@google-cloud/secret-manager` package and will use Application Default Credentials (ADC).\n *\n * @example\n * ```typescript\n * // With default pattern /\\$\\{gcp:(.+)\\}/g\n * // Value: \"${gcp:DATABASE_PASSWORD}\"\n * // Fetches: projects/{projectId}/secrets/DATABASE_PASSWORD/versions/latest\n *\n * const config = await new AppConfigBuilder()\n * .addSource(new AppConfigSourceJson('./config.json'))\n * .addProvider(new AppConfigProviderGcpSecrets('my-gcp-project'))\n * .build();\n * ```\n */\n@Injectable()\nexport class AppConfigProviderGcpSecrets implements AppConfigProvider {\n private readonly secretmanagerClient = new SecretManagerServiceClient();\n private readonly prefix: RegExp;\n\n /**\n * Creates a new AppConfigProviderGcpSecrets instance.\n *\n * @param projectId - The GCP project ID where secrets are stored.\n * @param prefix - A regex pattern or string to match secret references.\n * If a string is provided, it will be converted to a RegExp. The regex must have\n * at least one capture group that extracts the secret name.\n * Defaults to `/\\$\\{gcp:(.+)\\}/g` which matches `${gcp:SECRET_NAME}` patterns.\n *\n * @example\n * ```typescript\n * // Default pattern\n * const provider1 = new AppConfigProviderGcpSecrets('my-project');\n *\n * // Custom regex pattern\n * const provider2 = new AppConfigProviderGcpSecrets('my-project', /\\$\\{secret:([^}]+)\\}/g);\n * ```\n */\n constructor(\n private readonly projectId: string,\n prefix: string | RegExp = /\\$\\{gcp:(.+)\\}/g,\n ) {\n this.prefix = typeof prefix === 'string' ? new RegExp(prefix) : prefix;\n }\n\n /**\n * Checks if this provider can parse the given value.\n *\n * @param value - The string value to check.\n * @returns `true` if the value matches the provider's regex pattern, `false` otherwise.\n */\n canParse(value: string): boolean {\n return this.prefix.test(value);\n }\n\n /**\n * Fetches a secret from GCP Secret Manager.\n *\n * @param secretId - The name of the secret to fetch.\n * @returns A promise that resolves to the secret value, or an empty string if the secret\n * couldn't be fetched.\n * @internal\n */\n private async getSecret(secretId: string): Promise<string> {\n try {\n const [secret] = await this.secretmanagerClient.accessSecretVersion({\n name: `projects/${this.projectId}/secrets/${secretId}/versions/latest`,\n });\n return secret.payload?.data?.toString() ?? '';\n } catch (error) {\n console.error(error);\n return '';\n }\n }\n\n /**\n * Parses the value by replacing GCP secret references with actual secret values.\n *\n * The method:\n * 1. Finds all matches of the regex pattern in the value\n * 2. Fetches each secret from GCP Secret Manager in parallel\n * 3. Attempts to parse each result as JSON\n * 4. Updates the configuration object with the final value\n *\n * @param value - The string value containing GCP secret references.\n * @param meta - Metadata about the value's location in the configuration object.\n * @returns A promise that resolves when all secrets have been fetched and the\n * transformation is complete.\n *\n * @example\n * ```typescript\n * // If GCP secret \"API_KEY\" contains \"sk-abc123\"\n * // Value: \"${gcp:API_KEY}\"\n * // Result: \"sk-abc123\"\n *\n * // If GCP secret \"CONFIG\" contains '{\"retries\": 3}'\n * // Value: \"${gcp:CONFIG}\"\n * // Result: { retries: 3 } (parsed as JSON object)\n * ```\n */\n async parse(value: string, meta: ObjectVisitorMeta): Promise<void> {\n const tasks: Promise<void>[] = [];\n const matches = value.matchAll(this.prefix);\n\n for (const [, key] of matches) {\n const task = this.getSecret(key!).then(value => {\n if (meta.arrayIndex !== undefined && Array.isArray(meta.owner)) {\n meta.owner[meta.arrayIndex] = tryParseJson(value);\n } else {\n (meta.owner as Record<string, unknown>)[meta.propertyPath] = tryParseJson(value);\n }\n });\n tasks.push(task);\n }\n\n await Promise.all(tasks);\n }\n}\n"],"mappings":";;;;AAeO,IAAMA,YAAN,MAAMA;EAfb,OAeaA;;;;;;;;;EAMX,YAA6BC,QAAW;SAAXA,SAAAA;EAAY;;;;;;;;;;;;;;EAezCC,IAAIC,KAA0B;AAC5B,WAAO,KAAKF,OAAOE,GAAAA;EACrB;;;;;;;;;;;;;;;;;;;;;;EAuBAC,MAASD,KAAiB;AACxB,WAAO,KAAKF,OAAOE,GAAAA;EACrB;;;;;;;;;;;;;;;;;;EAmBAE,UAAUF,KAAsB;AAC9B,WAAOG,OAAO,KAAKJ,IAAIC,GAAAA,CAAAA;EACzB;;;;;;;;;;;;;;;;;;;EAoBAI,UAAUJ,KAAsB;AAC9B,WAAOK,OAAO,KAAKP,OAAOE,GAAAA,CAAI;EAChC;;;;;;;;;;;;;;;;;;;EAoBAM,WAAWN,KAAuB;AAChC,WAAOO,QAAQ,KAAKT,OAAOE,GAAAA,CAAI;EACjC;;;;;;;;;;;;;;;;;;;EAoBAQ,UAAUR,KAAsB;AAC9B,WAAO,KAAKF,OAAOE,GAAAA;EACrB;AACF;;;ACvJA,SAASS,iBAAiB;;;ACoDnB,IAAMC,gBAAgB,wBAACC,KAAcC,aAAAA;AAC1C,QAAMC,QAAQ,wBACZF,MACAC,WACAE,OAAe,IACfC,QAAgB,CAAC,GACjBC,eAAuB,IACvBC,eAAAA;AAEA,QAAI,CAACN,MAAK;AACR;IACF;AAEA,YAAQ,OAAOA,MAAAA;MACb,KAAK;AACH,YAAIO,MAAMC,QAAQR,IAAAA,GAAM;AACtBA,UAAAA,KAAIS,QAAQ,CAACC,MAAMC,UAAAA;AACjBT,kBAAMQ,M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","getBoolean","Boolean","getObject","deepmerge","objectVisitor","obj","callback","visit","path","owner","propertyPath","arrayIndex","Array","isArray","forEach","item","index","entries","Object","entry","length","propertyType","AppConfigBuilder","sources","providers","addSource","source","push","addProvider","provider","build","sourceTasks","Promise","all","map","x","load","mergedConfig","deepmerge","tasks","parse","value","meta","find","canParse","objectVisitor","AppConfig","dotenv","AppConfigSourceDotenv","filePath","load","result","dotenv","config","path","quiet","error","Promise","resolve","parsed","existsSync","readFile","AppConfigSourceJson","options","filePath","ignoreMissingFile","encoding","load","existsSync","file","readFile","JSON","parse","toString","existsSync","readFile","YAML","AppConfigSourceYaml","options","filePath","ignoreMissingFile","encoding","load","existsSync","file","readFile","YAML","parse","toString","tryParseJson","text","JSON","parse","_","value","AppConfigProviderDotenv","prefix","RegExp","canParse","value","lastIndex","test","parse","meta","matches","matchAll","result","found","key","replaceAll","process","env","arrayIndex","undefined","Array","isArray","owner","tryParseJson","propertyPath","Injectable","SecretManagerServiceClient","AppConfigProviderGcpSecrets","secretmanagerClient","SecretManagerServiceClient","prefix","projectId","RegExp","canParse","value","test","getSecret","secretId","secret","accessSecretVersion","name","payload","data","toString","error","console","parse","meta","tasks","matches","matchAll","key","task","then","arrayIndex","undefined","Array","isArray","owner","tryParseJson","propertyPath","push","Promise","all"]}
|
|
1
|
+
{"version":3,"sources":["../src/app.config.ts","../src/app.config.builder.ts","../src/object.visitor.ts","../src/helpers.ts","../src/sources/app.config.source.dotenv.ts","../src/sources/app.config.source.json.ts","../src/sources/app.config.source.yaml.ts","../src/providers/app.config.provider.dotenv.ts","../src/providers/app.config.provider.gcp.secrets.ts"],"sourcesContent":["/**\n * Configuration container that provides type-safe access to configuration values.\n *\n * @template T - The type of the configuration object. Defaults to `Record<string, unknown>`.\n *\n * @example\n * ```typescript\n * const config = new AppConfig({\n * database: { host: 'localhost', port: 5432 },\n * api: { timeout: 5000 }\n * });\n *\n * const host = config.get('database').host; // Type-safe access\n * ```\n */\nexport class AppConfig<T = Record<string, unknown>> {\n /**\n * Creates a new AppConfig instance with the provided configuration.\n *\n * @param config - The configuration object to wrap.\n */\n constructor(private readonly config: T) {}\n\n /**\n * Retrieves a configuration value by key.\n *\n * @template K - The key type, must be a key of T.\n * @param key - The configuration key to retrieve.\n * @returns The configuration value for the given key.\n *\n * @example\n * ```typescript\n * const config = new AppConfig({ port: 3000, host: 'localhost' });\n * const port = config.get('port'); // Returns 3000, typed as number\n * ```\n */\n get(key: keyof T): T[keyof T] {\n return this.config[key];\n }\n\n /**\n * Retrieves a configuration value cast to a specific type.\n *\n * Unlike `get()`, which returns `T[keyof T]`, this method lets you cast the\n * value to an arbitrary type `U`. Use this when the TypeScript type of the\n * stored value differs from what you need at the call site — for example,\n * when reading a nested object as a typed interface.\n *\n * @template U - The type to cast the value to.\n * @param key - The configuration key to retrieve.\n * @returns The configuration value cast to `U`.\n *\n * @example\n * ```typescript\n * interface DbConfig { host: string; port: number }\n *\n * const config = new AppConfig({ database: { host: 'localhost', port: 5432 } });\n * const db = config.getAs<DbConfig>('database');\n * console.log(db.host); // 'localhost'\n * ```\n */\n getAs<U>(key: keyof T): U {\n return this.config[key] as U;\n }\n\n /**\n * Retrieves a configuration value as a string.\n *\n * The value is converted to a string using `String()`. This is useful when\n * you need to ensure a value is a string regardless of its original type.\n *\n * @template K - The key type, must be a key of T.\n * @param key - The configuration key to retrieve.\n * @returns The configuration value converted to a string.\n *\n * @example\n * ```typescript\n * const config = new AppConfig({ port: 3000, enabled: true });\n * const portStr = config.getString('port'); // Returns \"3000\"\n * const enabledStr = config.getString('enabled'); // Returns \"true\"\n * ```\n */\n getString(key: keyof T): string {\n return String(this.get(key));\n }\n\n /**\n * Retrieves a configuration value as a number.\n *\n * The value is converted to a number using `Number()`. This is useful when\n * you need to ensure a value is a number regardless of its original type.\n * Note: Invalid conversions will result in `NaN`.\n *\n * @template K - The key type, must be a key of T.\n * @param key - The configuration key to retrieve.\n * @returns The configuration value converted to a number.\n *\n * @example\n * ```typescript\n * const config = new AppConfig({ port: '3000', timeout: '5000' });\n * const port = config.getNumber('port'); // Returns 3000\n * const timeout = config.getNumber('timeout'); // Returns 5000\n * ```\n */\n getNumber(key: keyof T): number {\n return Number(this.config[key]);\n }\n\n /**\n * Retrieves a configuration value as a boolean.\n *\n * The value is converted to a boolean using `Boolean()`. This is useful when\n * you need to ensure a value is a boolean regardless of its original type.\n * Note: Only falsy values (false, 0, '', null, undefined, NaN) become false.\n *\n * @template K - The key type, must be a key of T.\n * @param key - The configuration key to retrieve.\n * @returns The configuration value converted to a boolean.\n *\n * @example\n * ```typescript\n * const config = new AppConfig({ enabled: 'true', debug: 1 });\n * const enabled = config.getBoolean('enabled'); // Returns true\n * const debug = config.getBoolean('debug'); // Returns true\n * ```\n */\n getBoolean(key: keyof T): boolean {\n return Boolean(this.config[key]);\n }\n\n /**\n * Retrieves a configuration value as an object.\n *\n * The value is cast to an object type. This is useful when you know a value\n * is an object and want to access it with object methods.\n *\n * @template K - The key type, must be a key of T.\n * @param key - The configuration key to retrieve.\n * @returns The configuration value cast as an object.\n *\n * @example\n * ```typescript\n * const config = new AppConfig({\n * database: { host: 'localhost', port: 5432 }\n * });\n * const db = config.getObject('database'); // Returns { host: 'localhost', port: 5432 }\n * ```\n */\n getObject(key: keyof T): object {\n return this.config[key] as object;\n }\n}\n","import { deepmerge } from 'deepmerge-ts';\nimport { AppConfig } from './app.config.js';\nimport { AppConfigProvider } from './app.config.provider.js';\nimport { AppConfigSource } from './app.config.source.js';\nimport { objectVisitor, ObjectVisitorMeta } from './object.visitor.js';\n\n/**\n * Builder for constructing AppConfig instances from multiple sources with value transformation.\n *\n * The builder allows you to:\n * - Load configuration from multiple sources (files, environment variables, etc.)\n * - Merge configurations with later sources overriding earlier ones\n * - Transform string values using providers (e.g., resolving environment variable references)\n *\n * @example\n * ```typescript\n * const config = await new AppConfigBuilder()\n * .addSource(new AppConfigSourceJson('./config.json'))\n * .addSource(new AppConfigSourceDotenv())\n * .addProvider(new AppConfigProviderDotenv())\n * .build();\n * ```\n */\nexport class AppConfigBuilder {\n private readonly sources: AppConfigSource[] = [];\n private readonly providers: AppConfigProvider[] = [];\n\n /**\n * Adds a configuration source to the builder.\n *\n * Sources are loaded in the order they are added, and later sources override earlier ones\n * when merging configurations.\n *\n * @param source - The configuration source to add.\n * @returns The builder instance for method chaining.\n *\n * @example\n * ```typescript\n * builder\n * .addSource(new AppConfigSourceJson('./default.json'))\n * .addSource(new AppConfigSourceJson('./local.json'));\n * ```\n */\n addSource(source: AppConfigSource) {\n this.sources.push(source);\n return this;\n }\n\n /**\n * Adds a provider to transform string values during configuration building.\n *\n * Providers are applied to all string values found in the merged configuration.\n * The first provider that can parse a value will be used to transform it.\n *\n * @param provider - The provider to add.\n * @returns The builder instance for method chaining.\n *\n * @example\n * ```typescript\n * builder.addProvider(new AppConfigProviderDotenv());\n * ```\n */\n addProvider(provider: AppConfigProvider) {\n this.providers.push(provider);\n return this;\n }\n\n /**\n * Builds the AppConfig instance by loading all sources, merging them, and applying providers.\n *\n * The build process:\n * 1. Loads all sources in parallel\n * 2. Merges configurations (later sources override earlier ones)\n * 3. Traverses the merged configuration and applies providers to string values\n * 4. Returns the final AppConfig instance\n *\n * @template T - The type of the configuration object. Defaults to `Record<string, unknown>`.\n * @returns A promise that resolves to the built AppConfig instance.\n *\n * @example\n * ```typescript\n * const config = await builder.build<MyConfigType>();\n * const value = config.get('someKey');\n * ```\n */\n async build<T = Record<string, unknown>>(): Promise<AppConfig<T>> {\n const sourceTasks = await Promise.all(this.sources.map(x => x.load()));\n const mergedConfig = deepmerge(...sourceTasks) as T;\n\n const tasks: Promise<void>[] = [];\n const parse = (value: unknown, meta: ObjectVisitorMeta) => {\n if (typeof value === 'string') {\n const provider = this.providers.find(x => x.canParse(value));\n if (provider) {\n tasks.push(provider.parse(value, meta));\n }\n }\n };\n\n objectVisitor(mergedConfig, parse);\n await Promise.all(tasks);\n\n return new AppConfig<T>(mergedConfig);\n }\n}\n","/**\n * Metadata about a value's location within an object structure.\n */\nexport type ObjectVisitorMeta = {\n /** The full path to the value (e.g., \"database.host\" or \"items[0]\"). */\n path: string;\n /** The object that owns this property. */\n owner: object;\n /** The property name or array index path (e.g., \"host\" or \"items[0]\"). */\n propertyPath: string;\n /** The type of the property value. */\n propertyType: 'string' | 'number' | 'bigint' | 'boolean' | 'symbol' | 'undefined' | 'object' | 'function';\n /** The array index if the value is in an array, undefined otherwise. */\n arrayIndex?: number;\n};\n\n/**\n * Callback function invoked for each primitive value found during object traversal.\n *\n * @param value - The primitive value found.\n * @param meta - Metadata about the value's location in the object structure.\n */\nexport type ObjectVisitorCallback = (value: unknown, meta: ObjectVisitorMeta) => void;\n\n/**\n * Traverses an object structure and invokes a callback for each primitive value found.\n *\n * The visitor recursively traverses objects and arrays, calling the callback for each\n * primitive value (string, number, boolean, bigint) encountered. It skips functions,\n * symbols, null, and undefined values.\n *\n * @param obj - The object to traverse. Can be any value.\n * @param callback - The callback function to invoke for each primitive value.\n *\n * @example\n * ```typescript\n * const config = {\n * database: { host: 'localhost', port: 5432 },\n * items: ['a', 'b', 'c']\n * };\n *\n * objectVisitor(config, (value, meta) => {\n * console.log(`${meta.path} = ${value}`);\n * });\n * // Output:\n * // database.host = localhost\n * // database.port = 5432\n * // items[0] = a\n * // items[1] = b\n * // items[2] = c\n * ```\n */\nexport const objectVisitor = (obj: unknown, callback: ObjectVisitorCallback): void => {\n const visit = (\n obj: unknown,\n callback: ObjectVisitorCallback,\n path: string = '',\n owner: object = {},\n propertyPath: string = '',\n arrayIndex?: number,\n ): void => {\n if (!obj) {\n return;\n }\n\n switch (typeof obj) {\n case 'object':\n if (Array.isArray(obj)) {\n obj.forEach((item, index) => {\n visit(item, callback, path + `[${index}]`, obj, propertyPath + `[${index}]`, index);\n });\n } else {\n const entries = Object.entries(obj);\n for (const entry of entries) {\n visit(entry[1], callback, path + (path.length > 0 ? '.' : '') + entry[0], obj, entry[0]);\n }\n }\n break;\n case 'function':\n case 'symbol':\n case 'undefined':\n break;\n default:\n callback(obj, {\n owner,\n propertyPath,\n path,\n propertyType: typeof obj,\n arrayIndex,\n });\n break;\n }\n };\n\n visit(obj, callback);\n};\n","/**\n * Attempts to parse a string as JSON, returning the original string if parsing fails.\n *\n * @param text - The text to parse.\n * @returns The parsed JSON value, or the original text if parsing fails.\n */\nexport function tryParseJson(text: string): unknown {\n try {\n return JSON.parse(text, (_, value) => value);\n } catch {\n return text;\n }\n}\n\n/**\n * Transforms a flat key/value record into a nested object by splitting keys on a\n * separator string.\n *\n * Each key is split into path segments. Intermediate objects are created as needed.\n * If a path segment collides with an existing non-object value it is replaced by the\n * new object. Keys that do not contain the separator are passed through unchanged.\n *\n * Supports arbitrary nesting depth — a key with N separators produces N+1 levels.\n *\n * @param record - The flat key/value record to transform.\n * @param separator - The string used to delimit path segments (e.g. `'__'`).\n * @returns A new nested object.\n *\n * @example\n * ```typescript\n * nestKeys(\n * {\n * WEBHOOK__secret: 'abc',\n * WEBHOOK__header: 'X-Sig',\n * DATABASE_URL: 'postgres://localhost/db',\n * },\n * '__',\n * );\n * // → { WEBHOOK: { secret: 'abc', header: 'X-Sig' }, DATABASE_URL: 'postgres://localhost/db' }\n * ```\n */\nexport function nestKeys(record: Record<string, unknown>, separator: string): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(record)) {\n const parts = key.split(separator);\n\n if (parts.length === 1) {\n result[key] = value;\n } else {\n let current = result;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i]!;\n if (typeof current[part] !== 'object' || current[part] === null) {\n current[part] = {};\n }\n current = current[part] as Record<string, unknown>;\n }\n current[parts[parts.length - 1]!] = value;\n }\n }\n\n return result;\n}\n","import { AppConfigSource } from '../app.config.source.js';\nimport { nestKeys } from '../helpers.js';\nimport dotenv from 'dotenv';\n\n/**\n * Options for {@link AppConfigSourceDotenv}.\n */\nexport interface AppConfigSourceDotenvOptions {\n /**\n * When set, keys containing this separator are split into nested objects.\n *\n * For example, with `groupSeparator: '__'` the key `WEBHOOK__secret` becomes\n * `{ WEBHOOK: { secret: '...' } }`. Supports arbitrary nesting depth.\n *\n * @example\n * ```typescript\n * // .env\n * // WEBHOOK__secret=abc\n * // WEBHOOK__header=X-Sig\n * // DATABASE_URL=postgres://localhost/db\n *\n * const source = new AppConfigSourceDotenv('./.env', { groupSeparator: '__' });\n * await source.load();\n * // → { WEBHOOK: { secret: 'abc', header: 'X-Sig' }, DATABASE_URL: 'postgres://localhost/db' }\n * ```\n */\n groupSeparator?: string;\n}\n\n/**\n * Configuration source that loads environment variables from a `.env` file.\n *\n * This source uses the `dotenv` package to load environment variables from a `.env` file.\n * If no file path is provided, it will look for a `.env` file in the current working directory.\n * All values are strings as provided by the environment file.\n *\n * When the `groupSeparator` option is set, keys that contain the separator are automatically\n * collapsed into nested objects. This is useful for grouping related env vars under a shared\n * prefix (e.g. `WEBHOOK__secret` and `WEBHOOK__header` → `{ WEBHOOK: { secret, header } }`).\n *\n * @example\n * ```typescript\n * // Load from default .env file\n * const source1 = new AppConfigSourceDotenv();\n * const config1 = await source1.load();\n *\n * // Load from custom path\n * const source2 = new AppConfigSourceDotenv('./config/.env.local');\n * const config2 = await source2.load();\n *\n * // Group keys with __ separator into nested objects\n * const source3 = new AppConfigSourceDotenv('./.env', { groupSeparator: '__' });\n * const config3 = await source3.load();\n * ```\n */\nexport class AppConfigSourceDotenv implements AppConfigSource {\n /**\n * Creates a new AppConfigSourceDotenv instance.\n *\n * @param filePath - Optional path to the `.env` file. If not provided, `dotenv` will\n * look for a `.env` file in the current working directory.\n * @param options - Optional configuration options.\n */\n constructor(\n private readonly filePath?: string,\n private readonly options?: AppConfigSourceDotenvOptions,\n ) {}\n\n /**\n * Loads environment variables from the `.env` file.\n *\n * Uses `dotenv.config()` to parse the file and load variables into the returned object.\n * If `options.groupSeparator` is set the flat keys are transformed into a nested object\n * before being returned.\n *\n * @returns A promise that resolves to an object containing the parsed environment variables.\n * @throws {Error} If there's an error reading or parsing the `.env` file.\n */\n async load(): Promise<Record<string, unknown>> {\n const result = dotenv.config({ path: this.filePath, quiet: true });\n if (result.error) {\n throw result.error;\n }\n const parsed = result.parsed ?? {};\n\n if (this.options?.groupSeparator) {\n return nestKeys(parsed, this.options.groupSeparator);\n }\n\n return parsed;\n }\n}\n","import { existsSync } from 'node:fs';\nimport { AppConfigSource } from '../app.config.source.js';\nimport { readFile } from 'node:fs/promises';\nimport { AppConfigSourceFileOptions } from '../app.config.source.options.js';\n\n/**\n * Configuration source that loads configuration from a JSON file.\n *\n * This source reads a JSON file from the filesystem and parses it as a configuration object.\n * By default, it will return an empty object if the file doesn't exist instead of throwing an error.\n *\n * @example\n * ```typescript\n * // Load from JSON file, ignore if missing\n * const source1 = new AppConfigSourceJson('./config.json');\n *\n * // Load from JSON file, throw error if missing\n * const source2 = new AppConfigSourceJson('./config.json', {\n * ignoreMissingFile: false\n * });\n *\n * // Load with custom encoding\n * const source3 = new AppConfigSourceJson('./config.json', {\n * encoding: 'utf16le'\n * });\n * ```\n */\nexport class AppConfigSourceJson implements AppConfigSource {\n private readonly options: AppConfigSourceFileOptions;\n\n /**\n * Creates a new AppConfigSourceJson instance.\n *\n * @param filePath - The path to the JSON file to load.\n * @param options - Optional configuration for the source behavior.\n */\n constructor(\n private readonly filePath: string,\n options?: AppConfigSourceFileOptions,\n ) {\n this.options = {\n ignoreMissingFile: true,\n encoding: 'utf8',\n ...(options ?? {}),\n };\n }\n\n /**\n * Loads configuration from the JSON file.\n *\n * If the file doesn't exist and `ignoreMissingFile` is `true`, returns an empty object.\n * Otherwise, reads and parses the JSON file.\n *\n * @returns A promise that resolves to the parsed JSON configuration object.\n * @throws {Error} If the file doesn't exist and `ignoreMissingFile` is `false`,\n * or if the file contains invalid JSON.\n */\n async load(): Promise<Record<string, unknown>> {\n if (!existsSync(this.filePath) && this.options.ignoreMissingFile) {\n return {};\n }\n\n const file = await readFile(this.filePath, {\n encoding: this.options.encoding,\n });\n return JSON.parse(file.toString());\n }\n}\n","import { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport YAML from 'yaml';\nimport { AppConfigSource } from '../app.config.source.js';\nimport { AppConfigSourceFileOptions } from '../app.config.source.options.js';\n\n/**\n * Configuration source that loads configuration from a YAML file.\n *\n * This source reads a YAML file from the filesystem and parses it as a configuration object.\n * By default, it will return an empty object if the file doesn't exist instead of throwing an error.\n * Supports both `.yaml` and `.yml` file extensions.\n *\n * @example\n * ```typescript\n * // Load from YAML file, ignore if missing\n * const source1 = new AppConfigSourceYaml('./config.yaml');\n *\n * // Load from YAML file, throw error if missing\n * const source2 = new AppConfigSourceYaml('./config.yaml', {\n * ignoreMissingFile: false\n * });\n *\n * // Load with custom encoding\n * const source3 = new AppConfigSourceYaml('./config.yaml', {\n * encoding: 'utf16le'\n * });\n * ```\n */\nexport class AppConfigSourceYaml implements AppConfigSource {\n private readonly options: AppConfigSourceFileOptions;\n\n /**\n * Creates a new AppConfigSourceYaml instance.\n *\n * @param filePath - The path to the YAML file to load.\n * @param options - Optional configuration for the source behavior.\n */\n constructor(\n private readonly filePath: string,\n options?: AppConfigSourceFileOptions,\n ) {\n this.options = {\n ignoreMissingFile: true,\n encoding: 'utf8',\n ...(options ?? {}),\n };\n }\n\n /**\n * Loads configuration from the YAML file.\n *\n * If the file doesn't exist and `ignoreMissingFile` is `true`, returns an empty object.\n * Otherwise, reads and parses the YAML file.\n *\n * @returns A promise that resolves to the parsed YAML configuration object.\n * @throws {Error} If the file doesn't exist and `ignoreMissingFile` is `false`,\n * or if the file contains invalid YAML.\n */\n async load(): Promise<Record<string, unknown>> {\n if (!existsSync(this.filePath) && this.options.ignoreMissingFile) {\n return {};\n }\n\n const file = await readFile(this.filePath, {\n encoding: this.options.encoding,\n });\n return YAML.parse(file.toString());\n }\n}\n","import { AppConfigProvider } from '../app.config.provider.js';\nimport { ObjectVisitorMeta } from '../object.visitor.js';\nimport { tryParseJson } from '../helpers.js';\n\n/**\n * Provider that resolves environment variable references in configuration values.\n *\n * This provider matches string values using a regex pattern and replaces them with\n * values from `process.env`. The default pattern matches `${env:KEY}` and extracts\n * the key part to look up in the environment.\n *\n * After replacement, the result is attempted to be parsed as JSON. If parsing succeeds,\n * the parsed value is used; otherwise, the string value is used.\n *\n * @example\n * ```typescript\n * // With default pattern /\\$\\{env:(.+)\\}/g\n * // Value: \"${env:DATABASE_URL}\"\n * // Looks up: process.env.DATABASE_URL\n *\n * // Custom pattern\n * const provider = new AppConfigProviderDotenv(/\\$\\{([^}]+)\\}/g);\n * // Value: \"${DATABASE_URL}\"\n * // Looks up: process.env.DATABASE_URL\n * ```\n */\nexport class AppConfigProviderDotenv implements AppConfigProvider {\n private readonly prefix: RegExp;\n\n /**\n * Creates a new AppConfigProviderDotenv instance.\n *\n * @param prefix - A regex pattern or string to match environment variable references.\n * If a string is provided, it will be converted to a RegExp. The regex must have\n * at least one capture group that extracts the environment variable key.\n * Defaults to `/\\$\\{env:(.+)\\}/g` which matches `${env:KEY}` patterns.\n *\n * @example\n * ```typescript\n * // Default pattern\n * const provider1 = new AppConfigProviderDotenv();\n *\n * // Custom regex pattern\n * const provider2 = new AppConfigProviderDotenv(/\\$\\{([^}]+)\\}/g);\n *\n * // String pattern (converted to RegExp)\n * const provider3 = new AppConfigProviderDotenv('env:');\n * ```\n */\n constructor(prefix: string | RegExp = /\\$\\{env:(.+)\\}/g) {\n this.prefix = typeof prefix === 'string' ? new RegExp(prefix) : prefix;\n }\n\n /**\n * Checks if this provider can parse the given value.\n *\n * @param value - The string value to check.\n * @returns `true` if the value matches the provider's regex pattern, `false` otherwise.\n */\n canParse(value: string): boolean {\n this.prefix.lastIndex = 0;\n return this.prefix.test(value);\n }\n\n /**\n * Parses the value by replacing environment variable references with actual values.\n *\n * The method:\n * 1. Finds all matches of the regex pattern in the value\n * 2. Replaces each match with the corresponding value from `process.env`\n * 3. Attempts to parse the result as JSON\n * 4. Updates the configuration object with the final value\n *\n * @param value - The string value containing environment variable references.\n * @param meta - Metadata about the value's location in the configuration object.\n * @returns A promise that resolves when the transformation is complete.\n *\n * @example\n * ```typescript\n * // If process.env.DATABASE_URL = \"postgres://localhost/db\"\n * // Value: \"${env:DATABASE_URL}\"\n * // Result: \"postgres://localhost/db\"\n *\n * // If process.env.PORT = \"3000\"\n * // Value: \"${env:PORT}\"\n * // Result: 3000 (parsed as JSON number)\n * ```\n */\n async parse(value: string, meta: ObjectVisitorMeta): Promise<void> {\n const matches = value.matchAll(this.prefix);\n\n let result = value;\n for (const [found, key] of matches) {\n result = result.replaceAll(found, process.env[key!] ?? '');\n }\n\n if (meta.arrayIndex !== undefined && Array.isArray(meta.owner)) {\n meta.owner[meta.arrayIndex] = tryParseJson(result ?? '');\n } else {\n (meta.owner as Record<string, unknown>)[meta.propertyPath] = tryParseJson(result ?? '');\n }\n }\n}\n","import { Injectable } from 'injectkit';\nimport { AppConfigProvider } from '../app.config.provider.js';\nimport { ObjectVisitorMeta } from '../object.visitor.js';\nimport { SecretManagerServiceClient } from '@google-cloud/secret-manager';\nimport { tryParseJson } from '../helpers.js';\n\n/**\n * Provider that resolves Google Cloud Platform Secret Manager references in configuration values.\n *\n * This provider matches string values using a regex pattern and replaces them with\n * secrets fetched from GCP Secret Manager. The default pattern matches `${gcp:SECRET_NAME}`\n * and extracts the secret name to look up in Secret Manager.\n *\n * After retrieval, the secret value is attempted to be parsed as JSON. If parsing succeeds,\n * the parsed value is used; otherwise, the string value is used.\n *\n * @remarks\n * This provider requires valid GCP credentials to be configured. It uses the\n * `@google-cloud/secret-manager` package and will use Application Default Credentials (ADC).\n *\n * @example\n * ```typescript\n * // With default pattern /\\$\\{gcp:(.+)\\}/g\n * // Value: \"${gcp:DATABASE_PASSWORD}\"\n * // Fetches: projects/{projectId}/secrets/DATABASE_PASSWORD/versions/latest\n *\n * const config = await new AppConfigBuilder()\n * .addSource(new AppConfigSourceJson('./config.json'))\n * .addProvider(new AppConfigProviderGcpSecrets('my-gcp-project'))\n * .build();\n * ```\n */\n@Injectable()\nexport class AppConfigProviderGcpSecrets implements AppConfigProvider {\n private readonly secretmanagerClient = new SecretManagerServiceClient();\n private readonly prefix: RegExp;\n\n /**\n * Creates a new AppConfigProviderGcpSecrets instance.\n *\n * @param projectId - The GCP project ID where secrets are stored.\n * @param prefix - A regex pattern or string to match secret references.\n * If a string is provided, it will be converted to a RegExp. The regex must have\n * at least one capture group that extracts the secret name.\n * Defaults to `/\\$\\{gcp:(.+)\\}/g` which matches `${gcp:SECRET_NAME}` patterns.\n *\n * @example\n * ```typescript\n * // Default pattern\n * const provider1 = new AppConfigProviderGcpSecrets('my-project');\n *\n * // Custom regex pattern\n * const provider2 = new AppConfigProviderGcpSecrets('my-project', /\\$\\{secret:([^}]+)\\}/g);\n * ```\n */\n constructor(\n private readonly projectId: string,\n prefix: string | RegExp = /\\$\\{gcp:(.+)\\}/g,\n ) {\n this.prefix = typeof prefix === 'string' ? new RegExp(prefix) : prefix;\n }\n\n /**\n * Checks if this provider can parse the given value.\n *\n * @param value - The string value to check.\n * @returns `true` if the value matches the provider's regex pattern, `false` otherwise.\n */\n canParse(value: string): boolean {\n return this.prefix.test(value);\n }\n\n /**\n * Fetches a secret from GCP Secret Manager.\n *\n * @param secretId - The name of the secret to fetch.\n * @returns A promise that resolves to the secret value, or an empty string if the secret\n * couldn't be fetched.\n * @internal\n */\n private async getSecret(secretId: string): Promise<string> {\n try {\n const [secret] = await this.secretmanagerClient.accessSecretVersion({\n name: `projects/${this.projectId}/secrets/${secretId}/versions/latest`,\n });\n return secret.payload?.data?.toString() ?? '';\n } catch (error) {\n console.error(error);\n return '';\n }\n }\n\n /**\n * Parses the value by replacing GCP secret references with actual secret values.\n *\n * The method:\n * 1. Finds all matches of the regex pattern in the value\n * 2. Fetches each secret from GCP Secret Manager in parallel\n * 3. Attempts to parse each result as JSON\n * 4. Updates the configuration object with the final value\n *\n * @param value - The string value containing GCP secret references.\n * @param meta - Metadata about the value's location in the configuration object.\n * @returns A promise that resolves when all secrets have been fetched and the\n * transformation is complete.\n *\n * @example\n * ```typescript\n * // If GCP secret \"API_KEY\" contains \"sk-abc123\"\n * // Value: \"${gcp:API_KEY}\"\n * // Result: \"sk-abc123\"\n *\n * // If GCP secret \"CONFIG\" contains '{\"retries\": 3}'\n * // Value: \"${gcp:CONFIG}\"\n * // Result: { retries: 3 } (parsed as JSON object)\n * ```\n */\n async parse(value: string, meta: ObjectVisitorMeta): Promise<void> {\n const tasks: Promise<void>[] = [];\n const matches = value.matchAll(this.prefix);\n\n for (const [, key] of matches) {\n const task = this.getSecret(key!).then(value => {\n if (meta.arrayIndex !== undefined && Array.isArray(meta.owner)) {\n meta.owner[meta.arrayIndex] = tryParseJson(value);\n } else {\n (meta.owner as Record<string, unknown>)[meta.propertyPath] = tryParseJson(value);\n }\n });\n tasks.push(task);\n }\n\n await Promise.all(tasks);\n }\n}\n"],"mappings":";;;;AAeO,IAAMA,YAAN,MAAMA;EAfb,OAeaA;;;;;;;;;EAMX,YAA6BC,QAAW;SAAXA,SAAAA;EAAY;;;;;;;;;;;;;;EAezCC,IAAIC,KAA0B;AAC5B,WAAO,KAAKF,OAAOE,GAAAA;EACrB;;;;;;;;;;;;;;;;;;;;;;EAuBAC,MAASD,KAAiB;AACxB,WAAO,KAAKF,OAAOE,GAAAA;EACrB;;;;;;;;;;;;;;;;;;EAmBAE,UAAUF,KAAsB;AAC9B,WAAOG,OAAO,KAAKJ,IAAIC,GAAAA,CAAAA;EACzB;;;;;;;;;;;;;;;;;;;EAoBAI,UAAUJ,KAAsB;AAC9B,WAAOK,OAAO,KAAKP,OAAOE,GAAAA,CAAI;EAChC;;;;;;;;;;;;;;;;;;;EAoBAM,WAAWN,KAAuB;AAChC,WAAOO,QAAQ,KAAKT,OAAOE,GAAAA,CAAI;EACjC;;;;;;;;;;;;;;;;;;;EAoBAQ,UAAUR,KAAsB;AAC9B,WAAO,KAAKF,OAAOE,GAAAA;EACrB;AACF;;;ACvJA,SAASS,iBAAiB;;;ACoDnB,IAAMC,gBAAgB,wBAACC,KAAcC,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AA,IAAUA;EAClE;;;;;;;EAQAG,SAASC,OAAwB;AAC/B,WAAO,KAAKJ,OAAOK,KAAKD,KAAAA;EAC1B;;;;;;;;;EAUA,MAAcE,UAAUC,UAAmC;AACzD,QAAI;AACF,YAAM,CAACC,MAAAA,IAAU,MAAM,KAAKV,oBAAoBW,oBAAoB;QAClEC,MAAM,YAAY,KAAKT,SAAS,YAAYM,QAAAA;MAC9C,CAAA;AACA,aAAOC,OAAOG,SAASC,MAAMC,SAAAA,KAAc;IAC7C,SAASC,OAAO;AACdC,cAAQD,MAAMA,KAAAA;AACd,aAAO;IACT;EACF;;;;;;;;;;;;;;;;;;;;;;;;;;EA2BA,MAAME,MAAMZ,OAAea,MAAwC;AACjE,UAAMC,QAAyB,CAAA;AAC/B,UAAMC,UAAUf,MAAMgB,SAAS,KAAKpB,MAAM;AAE1C,eAAW,CAAA,EAAGqB,GAAAA,KAAQF,SAAS;AAC7B,YAAMG,OAAO,KAAKhB,UAAUe,GAAAA,EAAME,KAAKnB,CAAAA,WAAAA;AACrC,YAAIa,KAAKO,eAAeC,UAAaC,MAAMC,QAAQV,KAAKW,KAAK,GAAG;AAC9DX,eAAKW,MAAMX,KAAKO,UAAU,IAAIK,aAAazB,MAAAA;QAC7C,OAAO;AACJa,eAAKW,MAAkCX,KAAKa,YAAY,IAAID,aAAazB,MAAAA;QAC5E;MACF,CAAA;AACAc,YAAMa,KAAKT,IAAAA;IACb;AAEA,UAAMU,QAAQC,IAAIf,KAAAA;EACpB;AACF;;;;;;;;;","names":["AppConfig","config","get","key","getAs","getString","String","getNumber","Number","getBoolean","Boolean","getObject","deepmerge","objectVisitor","obj","callback","visit","path","owner","propertyPath","arrayIndex","Array","isArray","forEach","item","index","entries","Object","entry","length","propertyType","AppConfigBuilder","sources","providers","addSource","source","push","addProvider","provider","build","sourceTasks","Promise","all","map","x","load","mergedConfig","deepmerge","tasks","parse","value","meta","find","canParse","objectVisitor","AppConfig","tryParseJson","text","JSON","parse","_","value","nestKeys","record","separator","result","key","Object","entries","parts","split","length","current","i","part","dotenv","AppConfigSourceDotenv","filePath","options","load","result","dotenv","config","path","quiet","error","parsed","groupSeparator","nestKeys","existsSync","readFile","AppConfigSourceJson","options","filePath","ignoreMissingFile","encoding","load","existsSync","file","readFile","JSON","parse","toString","existsSync","readFile","YAML","AppConfigSourceYaml","options","filePath","ignoreMissingFile","encoding","load","existsSync","file","readFile","YAML","parse","toString","AppConfigProviderDotenv","prefix","RegExp","canParse","value","lastIndex","test","parse","meta","matches","matchAll","result","found","key","replaceAll","process","env","arrayIndex","undefined","Array","isArray","owner","tryParseJson","propertyPath","Injectable","SecretManagerServiceClient","AppConfigProviderGcpSecrets","secretmanagerClient","SecretManagerServiceClient","prefix","projectId","RegExp","canParse","value","test","getSecret","secretId","secret","accessSecretVersion","name","payload","data","toString","error","console","parse","meta","tasks","matches","matchAll","key","task","then","arrayIndex","undefined","Array","isArray","owner","tryParseJson","propertyPath","push","Promise","all"]}
|
|
@@ -1,4 +1,28 @@
|
|
|
1
1
|
import { AppConfigSource } from '../app.config.source.js';
|
|
2
|
+
/**
|
|
3
|
+
* Options for {@link AppConfigSourceDotenv}.
|
|
4
|
+
*/
|
|
5
|
+
export interface AppConfigSourceDotenvOptions {
|
|
6
|
+
/**
|
|
7
|
+
* When set, keys containing this separator are split into nested objects.
|
|
8
|
+
*
|
|
9
|
+
* For example, with `groupSeparator: '__'` the key `WEBHOOK__secret` becomes
|
|
10
|
+
* `{ WEBHOOK: { secret: '...' } }`. Supports arbitrary nesting depth.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```typescript
|
|
14
|
+
* // .env
|
|
15
|
+
* // WEBHOOK__secret=abc
|
|
16
|
+
* // WEBHOOK__header=X-Sig
|
|
17
|
+
* // DATABASE_URL=postgres://localhost/db
|
|
18
|
+
*
|
|
19
|
+
* const source = new AppConfigSourceDotenv('./.env', { groupSeparator: '__' });
|
|
20
|
+
* await source.load();
|
|
21
|
+
* // → { WEBHOOK: { secret: 'abc', header: 'X-Sig' }, DATABASE_URL: 'postgres://localhost/db' }
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
groupSeparator?: string;
|
|
25
|
+
}
|
|
2
26
|
/**
|
|
3
27
|
* Configuration source that loads environment variables from a `.env` file.
|
|
4
28
|
*
|
|
@@ -6,6 +30,10 @@ import { AppConfigSource } from '../app.config.source.js';
|
|
|
6
30
|
* If no file path is provided, it will look for a `.env` file in the current working directory.
|
|
7
31
|
* All values are strings as provided by the environment file.
|
|
8
32
|
*
|
|
33
|
+
* When the `groupSeparator` option is set, keys that contain the separator are automatically
|
|
34
|
+
* collapsed into nested objects. This is useful for grouping related env vars under a shared
|
|
35
|
+
* prefix (e.g. `WEBHOOK__secret` and `WEBHOOK__header` → `{ WEBHOOK: { secret, header } }`).
|
|
36
|
+
*
|
|
9
37
|
* @example
|
|
10
38
|
* ```typescript
|
|
11
39
|
* // Load from default .env file
|
|
@@ -15,22 +43,29 @@ import { AppConfigSource } from '../app.config.source.js';
|
|
|
15
43
|
* // Load from custom path
|
|
16
44
|
* const source2 = new AppConfigSourceDotenv('./config/.env.local');
|
|
17
45
|
* const config2 = await source2.load();
|
|
46
|
+
*
|
|
47
|
+
* // Group keys with __ separator into nested objects
|
|
48
|
+
* const source3 = new AppConfigSourceDotenv('./.env', { groupSeparator: '__' });
|
|
49
|
+
* const config3 = await source3.load();
|
|
18
50
|
* ```
|
|
19
51
|
*/
|
|
20
52
|
export declare class AppConfigSourceDotenv implements AppConfigSource {
|
|
21
53
|
private readonly filePath?;
|
|
54
|
+
private readonly options?;
|
|
22
55
|
/**
|
|
23
56
|
* Creates a new AppConfigSourceDotenv instance.
|
|
24
57
|
*
|
|
25
58
|
* @param filePath - Optional path to the `.env` file. If not provided, `dotenv` will
|
|
26
59
|
* look for a `.env` file in the current working directory.
|
|
60
|
+
* @param options - Optional configuration options.
|
|
27
61
|
*/
|
|
28
|
-
constructor(filePath?: string | undefined);
|
|
62
|
+
constructor(filePath?: string | undefined, options?: AppConfigSourceDotenvOptions | undefined);
|
|
29
63
|
/**
|
|
30
64
|
* Loads environment variables from the `.env` file.
|
|
31
65
|
*
|
|
32
66
|
* Uses `dotenv.config()` to parse the file and load variables into the returned object.
|
|
33
|
-
* If
|
|
67
|
+
* If `options.groupSeparator` is set the flat keys are transformed into a nested object
|
|
68
|
+
* before being returned.
|
|
34
69
|
*
|
|
35
70
|
* @returns A promise that resolves to an object containing the parsed environment variables.
|
|
36
71
|
* @throws {Error} If there's an error reading or parsing the `.env` file.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app.config.source.dotenv.d.ts","sourceRoot":"","sources":["../../src/sources/app.config.source.dotenv.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;
|
|
1
|
+
{"version":3,"file":"app.config.source.dotenv.d.ts","sourceRoot":"","sources":["../../src/sources/app.config.source.dotenv.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAI1D;;GAEG;AACH,MAAM,WAAW,4BAA4B;IAC3C;;;;;;;;;;;;;;;;;OAiBG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,qBAAa,qBAAsB,YAAW,eAAe;IASzD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAC;IAC1B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC;IAT3B;;;;;;OAMG;gBAEgB,QAAQ,CAAC,EAAE,MAAM,YAAA,EACjB,OAAO,CAAC,EAAE,4BAA4B,YAAA;IAGzD;;;;;;;;;OASG;IACG,IAAI,IAAI,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAa/C"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maroonedsoftware/appconfig",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.0",
|
|
4
4
|
"description": "A flexible, type-safe configuration management library with support for multiple sources and value transformation.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Marooned Software",
|
|
@@ -36,9 +36,9 @@
|
|
|
36
36
|
},
|
|
37
37
|
"devDependencies": {
|
|
38
38
|
"@google-cloud/secret-manager": "^6.1.1",
|
|
39
|
-
"yaml": "^2.8.
|
|
40
|
-
"@repo/config-
|
|
41
|
-
"@repo/config-
|
|
39
|
+
"yaml": "^2.8.3",
|
|
40
|
+
"@repo/config-eslint": "0.2.0",
|
|
41
|
+
"@repo/config-typescript": "0.1.0"
|
|
42
42
|
},
|
|
43
43
|
"peerDependencies": {
|
|
44
44
|
"@google-cloud/secret-manager": "^6.1.1",
|