nestjs-config-extended 1.2.6 → 2.0.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +236 -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/index.d.ts +4 -0
  7. package/dist/exceptions/index.js +9 -1
  8. package/dist/exceptions/invalid-loader-exception.d.ts +1 -1
  9. package/dist/exceptions/invalid-loader-exception.js +2 -2
  10. package/dist/exceptions/invalid-reload-interval-exception.d.ts +3 -0
  11. package/dist/exceptions/invalid-reload-interval-exception.js +11 -0
  12. package/dist/exceptions/invalid-schedule-exception.d.ts +1 -1
  13. package/dist/exceptions/invalid-schedule-exception.js +2 -2
  14. package/dist/exceptions/invalid-transformer-exception.d.ts +1 -1
  15. package/dist/exceptions/invalid-transformer-exception.js +2 -2
  16. package/dist/exceptions/invalid-validator-exception.d.ts +1 -1
  17. package/dist/exceptions/invalid-validator-exception.js +2 -2
  18. package/dist/exceptions/loading-exception.d.ts +1 -1
  19. package/dist/exceptions/loading-exception.js +2 -2
  20. package/dist/exceptions/missing-config-exception.d.ts +4 -0
  21. package/dist/exceptions/missing-config-exception.js +11 -0
  22. package/dist/exceptions/process-env-assignment-exception.d.ts +3 -0
  23. package/dist/exceptions/process-env-assignment-exception.js +10 -0
  24. package/dist/exceptions/schema-validation-exception.d.ts +5 -0
  25. package/dist/exceptions/schema-validation-exception.js +23 -0
  26. package/dist/exceptions/transformation-exception.d.ts +1 -1
  27. package/dist/exceptions/transformation-exception.js +2 -2
  28. package/dist/exceptions/validation-exception.d.ts +1 -1
  29. package/dist/exceptions/validation-exception.js +2 -2
  30. package/dist/extended-config.health.d.ts +13 -0
  31. package/dist/extended-config.health.js +50 -0
  32. package/dist/extended-config.module.d.ts +3 -0
  33. package/dist/extended-config.module.js +55 -28
  34. package/dist/extended-config.service.d.ts +41 -18
  35. package/dist/extended-config.service.js +326 -138
  36. package/dist/index.d.ts +3 -0
  37. package/dist/index.js +11 -1
  38. package/dist/interfaces/config-change-event.interface.d.ts +5 -0
  39. package/dist/interfaces/config-change-event.interface.js +2 -0
  40. package/dist/interfaces/config-loader-strategy.interface.d.ts +16 -7
  41. package/dist/interfaces/config-module-options.interface.d.ts +7 -2
  42. package/dist/interfaces/config-path.interface.d.ts +9 -0
  43. package/dist/interfaces/config-path.interface.js +2 -0
  44. package/dist/interfaces/config-status.interface.d.ts +13 -0
  45. package/dist/interfaces/config-status.interface.js +2 -0
  46. package/dist/interfaces/cron-scheduler.interface.d.ts +11 -0
  47. package/dist/interfaces/cron-scheduler.interface.js +2 -0
  48. package/dist/interfaces/index.d.ts +6 -0
  49. package/dist/interfaces/index.js +11 -1
  50. package/dist/interfaces/redact-options.interface.d.ts +4 -0
  51. package/dist/interfaces/redact-options.interface.js +2 -0
  52. package/dist/interfaces/standard-schema.interface.d.ts +33 -0
  53. package/dist/interfaces/standard-schema.interface.js +2 -0
  54. package/dist/strategies/dotEnv/dot-env.strategy.d.ts +1 -1
  55. package/dist/strategies/dotEnv/dot-env.strategy.js +36 -18
  56. package/dist/strategies/dotEnv/index.js +5 -1
  57. package/dist/strategies/file/file.interface.d.ts +5 -0
  58. package/dist/strategies/file/file.interface.js +2 -0
  59. package/dist/strategies/file/index.d.ts +3 -0
  60. package/dist/strategies/file/index.js +19 -0
  61. package/dist/strategies/file/json-file.strategy.d.ts +2 -0
  62. package/dist/strategies/file/json-file.strategy.js +6 -0
  63. package/dist/strategies/file/read-config-file.util.d.ts +2 -0
  64. package/dist/strategies/file/read-config-file.util.js +60 -0
  65. package/dist/strategies/file/yaml-file.strategy.d.ts +2 -0
  66. package/dist/strategies/file/yaml-file.strategy.js +17 -0
  67. package/dist/strategies/index.d.ts +1 -0
  68. package/dist/strategies/index.js +6 -1
  69. package/dist/util/clone.util.d.ts +1 -0
  70. package/dist/util/clone.util.js +24 -0
  71. package/dist/util/config-proxy.util.d.ts +1 -0
  72. package/dist/util/config-proxy.util.js +35 -0
  73. package/dist/util/deep-equal.util.d.ts +1 -0
  74. package/dist/util/deep-equal.util.js +26 -0
  75. package/dist/util/duration.util.d.ts +1 -0
  76. package/dist/util/duration.util.js +22 -0
  77. package/dist/util/identifier.util.d.ts +1 -0
  78. package/dist/util/identifier.util.js +6 -0
  79. package/dist/util/is-undefined.util.d.ts +1 -0
  80. package/dist/util/is-undefined.util.js +6 -0
  81. package/dist/util/loader.util.d.ts +4 -3
  82. package/dist/util/loader.util.js +67 -27
  83. package/dist/util/object.util.js +9 -4
  84. package/dist/util/redact.util.d.ts +4 -0
  85. package/dist/util/redact.util.js +47 -0
  86. package/index.d.mts +1 -0
  87. package/index.mjs +4 -0
  88. package/llms.txt +102 -0
  89. package/package.json +114 -44
  90. package/index.d.ts +0 -1
  91. package/index.js +0 -6
  92. package/logo.png +0 -0
  93. 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 |
