Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 26 additions & 10 deletions src/config.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
* - Validation runs BEFORE any other provider resolves.
* - If validation fails, ConfigValidationError is thrown and the app
* never finishes booting.
* - A shared namespace registry (Set<string>) is exported so that
* NamespacedConfig.asProvider() can detect duplicate namespaces.
*
* Contents:
* - ConfigModuleAsyncOptions — interface for registerAsync options
Expand All @@ -33,9 +35,9 @@ import { DynamicModule, Global, Module } from "@nestjs/common";
import type { Provider } from "@nestjs/common";
import type { z } from "zod";

import { CONFIG_VALUES_TOKEN } from "@/constants";
import type { ConfigDefinition } from "@/define-config";
import { ConfigService } from "@/config.service";
import { CONFIG_VALUES_TOKEN, NAMESPACE_REGISTRY_TOKEN } from "@/constants";
import type { ConfigDefinition } from "@/define-config";

// ─────────────────────────────────────────────────────────────────────────────
// Internal type helpers
Expand Down Expand Up @@ -82,9 +84,7 @@ export interface ConfigModuleAsyncOptions<T extends AnyZodObject = AnyZodObject>
* Factory function that returns the ConfigDefinition to validate.
* May be synchronous or async.
*/
useFactory: (
...args: unknown[]
) => Promise<ConfigDefinition<T>> | ConfigDefinition<T>;
useFactory: (...args: unknown[]) => Promise<ConfigDefinition<T>> | ConfigDefinition<T>;
}

// ─────────────────────────────────────────────────────────────────────────────
Expand Down Expand Up @@ -145,14 +145,24 @@ export class ConfigModule {
useValue: parsedConfig,
};

// Namespace registry — a shared Set<string> that NamespacedConfig.asProvider()
// injects to detect duplicate namespace registrations at module init time.
// A fresh Set is created per ConfigModule instance.
const namespaceRegistryProvider: Provider = {
provide: NAMESPACE_REGISTRY_TOKEN,
useValue: new Set<string>(),
};

return {
Comment on lines +150 to 156
Copy link

Copilot AI Apr 8, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The namespace registry is created as new Set<string>() per ConfigModule.register() / registerAsync() call. That means duplicate namespace detection only works within the scope of a single ConfigModule instance; importing ConfigModule multiple times will create multiple registries and allow duplicate namespaces across module graphs. If app-wide uniqueness is required, consider using a shared singleton registry (or enforce a single ConfigModule import) and document the expected usage.

Copilot uses AI. Check for mistakes.
module: ConfigModule,
providers: [
configValuesProvider, // must be listed before ConfigService (which depends on it)
configValuesProvider, // parsed config values — must come before ConfigService
namespaceRegistryProvider, // registry for namespace duplicate detection
ConfigService,
],
// Export ConfigService so the importing module can inject it
exports: [ConfigService],
// Export both ConfigService and the registry so feature modules' asProvider()
// can inject NAMESPACE_REGISTRY_TOKEN
exports: [ConfigService, NAMESPACE_REGISTRY_TOKEN],
// Non-global: only available in the importing module unless re-exported
global: false,
};
Expand Down Expand Up @@ -201,12 +211,18 @@ export class ConfigModule {
inject: (options.inject ?? []) as never[],
};

// Namespace registry shared with feature modules' asProvider() factories
const namespaceRegistryProvider: Provider = {
provide: NAMESPACE_REGISTRY_TOKEN,
useValue: new Set<string>(),
};

return {
module: ConfigModule,
// Make the imported modules available so the factory can resolve them
imports: options.imports ?? [],
providers: [configValuesProvider, ConfigService],
exports: [ConfigService],
providers: [configValuesProvider, namespaceRegistryProvider, ConfigService],
exports: [ConfigService, NAMESPACE_REGISTRY_TOKEN],
global: false,
};
}
Expand Down
48 changes: 44 additions & 4 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,62 @@
* These tokens are the "glue" between ConfigModule providers and the
* services that consume them. They are NOT part of the public API —
* consumers should never inject these tokens directly; they should use
* ConfigService instead.
* ConfigService or @InjectConfig() instead.
*
* Contents:
* - CONFIG_VALUES_TOKEN — token for the parsed, frozen config object
* - CONFIG_VALUES_TOKEN — token for the root parsed config object
* - getNamespaceToken() — generates a unique DI token per namespace
* - NAMESPACE_REGISTRY_TOKEN — token for the set of registered namespace names
*/

