ClaDI 🧩
ClaDI is a library for creating and managing classes in TypeScript
📚 Table of Contents
📖 Description
ClaDI is a powerful TypeScript library that provides a robust foundation for building scalable applications through class-based dependency injection. With ClaDI, you can easily create, manage, and organize your application's classes and dependencies with a clean, modular architecture. The library offers a comprehensive set of tools for class instantiation, dependency registration, and lifecycle management, making it ideal for both small projects and enterprise-level applications. Whether you're building a simple utility or a complex system, ClaDI helps establish a solid architectural foundation with minimal overhead.
🚀 Features
- ✨ 🚀 Zero dependencies - Lightweight footprint with no external runtime dependencies
- ✨ 📦 Registry system - Store, retrieve, and manage class templates efficiently
- ✨ 🏭 Factory pattern - Create class instances with automatic deep cloning
- ✨ 💉 Dependency injection - Simple yet powerful container for managing application services
- ✨ 🔄 Caching mechanism - Performance optimization for frequently used classes
- ✨ 🧩 Modular architecture - Clean separation of concerns with domain, infrastructure, and presentation layers
- ✨ 📝 Comprehensive logging - Built-in logging system with multiple log levels and context support
- ✨ 🔌 Multiple format support - Works with both ESM and CommonJS module systems
- ✨ ✅ Fully tested - Extensive unit and E2E test coverage ensures reliability
🛠 Installation
npm install @elsikora/cladi
yarn add @elsikora/cladi
pnpm add @elsikora/cladi
bun add @elsikora/cladi
💡 Usage
Basic Usage
The following example demonstrates how to create and use the core components of ClaDI:
import { createContainer, createFactory, createLogger, createRegistry, ELoggerLogLevel } from '@elsikora/cladi';
interface User {
name: string;
email: string;
role: string;
}
const logger = createLogger({
level: ELoggerLogLevel.DEBUG,
source: 'UserModule'
});
const registry = createRegistry<User>({ logger });
registry.register({ name: 'admin', email: 'admin@example.com', role: 'admin' });
registry.register({ name: 'user', email: 'user@example.com', role: 'user' });
const factory = createFactory<User>({ registry, logger });
const adminUser = factory.create('admin');
console.log(adminUser);
adminUser.email = 'new-admin@example.com';
Dependency Injection Container
Use the container to manage application services:
import { createContainer, ELoggerLogLevel, type ILogger } from '@elsikora/cladi';
const LoggerToken = Symbol('Logger');
const DatabaseToken = Symbol('Database');
const container = createContainer({});
container.register(LoggerToken, createLogger({
level: ELoggerLogLevel.INFO,
source: 'AppRoot'
}));
container.register(DatabaseToken, {
connect: () => console.log('Connected to database'),
query: (sql: string) => console.log(`Executing query: ${sql}`)
});
const logger = container.get<ILogger>(LoggerToken);
const db = container.get(DatabaseToken);
logger?.info('Application started');
db?.connect();
db?.query('SELECT * FROM users');
Advanced Logging
The built-in logger provides extensive capabilities:
import { createLogger, ELoggerLogLevel } from '@elsikora/cladi';
const logger = createLogger({
level: ELoggerLogLevel.TRACE,
source: 'PaymentService'
});
logger.info('Processing payment');
logger.debug('Payment details received', {
context: {
paymentId: '12345',
amount: 99.99,
currency: 'USD'
}
});
logger.warn('Retry attempt required', {
source: 'PaymentGateway',
context: {
attempt: 2,
maxAttempts: 3
}
});
Core Factory Pattern
For more advanced scenarios, use the CoreFactory singleton:
import { CoreFactory, ELoggerLogLevel, type IRegistry, type IFactory, type IContainer } from '@elsikora/cladi';
const coreFactory = CoreFactory.getInstance({
logger: createLogger({
level: ELoggerLogLevel.INFO,
source: 'CoreFactory'
})
});
interface Product {
name: string;
price: number;
inStock: boolean;
}
const productRegistry = coreFactory.createRegistry<Product>({});
const productFactory = coreFactory.createFactory<Product>({ registry: productRegistry });
const appContainer = coreFactory.createContainer({});
productRegistry.register({ name: 'Basic Widget', price: 9.99, inStock: true });
productRegistry.register({ name: 'Premium Widget', price: 19.99, inStock: false });
const basicWidget = productFactory.create('Basic Widget');
console.log(basicWidget);
Custom Transformers
You can provide custom transformers to modify objects during instantiation:
import { createFactory, createRegistry } from '@elsikora/cladi';
interface OrderTemplate {
name: string;
basePrice: number;
discountPercent: number;
}
const orderRegistry = createRegistry<OrderTemplate>({});
orderRegistry.register({
name: 'standard',
basePrice: 100,
discountPercent: 0
});
orderRegistry.register({
name: 'sale',
basePrice: 100,
discountPercent: 20
});
const orderTransformer = (template: OrderTemplate) => {
const discount = template.basePrice * (template.discountPercent / 100);
return {
...template,
discount,
finalPrice: template.basePrice - discount,
timestamp: new Date().toISOString()
};
};
const orderFactory = createFactory<ReturnType<typeof orderTransformer>>({
registry: orderRegistry as any,
transformer: orderTransformer
});
const standardOrder = orderFactory.create('standard');
console.log(standardOrder);
const saleOrder = orderFactory.create('sale');
console.log(saleOrder);
🛣 Roadmap
Core Registry implementation | ✅ Done |
Core Factory implementation | ✅ Done |
Dependency Injection Container | ✅ Done |
Logging System | ✅ Done |
Support for ESM and CJS modules | ✅ Done |
Registry caching mechanism | ✅ Done |
Factory deep cloning | ✅ Done |
Custom transformers | ✅ Done |
API documentation | 🚧 In Progress |
Type safety improvements | 🚧 In Progress |
Async factory support | 🚧 In Progress |
Schema validation | 🚧 In Progress |
Event system | 🚧 In Progress |
Circular dependency detection | 🚧 In Progress |
Lifecycle hooks | 🚧 In Progress |
Lazy loading | 🚧 In Progress |
Serialization/deserialization utilities | 🚧 In Progress |
Performance benchmarks | 🚧 In Progress |
Web framework integrations | 🚧 In Progress |
❓ FAQ
Frequently Asked Questions
Is ClaDI suitable for small projects?
Yes, ClaDI is designed to be scalable for projects of all sizes. For small projects, you can use just the components you need, such as the Registry and Factory, without implementing the full dependency injection system.
How does ClaDI compare to other DI frameworks like InversifyJS or TypeDI?
ClaDI is more lightweight and focused, with zero external dependencies. It provides core building blocks rather than a full-featured DI framework. It's suitable for projects that need a clean, extensible foundation with minimal overhead.
Does ClaDI work with browser environments?
Yes, ClaDI is designed to work in both Node.js and browser environments. It's built with ES modules and also provides CommonJS compatibility.
How does the registry's caching mechanism work?
The registry implements an internal cache for getAll()
and getMany()
operations. When you register or unregister items, the cache is automatically cleared to ensure you always get fresh data.
Can I use ClaDI with React, Angular, or Vue?
Yes, ClaDI can be used with any frontend framework. It's framework-agnostic and provides core infrastructure that can be integrated into your component system.
How do I handle circular dependencies?
Currently, circular dependencies must be managed manually. However, the roadmap includes adding circular dependency detection to help identify and resolve these issues.
Is there a performance penalty for using the factory pattern?
The factory performs deep cloning of templates using structuredClone()
, which has better performance than JSON serialization methods. For most applications, this overhead is negligible, and the benefits of immutability outweigh the performance cost.
🔒 License
This project is licensed under **MIT License
Copyright (c) 2025 ElsiKora
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.**.