nestjs-config-extended 1.2.7 → 2.0.0-next.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +255 -48
  2. package/dist/config-namespace.d.ts +2 -0
  3. package/dist/config-namespace.js +9 -0
  4. package/dist/config.constants.d.ts +7 -0
  5. package/dist/config.constants.js +8 -1
  6. package/dist/exceptions/extended-config-exception.d.ts +9 -0
  7. package/dist/exceptions/extended-config-exception.js +21 -0
  8. package/dist/exceptions/index.d.ts +5 -0
  9. package/dist/exceptions/index.js +10 -1
  10. package/dist/exceptions/invalid-loader-exception.d.ts +3 -2
  11. package/dist/exceptions/invalid-loader-exception.js +4 -3
  12. package/dist/exceptions/invalid-reload-interval-exception.d.ts +4 -0
  13. package/dist/exceptions/invalid-reload-interval-exception.js +11 -0
  14. package/dist/exceptions/invalid-schedule-exception.d.ts +3 -2
  15. package/dist/exceptions/invalid-schedule-exception.js +4 -3
  16. package/dist/exceptions/invalid-transformer-exception.d.ts +3 -2
  17. package/dist/exceptions/invalid-transformer-exception.js +4 -3
  18. package/dist/exceptions/invalid-validator-exception.d.ts +3 -2
  19. package/dist/exceptions/invalid-validator-exception.js +4 -3
  20. package/dist/exceptions/loading-exception.d.ts +3 -2
  21. package/dist/exceptions/loading-exception.js +4 -3
  22. package/dist/exceptions/missing-config-exception.d.ts +5 -0
  23. package/dist/exceptions/missing-config-exception.js +11 -0
  24. package/dist/exceptions/process-env-assignment-exception.d.ts +4 -0
  25. package/dist/exceptions/process-env-assignment-exception.js +11 -0
  26. package/dist/exceptions/schema-validation-exception.d.ts +6 -0
  27. package/dist/exceptions/schema-validation-exception.js +23 -0
  28. package/dist/exceptions/transformation-exception.d.ts +3 -2
  29. package/dist/exceptions/transformation-exception.js +4 -3
  30. package/dist/exceptions/validation-exception.d.ts +3 -2
  31. package/dist/exceptions/validation-exception.js +4 -3
  32. package/dist/extended-config.health.d.ts +13 -0
  33. package/dist/extended-config.health.js +50 -0
  34. package/dist/extended-config.module.d.ts +3 -0
  35. package/dist/extended-config.module.js +57 -28
  36. package/dist/extended-config.service.d.ts +41 -18
  37. package/dist/extended-config.service.js +324 -139
  38. package/dist/index.d.ts +3 -0
  39. package/dist/index.js +11 -1
  40. package/dist/interfaces/config-change-event.interface.d.ts +5 -0
  41. package/dist/interfaces/config-change-event.interface.js +2 -0
  42. package/dist/interfaces/config-loader-strategy.interface.d.ts +16 -7
  43. package/dist/interfaces/config-module-options.interface.d.ts +7 -2
  44. package/dist/interfaces/config-path.interface.d.ts +9 -0
  45. package/dist/interfaces/config-path.interface.js +2 -0
  46. package/dist/interfaces/config-status.interface.d.ts +13 -0
  47. package/dist/interfaces/config-status.interface.js +2 -0
  48. package/dist/interfaces/cron-scheduler.interface.d.ts +10 -0
  49. package/dist/interfaces/cron-scheduler.interface.js +2 -0
  50. package/dist/interfaces/index.d.ts +6 -0
  51. package/dist/interfaces/index.js +11 -1
  52. package/dist/interfaces/redact-options.interface.d.ts +4 -0
  53. package/dist/interfaces/redact-options.interface.js +2 -0
  54. package/dist/interfaces/standard-schema.interface.d.ts +33 -0
  55. package/dist/interfaces/standard-schema.interface.js +2 -0
  56. package/dist/strategies/dotEnv/dot-env.strategy.d.ts +1 -1
  57. package/dist/strategies/dotEnv/dot-env.strategy.js +36 -18
  58. package/dist/strategies/dotEnv/index.js +5 -1
  59. package/dist/strategies/file/file.interface.d.ts +5 -0
  60. package/dist/strategies/file/file.interface.js +2 -0
  61. package/dist/strategies/file/index.d.ts +3 -0
  62. package/dist/strategies/file/index.js +19 -0
  63. package/dist/strategies/file/json-file.strategy.d.ts +2 -0
  64. package/dist/strategies/file/json-file.strategy.js +6 -0
  65. package/dist/strategies/file/read-config-file.util.d.ts +2 -0
  66. package/dist/strategies/file/read-config-file.util.js +60 -0
  67. package/dist/strategies/file/yaml-file.strategy.d.ts +2 -0
  68. package/dist/strategies/file/yaml-file.strategy.js +17 -0
  69. package/dist/strategies/index.d.ts +1 -0
  70. package/dist/strategies/index.js +6 -1
  71. package/dist/util/clone.util.d.ts +1 -0
  72. package/dist/util/clone.util.js +24 -0
  73. package/dist/util/config-proxy.util.d.ts +1 -0
  74. package/dist/util/config-proxy.util.js +35 -0
  75. package/dist/util/deep-equal.util.d.ts +1 -0
  76. package/dist/util/deep-equal.util.js +26 -0
  77. package/dist/util/duration.util.d.ts +1 -0
  78. package/dist/util/duration.util.js +22 -0
  79. package/dist/util/identifier.util.d.ts +1 -0
  80. package/dist/util/identifier.util.js +6 -0
  81. package/dist/util/is-undefined.util.js +1 -2
  82. package/dist/util/loader.util.d.ts +4 -3
  83. package/dist/util/loader.util.js +67 -27
  84. package/dist/util/object.util.js +9 -4
  85. package/dist/util/redact.util.d.ts +4 -0
  86. package/dist/util/redact.util.js +47 -0
  87. package/index.d.mts +1 -0
  88. package/index.mjs +4 -0
  89. package/llms.txt +102 -0
  90. package/package.json +114 -45
  91. package/index.d.ts +0 -1
  92. package/index.js +0 -6
  93. package/logo.png +0 -0
  94. package/sonar-project.properties +0 -18