// ─────────────────────────────────────────────────────────────────────────────
// DI Tokens
// Root config token
// ─────────────────────────────────────────────────────────────────────────────

/**
* Injection token for the parsed and validated config object.
* Injection token for the parsed and validated root config object.
*
* ConfigModule registers the result of `definition.parse(process.env)` under
* this token. ConfigService then injects it to serve typed `get()` calls.
*
* Consumers should never inject this token directly — always use ConfigService.
*/
export const CONFIG_VALUES_TOKEN = "CONFIG_KIT_VALUES" as const;

// ─────────────────────────────────────────────────────────────────────────────
// Namespace tokens
// ─────────────────────────────────────────────────────────────────────────────

/**
* Generates a unique, stable DI token for a given namespace string.
*
* Each namespace gets its own token so that NestJS can inject the correct
* validated config slice into each feature module independently.
*
* The token is a plain string prefixed with `CONFIG_KIT_NS:` to avoid any
* accidental collision with other DI tokens in the consuming app.
*
* @param namespace - The namespace name passed to `defineNamespace()`.
* @returns A unique DI token string for that namespace.
*
* @example
* ```typescript
* getNamespaceToken('database') // → 'CONFIG_KIT_NS:database'
* getNamespaceToken('auth') // → 'CONFIG_KIT_NS:auth'
* ```
*/
export function getNamespaceToken(namespace: string): string {
return `CONFIG_KIT_NS:${namespace}`;
}

/**
* Injection token for the namespace registry.
*
* ConfigModule stores a `Set<string>` of all registered namespace names under
* this token at startup. When a new NamespacedConfig is added, it checks this
* registry and throws if the namespace has already been registered — preventing
* silent duplicate registrations that would produce unpredictable behavior.
*
* This token is internal; consumers never interact with it directly.
*/
export const NAMESPACE_REGISTRY_TOKEN = "CONFIG_KIT_NS_REGISTRY" as const;
72 changes: 72 additions & 0 deletions src/decorators/inject-config.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/**
* @file inject-config.decorator.ts
* @description
* Parameter decorator for injecting a typed namespace config slice into
* NestJS constructors.
*
* Usage:
* ```typescript
* constructor(
* @InjectConfig('auth') private cfg: z.output<typeof authConfig.definition.schema>
* ) {}
* ```
*
* Under the hood it is just `@Inject(getNamespaceToken(namespace))` — a thin
* wrapper so consumers never have to know about the internal token format.
*
* Contents:
* - InjectConfig() — parameter decorator factory
*/

import { Inject } from "@nestjs/common";

import { getNamespaceToken } from "@/constants";

// ─────────────────────────────────────────────────────────────────────────────
// @InjectConfig
// ─────────────────────────────────────────────────────────────────────────────

/**
* Parameter decorator that injects the validated config slice for a namespace.
*
* Must be used in constructors of NestJS providers (services, controllers, etc.)
* inside a module that has imported ConfigModule and added the corresponding
* `NamespacedConfig.asProvider()` to its `providers` array.
*
* The injected value is a frozen, fully-typed object — the Zod output of the
* schema passed to `defineNamespace()`. No `string | undefined` values.
*
* @param namespace - The namespace name used in `defineNamespace(namespace, schema)`.
* Must match exactly (case-sensitive).
* @returns A NestJS `@Inject()` parameter decorator bound to the namespace token.
*
* @example
* ```typescript
* // auth/auth.config.ts
* export const authConfig = defineNamespace('auth', z.object({
* JWT_SECRET: z.string().min(32),
* JWT_EXPIRES_IN: z.string().default('7d'),
* }));
*
* // auth/auth.module.ts
* @Module({ providers: [authConfig.asProvider(), AuthService] })
* export class AuthModule {}
*
* // auth/auth.service.ts
* @Injectable()
* export class AuthService {
* constructor(
* // Injects the validated { JWT_SECRET: string, JWT_EXPIRES_IN: string } object
* @InjectConfig('auth') private cfg: z.output<typeof authConfig.definition.schema>
* ) {}
*
* getSecret(): string {
* return this.cfg.JWT_SECRET; // string — never undefined
* }
* }
* ```
*/
export function InjectConfig(namespace: string): ParameterDecorator {
// Resolve the namespace to its unique DI token and delegate to NestJS @Inject
return Inject(getNamespaceToken(namespace));
}
Loading
Loading