41
+ | ---------------------- | -------- | ------- |
42
+ | 2.x | 11, 12 | 22.12+ |
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).
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,139 @@ 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
+ ### Reacting to changes
262
+
263
+ 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:
264
+
265
+ ```typescript
266
+ // emits now and on every distinct change
267
+ this.config.watch('database.host').subscribe(host => this.reconnect(host));
268
+
269
+ // { reason: 'load' | 'reload', identifier, changedKeys: string[] }
270
+ this.config.changes().subscribe(event => this.logger.log(event.changedKeys));
271
+ ```
272
+
273
+ Both observables complete when the application shuts down. The same information is available through the `onChange` and `onReloadError` module options.
274
+
275
+ ### Health checks
276
+
277
+ `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`):
278
+
279
+ ```typescript
280
+ @Module({
281
+ imports: [TerminusModule],
282
+ controllers: [HealthController],
283
+ providers: [ExtendedConfigHealthIndicator], // root module must be global
284
+ })
285
+ export class HealthModule {}
286
+
287
+ @Controller('health')
288
+ export class HealthController {
289
+ constructor(
290
+ private health: HealthCheckService,
291
+ private configHealth: ExtendedConfigHealthIndicator,
292
+ ) {}
293
+
294
+ @Get()
295
+ @HealthCheck()
296
+ check() {
297
+ return this.health.check([
298
+ () =>
299
+ this.configHealth.isHealthy('config', { maxConsecutiveFailures: 3 }),
300
+ ]);
301
+ }
302
+ }
303
+ ```
304
+
305
+ ### Typed configuration
306
+
307
+ 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>`.
308
+
309
+ ```typescript
310
+ interface AppConfig {
311
+ PORT: number;
312
+ database: { host: string; ssl?: boolean };
313
+ }
314
+
315
+ constructor(private config: ExtendedConfigService<AppConfig>) {}
316
+
317
+ const port = this.config.get('PORT'); // number | undefined
318
+ const host = this.config.getOrThrow('database.host'); // string
319
+ this.config.get('database.nope'); // compile error
320
+ ```
321
+
322
+ Untyped services keep accepting any string and explicit type arguments such as `get<string>('KEY')`.
323
+
324
+ > :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
325
 
140
326
  ## Full example
141
327
 
142
- The examples below uses all availables options to help you to understand the module, but some of them are conflicting.
328
+ 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
329
 
144
330
  ### Using `.forRoot()`
145
331
 
@@ -234,12 +420,14 @@ import { ExtendedConfigModule, dotEnvLoader } from 'nestjs-config-extended';
234
420
  export class AppModule {}
235
421
  ```