package/README.md CHANGED
@@ -3,33 +3,60 @@
3
3
  </p>
4
4
 
5
5
  <p align="center">
6
- Extended Configuration Module for Nest to load environment variables package.
6
+ Load, validate, reload and inject configuration in NestJS from any source.
7
7
  </p>
8
8
 
9
- <div>
10
- <img src="https://img.shields.io/github/package-json/v/pedrosodre/nestjs-config-extended" alt="Module Version" />
11
- <img src="https://sonarcloud.io/api/project_badges/measure?project=nestjs-config-extended&metric=alert_status" alt="SonarCloud Alert Status">
12
- <img src="https://sonarcloud.io/api/project_badges/measure?project=nestjs-config-extended&metric=security_rating" alt="SonarCloud Security Rating">
13
- <img src="https://sonarcloud.io/api/project_badges/measure?project=nestjs-config-extended&metric=coverage" alt="SonarCloud Coverage">
14
- <img src="https://sonarcloud.io/api/project_badges/measure?project=nestjs-config-extended&metric=bugs" alt="SonarCloud Bugs">
15
- <img src="https://img.shields.io/github/license/pedrosodre/nestjs-config-extended" alt="License" />
16
- <img src="https://img.shields.io/github/issues-raw/pedrosodre/nestjs-config-extended" alt="Issues" />
17
- <img src="https://img.shields.io/github/last-commit/pedrosodre/nestjs-config-extended" alt="GitHub Last Commit" />
18
- </div>
19
- <br />
20
-
21
- > :warning: **Attention:** For NestJS v7, this library will maintain `0.x` version in maintenance mode only. The `1.x` version supports NestJS v8 or later.
9
+ <p align="center">
10
+ <a href="https://www.npmjs.com/package/nestjs-config-extended"><img src="https://img.shields.io/npm/v/nestjs-config-extended" alt="npm version" /></a>
11
+ <a href="https://www.npmjs.com/package/nestjs-config-extended"><img src="https://img.shields.io/npm/dm/nestjs-config-extended" alt="npm downloads" /></a>
12
+ <a href="https://github.com/pedrosodre/nestjs-config-extended/actions/workflows/release.yml"><img src="https://github.com/pedrosodre/nestjs-config-extended/actions/workflows/release.yml/badge.svg?branch=master" alt="CI and release" /></a>
13
+ <a href="LICENSE"><img src="https://img.shields.io/npm/l/nestjs-config-extended" alt="License" /></a>
14
+ </p>
22
15
 
23
16
  ## Description
24
17
 
