modern-class-wrap
v0.0.1
Published
Modern class wrapper with DI, lifecycle, plugins, hooks, and state system
Maintainers
Readme
modern-class-wrap
A powerful lightweight class wrapper system for JavaScript that adds:
- Lifecycle hooks
- Dependency injection
- Plugin system
- State management
- Validation system
- Method wrapping
- Error handling
- Queue execution
- Retry + timeout utilities All in a single file npm package.
📦 Installation
npm install modern-class-wrap⸻
🚀 Basic Usage
const wrap = require("modern-class-wrap")
class User {
hello(name) {
return `Hello ${name}`
}
}
const WrappedUser = wrap(User, { autobind: true })
const user = new WrappedUser()
console.log(user.hello("Ali"))⸻
⚙️ Features
- ⚡ Single-file architecture
- 🔌 Plugin system
- 🧠 Dependency Injection (DI)
- 🔄 Lifecycle system
- 🧪 Validation engine
- 🧵 State management
- 🪝 Hooks system
- 🧰 Auto method binding
- 🔁 Retry / timeout utilities
- 📦 Queue system
- 🔍 Introspection tools
⸻
🔌 Plugin System
const loggerPlugin = {
setup(instance) {
instance.log = () => {
console.log("Instance ID:", instance.ctx.id)
}
}
}
WrappedUser.use(loggerPlugin)⸻
🔄 Lifecycle Hooks
WrappedUser.on("beforeInit", (instance) => {
console.log("Before init:", instance)
})
WrappedUser.on("afterInit", (instance) => {
console.log("After init:", instance)
})⸻
🧠 Dependency Injection
WrappedUser.register("api", {
baseURL: "https://api.example.com"
})
const api = WrappedUser.resolve("api")
console.log(api.baseURL)⸻
📦 State System
const state = new WrappedUser.state({ count: 0 })
state.set("count", 10)
console.log(state.get("count"))⸻
🧪 Validation
WrappedUser.validate("hello", {
args: [{ type: "string" }],
returns: "string"
})⸻
🔁 Retry & Timeout
const fn = async () => "done"
const safeFn = wrap.withRetry(fn, 3)
const timedFn = wrap.withTimeout(fn, 2000)⸻
📦 Queue System
const queue = WrappedUser.queue()
queue.add(async (ctx) => {
console.log("Job 1", ctx)
})
queue.add(async (ctx) => {
console.log("Job 2", ctx)
})
queue.run({ id: "task-1" })⸻
🔍 Introspection
console.log(WrappedUser.inspect())
Returns:
{
plugins: 1,
validators: 0,
hooks: {},
DI: 1
}⸻
🔁 Method Wrapping
WrappedUser.wrapMethod("hello", (original) => {
return function (...args) {
console.log("Calling hello...")
return original.apply(this, args)
}
})⸻
🧹 Error Handling
WrappedUser.onError((err, ctx) => {
console.error("Error:", err, "Context:", ctx)
})⸻
🔓 Unwrap Original Class
const Original = WrappedUser.unwrap(WrappedUser)⸻
🧠 Check if Wrapped
console.log(WrappedUser.isWrapped(User))⸻
⚙️ API
wrap(Class, options)
Wraps a class with extended capabilities.
wrap(MyClass, {
autobind: true
})
Options
Option Type Description
autobind boolean Auto bind instance methods⸻
📜 Philosophy
This library is designed to be:
- Minimal but powerful
- Single-file and dependency-free
- Framework-agnostic
- Easy to embed anywhere
⸻
🪪 License
MIT
⸻
⭐ Why use it?
Because sometimes you want framework power without a framework.