236
422
 
237
- ## Stay in touch
423
+ ## Contributing
238
424
 
239
- - Author - [Pedro Sodré](https://github.com/pedrosodre)
425
+ 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
426
 
241
- ## License
427
+ 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
428
 
243
- This module is [MIT licensed](LICENSE).
429
+ Release notes are published on the [GitHub releases page](https://github.com/pedrosodre/nestjs-config-extended/releases).
430
+
431
+ ## License
244
432
 
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).
433
+ [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';
@@ -5,3 +5,7 @@ export * from './invalid-schedule-exception';
5
5
  export * from './validation-exception';
6
6
  export * from './loading-exception';
7
7
  export * from './transformation-exception';
8
+ export * from './process-env-assignment-exception';
9
+ export * from './schema-validation-exception';
10
+ export * from './missing-config-exception';
11
+ 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];
@@ -17,3 +21,7 @@ __exportStar(require("./invalid-schedule-exception"), exports);
17
21
  __exportStar(require("./validation-exception"), exports);
18
22
  __exportStar(require("./loading-exception"), exports);
19
23
  __exportStar(require("./transformation-exception"), exports);
24
+ __exportStar(require("./process-env-assignment-exception"), exports);
25
+ __exportStar(require("./schema-validation-exception"), exports);
26
+ __exportStar(require("./missing-config-exception"), exports);
27
+ __exportStar(require("./invalid-reload-interval-exception"), exports);
@@ -1,3 +1,3 @@
1
1
  export declare class InvalidLoaderException extends Error {
2
- constructor(identifier?: string | Symbol);
2
+ constructor(identifier?: string | symbol);
3
3
  }
@@ -1,10 +1,10 @@
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");
4
+ const identifier_util_1 = require("../util/identifier.util");
5
5
  class InvalidLoaderException extends Error {
6
6
  constructor(identifier) {
7
- super(`${identifier || config_constants_1.NOT_IDENTIFIED} strategy's loader is not an instance of LoaderMethod or LoaderClass`);
7
+ super(`${(0, identifier_util_1.formatIdentifier)(identifier)} strategy's loader is not an instance of LoaderMethod or LoaderClass`);
8
8
  }
9
9
  }
10
10
  exports.InvalidLoaderException = InvalidLoaderException;
@@ -0,0 +1,3 @@
1
+ export declare class InvalidReloadIntervalException extends Error {
2
+ constructor(reason: string, identifier?: string | symbol);
3
+ }
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InvalidReloadIntervalException = void 0;
4
+ const identifier_util_1 = require("../util/identifier.util");
5
+ class InvalidReloadIntervalException extends Error {
6
+ constructor(reason, identifier) {
7
+ super(`${(0, identifier_util_1.formatIdentifier)(identifier)} strategy's reload interval is invalid due "${reason}"`);
8
+ this.name = 'InvalidReloadIntervalException';
9
+ }
10
+ }
11
+ exports.InvalidReloadIntervalException = InvalidReloadIntervalException;
@@ -1,3 +1,3 @@
1
1
  export declare class InvalidScheduleException extends Error {
2
- constructor(identifier?: string | Symbol);
2
+ constructor(identifier?: string | symbol);
3
3
  }
@@ -1,10 +1,10 @@
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");
4
+ const identifier_util_1 = require("../util/identifier.util");
5
5
  class InvalidScheduleException extends Error {
6
6
  constructor(identifier) {
7
- super(`${identifier || config_constants_1.NOT_IDENTIFIED} strategy's schedule is not a valid cron syntax`);
7
+ super(`${(0, identifier_util_1.formatIdentifier)(identifier)} strategy's schedule is not a valid cron syntax`);
8
8
  }
9
9
  }
10
10
  exports.InvalidScheduleException = InvalidScheduleException;
@@ -1,3 +1,3 @@
1
1
  export declare class InvalidTransformerException extends Error {
2
- constructor(identifier?: string | Symbol);
2
+ constructor(identifier?: string | symbol);
3
3
  }
@@ -1,10 +1,10 @@
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");
4
+ const identifier_util_1 = require("../util/identifier.util");
5
5
  class InvalidTransformerException extends Error {
6
6
  constructor(identifier) {
7
- super(`${identifier || config_constants_1.NOT_IDENTIFIED} strategy's transformer is not an instance of TransformerClass or TransformerMethod`);
7
+ super(`${(0, identifier_util_1.formatIdentifier)(identifier)} strategy's transformer is not an instance of TransformerClass or TransformerMethod`);
8
8
  }
9
9
  }
10
10
  exports.InvalidTransformerException = InvalidTransformerException;
@@ -1,3 +1,3 @@
1
1
  export declare class InvalidValidatorException extends Error {
2
- constructor(identifier?: string | Symbol);
2
+ constructor(identifier?: string | symbol);
3
3
  }
@@ -1,10 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.InvalidValidatorException = void 0;
4
- const config_constants_1 = require("../config.constants");
4
+ const identifier_util_1 = require("../util/identifier.util");
5
5
  class InvalidValidatorException extends Error {
6
6
  constructor(identifier) {
7
- super(`${identifier || config_constants_1.NOT_IDENTIFIED} strategy's validator is not an instance of ValidatorMethod or ValidatorClass`);
7
+ super(`${(0, identifier_util_1.formatIdentifier)(identifier)} strategy's validator is not an instance of ValidatorMethod or ValidatorClass`);
8
8
  }
9
9
  }
10
10
  exports.InvalidValidatorException = InvalidValidatorException;
@@ -1,3 +1,3 @@
1
1
  export declare class LoadingException extends Error {
2
- constructor(reason: Error | string, identifier?: string | Symbol);
2
+ constructor(reason: Error | string, identifier?: string | symbol);
3
3
  }
@@ -1,10 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.LoadingException = void 0;
4
- const config_constants_1 = require("../config.constants");
4
+ const identifier_util_1 = require("../util/identifier.util");
5
5
  class LoadingException extends Error {
6
6
  constructor(reason, identifier) {
7
- super(`${identifier || config_constants_1.NOT_IDENTIFIED} strategy's loader was not able to load variables due "${reason}"`);
7
+ super(`${(0, identifier_util_1.formatIdentifier)(identifier)} strategy's loader was not able to load variables due "${reason}"`);
8
8
  }
9
9
  }
10
10
  exports.LoadingException = LoadingException;
@@ -0,0 +1,4 @@
1
+ export declare class MissingConfigException extends Error {
2
+ readonly path: string;
3
+ constructor(path: string);
4
+ }
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MissingConfigException = void 0;
4
+ class MissingConfigException extends Error {
5
+ constructor(path) {
6
+ super(`Configuration value "${path}" is not defined`);
7
+ this.path = path;
8
+ this.name = 'MissingConfigException';
9
+ }
10
+ }
11
+ exports.MissingConfigException = MissingConfigException;
@@ -0,0 +1,3 @@
1
+ export declare class ProcessEnvAssignmentException extends Error {
2
+ constructor(reason: string, identifier?: string | symbol);
3
+ }
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ProcessEnvAssignmentException = void 0;
4
+ const identifier_util_1 = require("../util/identifier.util");
5
+ class ProcessEnvAssignmentException extends Error {
6
+ constructor(reason, identifier) {
7
+ super(`${(0, identifier_util_1.formatIdentifier)(identifier)} strategy's variables cannot be stored on process.env (cache disabled) due "${reason}"`);
8
+ }
9
+ }
10
+ exports.ProcessEnvAssignmentException = ProcessEnvAssignmentException;
@@ -0,0 +1,5 @@
1
+ import { StandardSchemaV1 } from '../interfaces/standard-schema.interface';
2
+ export declare class SchemaValidationException extends Error {
3
+ readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
4
+ constructor(issues: ReadonlyArray<StandardSchemaV1.Issue>, identifier?: string | symbol);
5
+ }