25
- Extended Configuration Module for [Nest](https://github.com/nestjs/nest) based on the [Nest's Configuration Module](https://docs.nestjs.com/techniques/configuration) to load environment variables.
18
+ Extended configuration module for [NestJS](https://nestjs.com), inspired by [Nest's configuration module](https://docs.nestjs.com/techniques/configuration). It combines configuration from several **strategies** (environment variables, `.env`, JSON and YAML files, or your own loaders such as a secrets manager) and adds:
19
+
20
+ - **Validation** with any [Standard Schema](https://standardschema.dev) library (Zod, Valibot, ArkType, ...) and **typed access** with autocompleted dotted paths.
21
+ - **Reloading** on demand, on a cron schedule or at an interval, with retries, and **change notifications** through RxJS observables and hooks.
22
+ - **Injectable namespaces** with `@InjectConfig()`, which always reflect the latest values.
23
+ - **Safe printing**: secrets are masked when the configuration is logged.
24
+ - **Health checks** for `@nestjs/terminus`.
25
+ - CommonJS and ESM support.
26
+
27
+ ## Contents
28
+
29
+ - [Compatibility](#compatibility)
30
+ - [Installation](#installation)
31
+ - [Getting started](#getting-started)
32
+ - [Module configuration](#module-configuration) · [Strategies](#strategies) · [Pre-made loaders](#pre-made-loaders) · [Schema validation](#schema-validation)
33
+ - [Using the `ExtendedConfigService`](#using-the-extendedconfigservice)
34
+ - [Printing configuration safely](#printing-configuration-safely) · [Injecting namespaces](#injecting-configuration-namespaces) · [Reacting to changes](#reacting-to-changes) · [Health checks](#health-checks) · [Typed configuration](#typed-configuration)
35
+ - [Full example](#full-example)
36
+ - [Contributing](#contributing)
37
+
38
+ ## Compatibility
39
+
40
+ | nestjs-config-extended | NestJS | Node.js | TypeScript |
41
+ | ---------------------- | -------- | ------- | ---------- |
42
+ | 2.x | 11, 12 | 22.12+ | 5.4+ |
43
+ | 1.x | 8, 9, 10 | - | - |
44
+ | 0.x | 7 | - | - |
45
+
46
+ NestJS 12 is ESM-only. This package works with it from both CommonJS and ESM applications, relying on `require()` of ES modules, which Node.js supports without a flag since 22.12.
47
+
48
+ Upgrading from 1.x? Read the [migration guide](MIGRATION.md).
26
49
 
27
50
  ## Installation
28
51
 
29
- To begin using it, we first install the module itself.
52
+ ```bash
53
+ npm install nestjs-config-extended
54
+ ```
55
+
56
+ To use `yamlFileLoader`, also install the optional [`yaml`](https://www.npmjs.com/package/yaml) package:
30
57
 
31
58
  ```bash
32
- $ npm i --save nestjs-config-extended
59
+ npm install yaml
33
60
  ```
34
61
 
35
62
  ## Getting started
@@ -68,44 +95,89 @@ If needed, you can also initialize `ExtendedConfigModule` using `.forRootAsync()
68
95
 
69
96
  To customize module's configuration, you can setup few options by importing it using one of `.forRoot()` or `.forRootAsync()` method.
70
97
 
71
- | Option | Default value | Required | Type | Description |
72
- | ------------ | ------------- | -------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
73
- | `strategies` | `[]` | `false` | `ConfigLoaderStrategy[]` | Array with all strategies used to load configuration variables. |
74
- | `cache` | `true` | `false` | `boolean` | If `false`, values will be stored directly in process.env object. <br> If `true`, values will be stored only in the memory. |
75
- | `debug` | `false` | `false` | `boolean` | If `true`, module will log some internal process information. |
76
- | `isGlobal` | `false` | `false` | `boolean` | If `true`, registers `ExtendedConfigModule` as a global module. |
77
- | `preload` | `false` | `false` | `boolean` | If `true`, variables load will be done by the module and injected on service. This option is required if you need to inject the service on a custom provider and retrieve a variable before application is totally ready. |
98
+ | Option | Default value | Required | Type | Description |
99
+ | --------------- | ------------- | -------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
100
+ | `strategies` | `[]` | `false` | `ConfigLoaderStrategy[]` | Array with all strategies used to load configuration variables. |
101
+ | `cache` | `true` | `false` | `boolean` | If `false`, values will be stored directly in process.env object (as strings, under their literal key; object values and `registerAs` are not supported). <br> If `true`, values will be stored only in the memory. |
102
+ | `debug` | `false` | `false` | `boolean` | If `true`, module will log some internal process information. |
103
+ | `isGlobal` | `false` | `false` | `boolean` | If `true`, registers `ExtendedConfigModule` as a global module. |
104
+ | `preload` | `false` | `false` | `boolean` | If `true`, variables load will be done by the module and injected on service. This option is required if you need to inject the service on a custom provider and retrieve a variable before application is totally ready. |
105
+ | `redact` | defaults | `false` | `RedactOptions \| false` | How `toJSON()` and `console.log(service)` mask sensitive values: `{ keys?: (string \| RegExp)[], replacement?: string }`. `false` disables masking. |
106
+ | `onChange` | - | `false` | `(event: ConfigChangeEvent) => void \| Promise<void>` | Called after a load or reload changes at least one top-level key. Errors are logged and never break loading. |
107
+ | `onReloadError` | - | `false` | `(error: Error, identifier?) => void \| Promise<void>` | Called when a scheduled reload or `reload()` fails. Previously loaded values are kept. |
78
108
 
79
109
  ### Strategies
80
110
 
81
111
  To keep everything as flexible as possible, `ExtendedConfigModule` works with an array of strategies, that are specialized objects in load environment variables. Each strategy has its own options, as described below:
82
112
 
83
- | Option | Default value | Required | Type | Description |
84
- | ------------------ | ------------- | -------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
85
- | `loader` | - | `true` | `LoaderClass | LoaderMethod` | Class or function responsible for loading environment variables for this strategy. Accepts a custom function or class with load() method. |
86
- | `identifier` | - | `false` | `string | Symbol` | Identify a strategy to allow module to manipulate it directly on helper functions. |
87
- | `disable` | `false` | `false` | `boolean` | If `true`, this strategy will not used. This flag is useful to perform conditional strategy disabling. |
88
- | `options` | - | `false` | `Record<string, any>` | Set options to loader class or function. |
89
- | `reloadable` | `false` | `false` | `boolean` | If `false`, this strategy will not be called again when service or scheduler requests a reload. |
90
- | `schedule` | - | `false` | `string` | Schedules the strategy reload (if reloadable) using cron syntax. This feature may not work correctly with serverless functions. |
91
- | `scheduleTimezone` | - | `false` | `Timezone` | Set scheduler timezone. |
92
- | `registerAs` | - | `false` | `string` | If set, all configuration will be set under the key passed on this variable. |
93
- | `transformer` | - | `false` | `TransformerClass | TransformerMethod` | If you wish to transform the loaded configuration variables, you can pass a function to handle it. Accepts a function or a class with transform() method. |
94
- | `validator` | - | `false` | `ValidatorClass | ValidatorMethod` | If you wish to transform the loaded configuration variables, you can pass a function to handle it. Accepts a function or a class with validate() method. |
113
+ | Option | Default value | Required | Type | Description |
114
+ | ------------------ | ------------- | -------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
115
+ | `loader` | - | `true` | `LoaderClass \| LoaderMethod` | Class or function responsible for loading environment variables for this strategy. Accepts a custom function or class with `load()` method. |
116
+ | `identifier` | - | `false` | `string \| Symbol` | Identify a strategy to allow module to manipulate it directly on helper functions. |
117
+ | `disable` | `false` | `false` | `boolean` | If `true`, this strategy will not be used. Useful to perform conditional strategy disabling. |
118
+ | `options` | - | `false` | `Record<string, any>` | Options passed to the loader class or function. |
119
+ | `reloadable` | `false` | `false` | `boolean` | If `false`, this strategy will not be called again when service, scheduler or interval requests a reload. |
120
+ | `schedule` | - | `false` | `string` | Schedules the strategy reload (if reloadable) using cron syntax. This feature may not work correctly with serverless functions. |
121
+ | `scheduleTimezone` | - | `false` | `string` | Scheduler timezone as an IANA name, e.g. `America/Sao_Paulo`. |
122
+ | `reloadInterval` | - | `false` | `number \| string` | Reloads the strategy (if reloadable) at a fixed interval, as an alternative to `schedule`. Milliseconds or a string like `'30s'`, `'5m'`, `'1h'`. |
123
+ | `retry` | - | `false` | `RetryOptions` | Retries a failing loader with exponential backoff: `{ retries, delay = 1000, factor = 2, maxDelay = 30000 }`. Applies to the first load and to reloads. |
124
+ | `registerAs` | - | `false` | `string` | If set, all configuration will be set under the key passed on this variable. |
125
+ | `transformer` | - | `false` | `TransformerClass \| TransformerMethod` | Transforms the loaded variables. Accepts a function or a class with `transform()` method. |
126
+ | `validator` | - | `false` | `ValidatorClass \| ValidatorMethod` | Validates the loaded variables. Accepts a function or a class with `validate()` method. |
127
+ | `schema` | - | `false` | `StandardSchemaV1` | [Standard Schema](https://standardschema.dev) (Zod, Valibot, ArkType, ...) that validates and parses the variables after the validator and transformer. Its output replaces the loaded variables. |
128
+
129
+ Reloads of the same strategy never overlap: a reload requested while another one is running for that strategy waits for it instead of calling the loader again. When a background reload (schedule or interval) fails, the error is logged, `onReloadError` is called and the previous values are kept.
95
130
 
96
131
  #### Pre-made loaders
97
132
 
98
- Based on key use cases, `ExtendedConfigModule` has two pre-made loaders. To use them you simply need to import and refer it on strategy's `loader` option.
133
+ Based on key use cases, `ExtendedConfigModule` has some pre-made loaders. To use them you simply need to import and refer it on strategy's `loader` option.
99
134
 
100
135
  - `processEnvLoader`: loads variables from node's `process.env`.
101
136
  - `dotEnvLoader`: loads variables from `.env` files, based on loader options. You can specify file(s) `path` and `encoding`, and enable `expandVariables`.
137
+ - `jsonFileLoader`: loads variables from a JSON file. Options: `path` (required, relative to `process.cwd()`), `encoding` and `optional` (a missing file loads nothing instead of failing; combined with `registerAs`, the key then holds an empty object).
138
+ - `yamlFileLoader`: loads variables from a YAML file, with the same options. Requires the optional [`yaml`](https://www.npmjs.com/package/yaml) package (`npm install yaml`).
139
+
140
+ ```typescript
141
+ ExtendedConfigModule.forRoot({
142
+ strategies: [
143
+ { loader: yamlFileLoader, options: { path: 'config/default.yaml' } },
144
+ {
145
+ loader: jsonFileLoader,
146
+ options: { path: 'config/local.json', optional: true },
147
+ },
148
+ ],
149
+ });
150
+ ```
151
+
152
+ #### Schema validation
153
+
154
+ Any [Standard Schema](https://standardschema.dev) compatible library (Zod 3.24+, Valibot 1+, ArkType 2+, ...) can validate and parse a strategy's variables. The parsed output (with coerced types and defaults) replaces the loaded variables, and `InferConfig` types the service from the schema:
155
+
156
+ ```typescript
157
+ import { z } from 'zod';
158
+ import { dotEnvLoader, ExtendedConfigService, InferConfig } from 'nestjs-config-extended';
159
+
160
+ export const envSchema = z.object({
161
+ PORT: z.coerce.number().default(3000),
162
+ DATABASE_URL: z.string().url(),
163
+ });
164
+
165
+ ExtendedConfigModule.forRoot({
166
+ strategies: [{ loader: dotEnvLoader, schema: envSchema }],
167
+ });
168
+
169
+ // inject a typed service
170
+ constructor(private config: ExtendedConfigService<InferConfig<typeof envSchema>>) {}
171
+ ```
172
+
173
+ When validation fails, loading throws a `SchemaValidationException` that lists every issue and exposes them on its `issues` property.
102
174
 
103
175
  ## Using the `ExtendedConfigService`
104
176
 
105
177
  To access the loaded configuration values from our `ExtendedConfigService`, we first need to inject `ExtendedConfigService`. As with any provider, we need to import its containing module - the `ExtendedConfigModule` - into the module that will use it (unless you set the `isGlobal` property in the options to true). Then we can inject it using standard constructor injection:
106
178
 
107
179
  ```typescript
108
- constructor(private extendedConfigService: ExtendedConfigModule) {}
180
+ constructor(private extendedConfigService: ExtendedConfigService) {}
109
181
  ```
110
182
 
111
183
  Once it's injected, you already can use the following service methods to work with environment variables.
@@ -121,25 +193,158 @@ await this.extendedConfigService.load(true);
121
193
  const dbUser = this.extendedConfigService.get<string>('DATABASE_USER');
122
194
 
123
195
  // get a proxy of an object from environment variable
124
- const appConfig = this.extendedConfigService.getProxyOf<
125
- Record<string, unknown>
126
- >('APP_CONFIG');
196
+ const appConfig =
197
+ this.extendedConfigService.getProxyOf<Record<string, unknown>>('APP_CONFIG');
198
+
199
+ // get a nested value using a dotted path
200
+ const dbHost = this.extendedConfigService.get('database.host');
201
+
202
+ // get a value or throw a MissingConfigException when it is not defined
203
+ const apiKey = this.extendedConfigService.getOrThrow<string>('API_KEY');
127
204
 
128
205
  // verify if an environment variable exists
129
206
  const hasPassword = this.extendedConfigService.has('DATABASE_USER');
130
207
 
131
208
  // reload environment variables on strategies that allows reload
209
+ // (every reloadable strategy is attempted; rejects with the first error)
132
210
  await this.extendedConfigService.reload();
133
211
 
134
212
  // reload environment variables for a specific strategy that allows reload
135
213
  await this.extendedConfigService.reload('STRATEGY_IDENTIFIER');
136
214
  ```
137
215
 
138
- > :warning: **Important:** `getProxyOf()` method only returns a proxy when returned value is an object, in any other cases, it will return the value directly. If you need a non-object value from the proxy, try encapsulate it with a transformer.
216
+ ### Printing configuration safely
217
+
218
+ `JSON.stringify(service)`, `service.toJSON()` and `console.log(service)` return the loaded configuration with sensitive values masked. Keys matching password, secret, token, api key, private key, credential, session, cookie, salt or signature are replaced with `[REDACTED]`, and passwords embedded in URLs (`postgres://user:[REDACTED]@host`) are removed. Add your own keys with the `redact` option, or use `redactConfig()` directly:
219
+
220
+ ```typescript
221
+ ExtendedConfigModule.forRoot({
222
+ strategies: [{ loader: processEnvLoader }],
223
+ redact: { keys: ['INTERNAL_ID', /^iban$/i] },
224
+ });
225
+
226
+ this.logger.log(`Config: ${JSON.stringify(this.config)}`);
227
+ ```
228
+
229
+ With `debug: true`, logs only list the loaded key names, never their values.
230
+
231
+ ### Injecting configuration namespaces
232
+
233
+ Register namespaces (a strategy's `registerAs` key or any object path) with `forFeature()` and inject them with `@InjectConfig()`. The root module must be global. The injection waits for the first load, so `preload` is not required, and the injected object is a read-only proxy that always reflects reloaded values:
234
+
235
+ ```typescript
236
+ @Module({
237
+ imports: [
238
+ ExtendedConfigModule.forRoot({
239
+ isGlobal: true,
240
+ strategies: [{ loader: databaseLoader, registerAs: 'database' }],
241
+ }),
242
+ DatabaseModule,
243
+ ],
244
+ })
245
+ export class AppModule {}
246
+
247
+ @Module({
248
+ imports: [ExtendedConfigModule.forFeature('database')],
249
+ providers: [DatabaseService],
250
+ })
251
+ export class DatabaseModule {}
252
+
253
+ @Injectable()
254
+ export class DatabaseService {
255
+ constructor(@InjectConfig('database') private readonly db: DatabaseConfig) {}
256
+ }
257
+ ```
258
+
259
+ `getConfigToken('database')` returns the injection token, for example to use it in other providers' `inject` arrays.
260
+
261
+ > **Note:** the first injection of a namespace triggers the first load while Nest creates providers, which is earlier than the module's `onModuleInit`. If a `forRootAsync()` loader is a provider that needs its own `onModuleInit` before it can load, make sure its dependencies are ready in its constructor or factory, or inject the namespace only in modules that are initialized after it.
262
+
263
+ ### Reacting to changes
264
+
265
+ Reloads (manual or scheduled) can change values while the application runs. `watch()` emits the current value of a key or dotted path and then every distinct change, and `changes()` emits an event with the top-level keys that changed:
266
+
267
+ ```typescript
268
+ // emits now and on every distinct change
269
+ this.config.watch('database.host').subscribe(host => this.reconnect(host));
270
+
271
+ // { reason: 'load' | 'reload', identifier, changedKeys: string[] }
272
+ this.config.changes().subscribe(event => this.logger.log(event.changedKeys));
273
+ ```
274
+
275
+ Both observables complete when the application shuts down. The same information is available through the `onChange` and `onReloadError` module options.
276
+
277
+ ### Health checks
278
+
279
+ `getStatus()` returns whether the configuration finished loading and, per strategy, the last success, last failure (with URL credentials masked) and consecutive failures. `ExtendedConfigHealthIndicator` turns that into a [`@nestjs/terminus`](https://docs.nestjs.com/recipes/terminus) (v11+) health indicator without depending on it. It reports `down` until the first load finishes and while a strategy's consecutive failures reach `maxConsecutiveFailures` (default `1`):
280
+
281
+ ```typescript
282
+ @Module({
283
+ imports: [TerminusModule],
284
+ controllers: [HealthController],
285
+ providers: [ExtendedConfigHealthIndicator], // root module must be global
286
+ })
287
+ export class HealthModule {}
288
+
289
+ @Controller('health')
290
+ export class HealthController {
291
+ constructor(
292
+ private health: HealthCheckService,
293
+ private configHealth: ExtendedConfigHealthIndicator,
294
+ ) {}
295
+
296
+ @Get()
297
+ @HealthCheck()
298
+ check() {
299
+ return this.health.check([
300
+ () =>
301
+ this.configHealth.isHealthy('config', { maxConsecutiveFailures: 3 }),
302
+ ]);
303
+ }
304
+ }
305
+ ```
306
+
307
+ ### Errors
308
+
309
+ Every error thrown by the module extends `ExtendedConfigException`, so one `instanceof` check catches them all. Errors have a specific `name` (`LoadingException`, `SchemaValidationException`, `MissingConfigException`, ...), the strategy's `identifier` when one is involved, and the original loader, validator or transformer error as `cause`:
310
+
311
+ ```typescript
312
+ try {
313
+ await this.config.reload('REMOTE');
314
+ } catch (error) {
315
+ if (error instanceof ExtendedConfigException) {
316
+ this.logger.error(
317
+ `${error.name} in ${String(error.identifier)}`,
318
+ error.cause,
319
+ );
320
+ }
321
+ }
322
+ ```
323
+
324
+ ### Typed configuration
325
+
326
+ Pass your configuration type to the service to get autocompleted dotted paths and inferred return types (up to 5 levels deep). With a [schema](#schema-validation), use `InferConfig<typeof schema>`.
327
+
328
+ ```typescript
329
+ interface AppConfig {
330
+ PORT: number;
331
+ database: { host: string; ssl?: boolean };
332
+ }
333
+
334
+ constructor(private config: ExtendedConfigService<AppConfig>) {}
335
+
336
+ const port = this.config.get('PORT'); // number | undefined
337
+ const host = this.config.getOrThrow('database.host'); // string
338
+ this.config.get('database.nope'); // compile error
339
+ ```
340
+
341
+ Untyped services keep accepting any string and explicit type arguments such as `get<string>('KEY')`.
342
+
343
+ > :warning: **Important:** `getProxyOf()` method only returns a proxy when returned value is an object, in any other cases, it will return the value directly. The proxy is read-only and supports property access, `in`, `Object.keys()`, spreading and `JSON.stringify()`.
139
344
 
140
345
  ## Full example
141
346
 
142
- The examples below uses all availables options to help you to understand the module, but some of them are conflicting.
347
+ The examples below use most of the available options to show how they fit together. Some of them conflict with each other, so do not copy them as-is.
143
348
 
144
349
  ### Using `.forRoot()`
145
350
 
@@ -234,12 +439,14 @@ import { ExtendedConfigModule, dotEnvLoader } from 'nestjs-config-extended';
234
439
  export class AppModule {}
235
440
  ```
236
441
 
237
- ## Stay in touch
442
+ ## Contributing
238
443
 
239
- - Author - [Pedro Sodré](https://github.com/pedrosodre)
444
+ Contributions are welcome! Read the [contributing guide](CONTRIBUTING.md) to get started, and please follow the [Code of Conduct](CODE_OF_CONDUCT.md). To report a security problem, see the [security policy](SECURITY.md).
240
445
 
241
- ## License
446
+ An API summary for AI coding assistants ships with the package as [`llms.txt`](llms.txt) (also at `node_modules/nestjs-config-extended/llms.txt`).
242
447
 
243
- This module is [MIT licensed](LICENSE).
448
+ Release notes are published on the [GitHub releases page](https://github.com/pedrosodre/nestjs-config-extended/releases).
449
+
450
+ ## License
244
451
 
245
- Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
452
+ [MIT](LICENSE) © [Pedro Sodré](https://github.com/pedrosodre)
@@ -0,0 +1,2 @@
1
+ export declare const getConfigToken: (namespace: string) => string;
2
+ export declare const InjectConfig: (namespace: string) => ParameterDecorator & PropertyDecorator;
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InjectConfig = exports.getConfigToken = void 0;
4
+ const common_1 = require("@nestjs/common");
5
+ const CONFIG_NAMESPACE_TOKEN_PREFIX = 'EXTENDED_CONFIG_NAMESPACE:';
6
+ const getConfigToken = (namespace) => `${CONFIG_NAMESPACE_TOKEN_PREFIX}${namespace}`;
7
+ exports.getConfigToken = getConfigToken;
8
+ const InjectConfig = (namespace) => (0, common_1.Inject)((0, exports.getConfigToken)(namespace));
9
+ exports.InjectConfig = InjectConfig;
@@ -19,3 +19,10 @@ export declare const STARTING_RELOAD = "Starting variables reload";
19
19
  export declare const ALL_STRATEGIES = "ALL";
20
20
  export declare const NOT_LOADED_STRATEGY_DISABLED = "Variables not loaded since strategy is disabled";
21
21
  export declare const DEBUG_LOG_PREFIX = "[Extended Config Module]";
22
+ export declare const SCHEDULED_RELOAD_FAILED = "Scheduled reload failed, keeping previously loaded variables";
23
+ export declare const PARSING_VARIABLES_WITH_SCHEMA = "Parsing variables with strategy's schema";
24
+ export declare const ON_CHANGE_HOOK_FAILED = "onChange hook failed";
25
+ export declare const ON_RELOAD_ERROR_HOOK_FAILED = "onReloadError hook failed";
26
+ export declare const RETRYING_LOADER = "Retrying strategy's loader";
27
+ export declare const RELOADING_VARIABLES_FROM_STRATEGY_BY_INTERVAL = "Reloading variables from strategy's loader by interval";
28
+ export declare const LOADED_KEYS = "Loaded keys";
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DEBUG_LOG_PREFIX = exports.NOT_LOADED_STRATEGY_DISABLED = exports.ALL_STRATEGIES = exports.STARTING_RELOAD = exports.ASSIGNING_VARIABLES_TO_CACHE = exports.ASSIGNING_VARIABLES_TO_PROCESS_ENV = exports.TRANSFORMING_VARIABLES_FROM_STRATEGY = exports.VALIDATING_VARIABLES_FROM_STRATEGY = exports.RELOADING_VARIABLES_FROM_STRATEGY_BY_SCHEDULER = exports.RELOADING_VARIABLES_FROM_STRATEGY = exports.LOADING_VARIABLES_FROM_STRATEGY = exports.STARTING_STRATEGY = exports.INVALID_VARIABLES = exports.LOAD_REQUEST_IGNORED_DUE_IN_PROGRESS = exports.LOAD_REQUEST_IGNORED_DUE_ALREADY_LOADED = exports.FIRST_LOAD_REQUESTED = exports.VARIABLES_PRELOADED_BY_MODULE = exports.NOT_IDENTIFIED = exports.PRE_LOADED_VALUES = exports.EXTENDED_CONFIG_OPTIONS = exports.CRON_SCHEDULER = void 0;
3
+ exports.LOADED_KEYS = exports.RELOADING_VARIABLES_FROM_STRATEGY_BY_INTERVAL = exports.RETRYING_LOADER = exports.ON_RELOAD_ERROR_HOOK_FAILED = exports.ON_CHANGE_HOOK_FAILED = exports.PARSING_VARIABLES_WITH_SCHEMA = exports.SCHEDULED_RELOAD_FAILED = exports.DEBUG_LOG_PREFIX = exports.NOT_LOADED_STRATEGY_DISABLED = exports.ALL_STRATEGIES = exports.STARTING_RELOAD = exports.ASSIGNING_VARIABLES_TO_CACHE = exports.ASSIGNING_VARIABLES_TO_PROCESS_ENV = exports.TRANSFORMING_VARIABLES_FROM_STRATEGY = exports.VALIDATING_VARIABLES_FROM_STRATEGY = exports.RELOADING_VARIABLES_FROM_STRATEGY_BY_SCHEDULER = exports.RELOADING_VARIABLES_FROM_STRATEGY = exports.LOADING_VARIABLES_FROM_STRATEGY = exports.STARTING_STRATEGY = exports.INVALID_VARIABLES = exports.LOAD_REQUEST_IGNORED_DUE_IN_PROGRESS = exports.LOAD_REQUEST_IGNORED_DUE_ALREADY_LOADED = exports.FIRST_LOAD_REQUESTED = exports.VARIABLES_PRELOADED_BY_MODULE = exports.NOT_IDENTIFIED = exports.PRE_LOADED_VALUES = exports.EXTENDED_CONFIG_OPTIONS = exports.CRON_SCHEDULER = void 0;
4
4
  exports.CRON_SCHEDULER = 'CRON_SCHEDULER';
5
5
  exports.EXTENDED_CONFIG_OPTIONS = 'EXTENDED_CONFIG_OPTIONS';
6
6
  exports.PRE_LOADED_VALUES = 'PRE_LOADED_VALUES';
@@ -22,3 +22,10 @@ exports.STARTING_RELOAD = 'Starting variables reload';
22
22
  exports.ALL_STRATEGIES = 'ALL';
23
23
  exports.NOT_LOADED_STRATEGY_DISABLED = 'Variables not loaded since strategy is disabled';
24
24
  exports.DEBUG_LOG_PREFIX = '[Extended Config Module]';
25
+ exports.SCHEDULED_RELOAD_FAILED = 'Scheduled reload failed, keeping previously loaded variables';
26
+ exports.PARSING_VARIABLES_WITH_SCHEMA = "Parsing variables with strategy's schema";
27
+ exports.ON_CHANGE_HOOK_FAILED = 'onChange hook failed';
28
+ exports.ON_RELOAD_ERROR_HOOK_FAILED = 'onReloadError hook failed';
29
+ exports.RETRYING_LOADER = "Retrying strategy's loader";
30
+ exports.RELOADING_VARIABLES_FROM_STRATEGY_BY_INTERVAL = "Reloading variables from strategy's loader by interval";
31
+ exports.LOADED_KEYS = 'Loaded keys';
@@ -0,0 +1,9 @@
1
+ export interface ExtendedConfigExceptionOptions {
2
+ cause?: unknown;
3
+ identifier?: string | symbol;
4
+ }
5
+ export declare abstract class ExtendedConfigException extends Error {
6
+ readonly cause?: unknown;
7
+ readonly identifier?: string | symbol;
8
+ protected constructor(message: string, options?: ExtendedConfigExceptionOptions);
9
+ }
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ExtendedConfigException = void 0;
4
+ class ExtendedConfigException extends Error {
5
+ constructor(message, options = {}) {
6
+ super(message);
7
+ this.name = new.target.name;
8
+ if (options.cause !== undefined) {
9
+ Object.defineProperty(this, 'cause', {
10
+ value: options.cause,
11
+ writable: true,
12
+ configurable: true,
13
+ enumerable: false,
14
+ });
15
+ }
16
+ if (options.identifier !== undefined) {
17
+ this.identifier = options.identifier;
18
+ }
19
+ }
20
+ }
21
+ exports.ExtendedConfigException = ExtendedConfigException;
@@ -1,3 +1,4 @@
1
+ export * from './extended-config-exception';
1
2
  export * from './invalid-loader-exception';
2
3
  export * from './invalid-transformer-exception';
3
4
  export * from './invalid-validator-exception';
@@ -5,3 +6,7 @@ export * from './invalid-schedule-exception';
5
6
  export * from './validation-exception';
6
7
  export * from './loading-exception';
7
8
  export * from './transformation-exception';
9
+ export * from './process-env-assignment-exception';
10
+ export * from './schema-validation-exception';
11
+ export * from './missing-config-exception';
12
+ export * from './invalid-reload-interval-exception';
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
3
  if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
5
9
  }) : (function(o, m, k, k2) {
6
10
  if (k2 === undefined) k2 = k;
7
11
  o[k2] = m[k];
@@ -10,6 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
15
  };
12
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./extended-config-exception"), exports);
13
18
  __exportStar(require("./invalid-loader-exception"), exports);
14
19
  __exportStar(require("./invalid-transformer-exception"), exports);
15
20
  __exportStar(require("./invalid-validator-exception"), exports);
@@ -17,3 +22,7 @@ __exportStar(require("./invalid-schedule-exception"), exports);
17
22
  __exportStar(require("./validation-exception"), exports);
18
23
  __exportStar(require("./loading-exception"), exports);
19
24
  __exportStar(require("./transformation-exception"), exports);
25
+ __exportStar(require("./process-env-assignment-exception"), exports);
26
+ __exportStar(require("./schema-validation-exception"), exports);
27
+ __exportStar(require("./missing-config-exception"), exports);
28
+ __exportStar(require("./invalid-reload-interval-exception"), exports);
@@ -1,3 +1,4 @@
1
- export declare class InvalidLoaderException extends Error {
2
- constructor(identifier?: string | Symbol);
1
+ import { ExtendedConfigException } from './extended-config-exception';
2
+ export declare class InvalidLoaderException extends ExtendedConfigException {
3
+ constructor(identifier?: string | symbol);
3
4
  }
@@ -1,10 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.InvalidLoaderException = void 0;
4
- const config_constants_1 = require("../config.constants");
5
- class InvalidLoaderException extends Error {
4
+ const extended_config_exception_1 = require("./extended-config-exception");
5
+ const identifier_util_1 = require("../util/identifier.util");
6
+ class InvalidLoaderException extends extended_config_exception_1.ExtendedConfigException {
6
7
  constructor(identifier) {
7
- super(`${identifier || config_constants_1.NOT_IDENTIFIED} strategy's loader is not an instance of LoaderMethod or LoaderClass`);
8
+ super(`${(0, identifier_util_1.formatIdentifier)(identifier)} strategy's loader is not an instance of LoaderMethod or LoaderClass`, { identifier });
8
9
  }
9
10
  }
10
11
  exports.InvalidLoaderException = InvalidLoaderException;
@@ -0,0 +1,4 @@
1
+ import { ExtendedConfigException } from './extended-config-exception';
2
+ export declare class InvalidReloadIntervalException extends ExtendedConfigException {
3
+ constructor(reason: string, identifier?: string | symbol);
4
+ }
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InvalidReloadIntervalException = void 0;
4
+ const extended_config_exception_1 = require("./extended-config-exception");
5
+ const identifier_util_1 = require("../util/identifier.util");
6
+ class InvalidReloadIntervalException extends extended_config_exception_1.ExtendedConfigException {
7
+ constructor(reason, identifier) {
8
+ super(`${(0, identifier_util_1.formatIdentifier)(identifier)} strategy's reload interval is invalid due "${reason}"`, { identifier });
9
+ }
10
+ }
11
+ exports.InvalidReloadIntervalException = InvalidReloadIntervalException;
@@ -1,3 +1,4 @@
1
- export declare class InvalidScheduleException extends Error {
2
- constructor(identifier?: string | Symbol);
1
+ import { ExtendedConfigException } from './extended-config-exception';
2
+ export declare class InvalidScheduleException extends ExtendedConfigException {
3
+ constructor(identifier?: string | symbol);
3
4
  }
@@ -1,10 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.InvalidScheduleException = void 0;
4
- const config_constants_1 = require("../config.constants");
5
- class InvalidScheduleException extends Error {
4
+ const extended_config_exception_1 = require("./extended-config-exception");
5
+ const identifier_util_1 = require("../util/identifier.util");
6
+ class InvalidScheduleException extends extended_config_exception_1.ExtendedConfigException {
6
7
  constructor(identifier) {
7
- super(`${identifier || config_constants_1.NOT_IDENTIFIED} strategy's schedule is not a valid cron syntax`);
8
+ super(`${(0, identifier_util_1.formatIdentifier)(identifier)} strategy's schedule is not a valid cron syntax`, { identifier });
8
9
  }
9
10
  }
10
11
  exports.InvalidScheduleException = InvalidScheduleException;
@@ -1,3 +1,4 @@
1
- export declare class InvalidTransformerException extends Error {
2
- constructor(identifier?: string | Symbol);
1
+ import { ExtendedConfigException } from './extended-config-exception';
2
+ export declare class InvalidTransformerException extends ExtendedConfigException {
3
+ constructor(identifier?: string | symbol);
3
4
  }
@@ -1,10 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.InvalidTransformerException = void 0;
4
- const config_constants_1 = require("../config.constants");
5
- class InvalidTransformerException extends Error {
4
+ const extended_config_exception_1 = require("./extended-config-exception");
5
+ const identifier_util_1 = require("../util/identifier.util");
6
+ class InvalidTransformerException extends extended_config_exception_1.ExtendedConfigException {
6
7
  constructor(identifier) {
7
- super(`${identifier || config_constants_1.NOT_IDENTIFIED} strategy's transformer is not an instance of TransformerClass or TransformerMethod`);
8
+ super(`${(0, identifier_util_1.formatIdentifier)(identifier)} strategy's transformer is not an instance of TransformerClass or TransformerMethod`, { identifier });
8
9
  }
9
10
  }
10
11
  exports.InvalidTransformerException = InvalidTransformerException;
@@ -1,3 +1,4 @@
1
- export declare class InvalidValidatorException extends Error {
2
- constructor(identifier?: string | Symbol);
1
+ import { ExtendedConfigException } from './extended-config-exception';
2
+ export declare class InvalidValidatorException extends ExtendedConfigException {
3
+ constructor(identifier?: string | symbol);
3
4
  }