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
10 changes: 10 additions & 0 deletions docs/reference/dependency-injection.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,13 @@ await kernel.dependencyInjection({

This avoids local bridge contracts or hand-written aliases when applications
inject contracts exported by this package.

## Autowire Noise

Container generation ignores type-only default exports and other files that
look like TypeScript declarations but have no runtime default export. Those
files are skipped without warning so generated logs stay focused on actionable
container issues.

Warnings that remain during autowire should describe a concrete service,
dependency symbol or import that needs to be fixed.
13 changes: 12 additions & 1 deletion docs/reference/kernel.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,18 @@ kernel.environment.SERVICE_NAME; // string | undefined
Required variables throw `KernelEnvironmentValidationError` when they are
missing. `number` and `boolean` values are parsed after `.env` files are loaded.
Boolean values accept `true`, `false`, `1`, `0`, `yes`, `no`, `on` and `off`.
Blank numeric values are rejected instead of being coerced to `0`.

Blank values are handled before parsing:

| Schema | Environment value | Result |
| ---------------------------------------- | ----------------- | -------------------------------------- |
| `{ type: 'number' }` | `FOO=` | `kernel.environment.FOO === undefined` |
| `{ type: 'number', defaultValue: 3000 }` | `FOO=` | `kernel.environment.FOO === 3000` |
| `{ type: 'number', required: true }` | `FOO=` | `KernelEnvironmentValidationError` |
| `{ type: 'number' }` | `FOO=abc` | `KernelEnvironmentValidationError` |

Validation errors distinguish missing required variables, blank required
variables and invalid parsed values.

`choices` restricts the allowed runtime values and narrows the TypeScript type
when the schema is declared `as const`:
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,7 @@
"prettier": "^3.9.1",
"reflect-metadata": "^0.2.2",
"routing-controllers": "^0.11.3",
"ts-node": "^10.9.2",
"tsup": "^8.5.1",
"typescript": "^6.0.3",
"vitepress": "^1.6.4",
Expand Down
83 changes: 69 additions & 14 deletions src/Kernel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,18 @@ export class Kernel<
}
}

private static assertRequiredEnvironmentVariableIsNotBlank(
name: string,
value: string,
schema: KernelEnvironmentSchema,
): void {
if (schema[name]?.required === true && value.trim() === '') {
throw new KernelEnvironmentValidationError(
`Blank required environment variable "${name}".`,
);
}
}

private static assertEnvironmentVariableChoice(
name: string,
value: KernelEnvironmentValue,
Expand Down Expand Up @@ -176,28 +188,22 @@ export class Kernel<
}

throw new KernelEnvironmentValidationError(
`Environment variable "${name}" must be a boolean.`,
`Environment variable "${name}" has invalid boolean value "${value}".`,
);
}

private static parseNumberEnvironmentVariable(
name: string,
value: string,
): number {
if (value.trim() === '') {
throw new KernelEnvironmentValidationError(
`Environment variable "${name}" must be a number.`,
);
}

const parsedValue = Number(value);

if (Number.isFinite(parsedValue)) {
return parsedValue;
}

throw new KernelEnvironmentValidationError(
`Environment variable "${name}" must be a number.`,
`Environment variable "${name}" has invalid number value "${value}".`,
);
}

Expand Down Expand Up @@ -229,22 +235,71 @@ export class Kernel<
return value;
}

private static getEnvironmentVariableValue(
name: string,
definition: KernelEnvironmentSchema[string],
schema: KernelEnvironmentSchema,
): string | undefined {
const value = process.env[name];

Kernel.assertRequiredEnvironmentVariable(name, value, schema);

if (value !== undefined) {
Kernel.assertRequiredEnvironmentVariableIsNotBlank(name, value, schema);
}

if (value !== undefined && value.trim() !== '') {
return value;
}

return definition.defaultValue?.toString();
}

private static shouldUnsetBlankOptionalEnvironmentVariable(
name: string,
value: string | undefined,
valueOrDefault: string | undefined,
schema: KernelEnvironmentSchema,
): boolean {
return (
value !== undefined &&
value.trim() === '' &&
valueOrDefault === undefined &&
schema[name]?.required !== true
);
}

private static validateEnvironmentVariables<
TSchema extends KernelEnvironmentSchema,
>(schema: TSchema): KernelEnvironmentForSchema<TSchema> {
const environmentVariables: Record<string, KernelEnvironmentValue> = {};
const environmentVariables: Record<
string,
KernelEnvironmentValue | undefined
> = {};

for (const [name, definition] of Object.entries(schema)) {
const value = process.env[name] ?? definition.defaultValue?.toString();

Kernel.assertRequiredEnvironmentVariable(name, value, schema);
const value = process.env[name];
const valueOrDefault = Kernel.getEnvironmentVariableValue(
name,
definition,
schema,
);

if (value !== undefined) {
if (valueOrDefault !== undefined) {
environmentVariables[name] = Kernel.parseEnvironmentVariable(
name,
value,
valueOrDefault,
schema,
);
} else if (
Kernel.shouldUnsetBlankOptionalEnvironmentVariable(
name,
value,
valueOrDefault,
schema,
)
) {
environmentVariables[name] = undefined;
}
}

Expand Down
35 changes: 35 additions & 0 deletions src/infrastructure/dependency-injection/AutowireWarningFilter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import type { Logger } from 'node-dependency-injection';

export class AutowireWarningFilter implements Logger {
constructor(private readonly logger: Logger) {}

private isIgnorableAutowireWarning(message: string): boolean {
return (
message.startsWith(
'Autowire: file has export default declaration but no runtime default export:',
) ||
message.startsWith('Autowire: failed to create definition for undefined:')
);
}

public warn(message?: unknown, ...optionalParams: unknown[]): void {
if (
typeof message === 'string' &&
this.isIgnorableAutowireWarning(message)
) {
this.logger.debug?.(`Ignored ${message}`, ...optionalParams);

return;
}

this.logger.warn(message, ...optionalParams);
}

public info(message?: unknown, ...optionalParams: unknown[]): void {
this.logger.info?.(message, ...optionalParams);
}

public debug(message?: unknown, ...optionalParams: unknown[]): void {
this.logger.debug?.(message, ...optionalParams);
}
}
16 changes: 15 additions & 1 deletion src/infrastructure/dependency-injection/DependencyInjection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import type { DefinitionMetadata } from './DefinitionMetadata.js';
import type { DependencyInjectionOptions } from './DependencyInjectionOptions.js';
import type { DependencyOverride } from './DependencyOverride.js';

import { AutowireWarningFilter } from './AutowireWarningFilter.js';

export class DependencyInjection implements ServiceResolver {
private static configuredInstance: DependencyInjection | undefined;
private autowire: Autowire | undefined;
Expand Down Expand Up @@ -295,6 +297,18 @@ export class DependencyInjection implements ServiceResolver {
}
}

private async processAutowire(): Promise<void> {
const previousLogger = this.container.logger;

this.container.logger = new AutowireWarningFilter(previousLogger);

try {
await this.autowire?.process();
} finally {
this.container.logger = previousLogger;
}
}

private registerParentAliases(): void {
for (const [id, definition] of this.definitions.entries()) {
if (definition._abstract === true || !definition._parent) {
Expand All @@ -313,7 +327,7 @@ export class DependencyInjection implements ServiceResolver {
this.options.servicesYamlPath,
false,
);
await this.autowire.process();
await this.processAutowire();
} else {
this.loader = new YamlFileLoader(this.container);
await this.loader.load(this.options.servicesYamlPath);
Expand Down
1 change: 1 addition & 0 deletions src/infrastructure/dependency-injection/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './AutowireWarningFilter.js';
export * from './ClassDependencyOverride.js';
export * from './ContainerDefinition.js';
export * from './ContainerInternals.js';
Expand Down
99 changes: 98 additions & 1 deletion tests/dependency-injection.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ import test from 'node:test';

import { Reference } from 'node-dependency-injection';

import { DependencyInjection } from '../dist/infrastructure/dependency-injection/index.js';
import { DomainEventPublisher } from '../dist/domain/index.js';
import {
AutowireWarningFilter,
DependencyInjection,
} from '../dist/infrastructure/dependency-injection/index.js';

class ContractRepository {}

Expand All @@ -21,11 +25,42 @@ class AliasRepository {}

class ConcreteService {}

class MessageBus extends DomainEventPublisher {
async publish() {}
}

const serviceIdFor = (ClassDefinition) =>
Buffer.from(
`${ClassDefinition.name}.ts__${ClassDefinition.name}__${ClassDefinition.name}`,
).toString('base64');

test('filters ignorable autowire warnings and forwards actionable logs', () => {
const calls = [];
const logger = new AutowireWarningFilter({
debug: (message) => calls.push(`debug:${message}`),
info: (message) => calls.push(`info:${message}`),
warn: (message) => calls.push(`warn:${message}`),
});

logger.warn(
'Autowire: file has export default declaration but no runtime default export: Contract.ts',
);
logger.warn(
"Autowire: failed to create definition for HttpClient: Cannot read properties of undefined (reading 'body')",
);
logger.warn('Autowire: could not resolve dependency "Repository"');
logger.info('Autowire scan completed');
logger.debug('Autowire debug message');

assert.deepEqual(calls, [
'debug:Ignored Autowire: file has export default declaration but no runtime default export: Contract.ts',
"warn:Autowire: failed to create definition for HttpClient: Cannot read properties of undefined (reading 'body')",
'warn:Autowire: could not resolve dependency "Repository"',
'info:Autowire scan completed',
'debug:Autowire debug message',
]);
});

test('resolves a concrete class registered in the container', async () => {
const dependencyInjection = new DependencyInjection();
const serviceId = serviceIdFor(ConcreteService);
Expand Down Expand Up @@ -298,6 +333,36 @@ test('overrides unresolved argument references generated for external package im
);
});

test('overrides unresolved argument references generated for kernel subpath imports', async () => {
class ServiceThatNeedsDomainEventPublisher {}

const dependencyInjection = new DependencyInjection({
containerBuild: true,
overrides: [
{
token: DomainEventPublisher,
useClass: MessageBus,
},
],
servicesYamlPath: '/tmp/services.yaml',
sourceDirectory: process.cwd(),
});
const serviceId = serviceIdFor(ServiceThatNeedsDomainEventPublisher);
const externalReferenceId = Buffer.from(
'src__application____haskou__ddd-kernel__domain__DomainEventPublisher',
).toString('base64');

dependencyInjection.container
.register(serviceId, ServiceThatNeedsDomainEventPublisher)
.addArgument(new Reference(externalReferenceId));
dependencyInjection.applyOverrides();
await dependencyInjection.container.compile();

assert.ok(
dependencyInjection.getService(externalReferenceId) instanceof MessageBus,
);
});

test('generates services.yaml', async () => {
const temporaryDirectory = await mkdtemp(path.join(tmpdir(), 'ddd-kernel-'));
const sourceDirectory = temporaryDirectory;
Expand Down Expand Up @@ -326,6 +391,38 @@ test('generates services.yaml', async () => {
assert.match(servicesYaml, /GeneratedRepository/);
});

test('ignores type-only default exports during autowire', async () => {
const temporaryDirectory = await mkdtemp(path.join(tmpdir(), 'ddd-kernel-'));
const servicesYamlPath = path.join(
temporaryDirectory,
'config',
'container',
'services.yaml',
);
const warnings = [];

await writeFile(
path.join(temporaryDirectory, 'IgnoredContract.ts'),
'export default interface IgnoredContract {}\n',
);

const dependencyInjection = new DependencyInjection({
containerBuild: true,
servicesYamlPath,
sourceDirectory: temporaryDirectory,
});

dependencyInjection.container.logger = {
warn(message) {
warnings.push(String(message));
},
};

await dependencyInjection.compile();

assert.deepEqual(warnings, []);
});

test('reads services.yaml', async () => {
const temporaryDirectory = await mkdtemp(path.join(tmpdir(), 'ddd-kernel-'));
const loadedRepositoryPath = path.join(
Expand Down
Loading