The package is ESM-only. Use import. TypeScript consumers should set moduleResolution: "bundler". NodeNext and Node16 declaration resolution are not supported.
The kernel uses no platform APIs — no process, no DOM, no timers — so it runs unchanged on Node.js, Bun, Deno, browsers, workers, and edge runtimes. Only shutdown differs. See stop().
start() runs the root factory once
bootstrapApp() builds the graph and returns a handle. It runs nothing. app.start() runs the root factory and rejects if it fails. The root factory returns void: it wires the graph and does the work. It is not an expression that produces a value.
Register shutdown handling before start(). bootstrapApp() runs no provider, so the handle exists before any factory does. start() is idempotent: repeated calls return the same Promise and run the root factory once.
token() makes a key with no default
A Token<T> must be bound with provideFor() before anything injects it. The description is the name in the error. A ref with no description is reported as <anonymous>.
Leave the token unbound and inject(prefixToken) throws No provider for token: Prefix.
provide() makes a Ref that self-installs
A Ref<T> has a default factory. The first inject() in a scope installs it there and caches the instance. It is not a global singleton. Install a shared ref at bootstrap — pass it in providers, as formatterRef is above — so sibling subtrees reuse the same instance.
import { bootstrapApp, provide } from 'dn-ioc'
let created = 0
const configRef = provide(() => ({ id: ++created }))
const app = bootstrapApp(({ inject }) => {
const first = inject(configRef)
const second = inject(configRef)
console.log(first === second, created) // true 1
})
await app.start()
Provider configuration
provide() and provideFor() both accept { providers }. That array is a private subtree, visible to that provider and its descendants. See injection scopes for how lookups cross its boundary.
Snapshotting
Provider arrays and bundles are copied when their owning ref, binding, or bundle is created. Later edits to those arrays do not change that definition.
Order
Provider inputs are flattened in source order, nested arrays and bundles included.
Last-write-wins
If the same key is installed twice in one scope, the later binding silently replaces the earlier one, including its nested providers.
A bundle is an ordinary provider input. Use it to ship a token and the factory that reads it as one value:
inject(key) looks for a binding in the current scope, then walks up through parents. The first binding found wins.
A provider resolves its dependencies in the scope that owns its binding, including its private providers if it has any. It does not adopt the caller’s local overrides. A local binding affects its own subtree, not its parent or siblings.
Compare scope configurations
Each example starts a fresh app with the same definitions below. The app provides 'app'; the preview asks for a renderer, which asks for a label.
stop() closes injection, then runs cleanup newest-first
A successful start() never stops the app. The caller decides when to call stop(). Not every app needs it.
Call it for a long-running process holding sockets, timers, or file handles.
Call it in tests, one app per test, so timers and connections do not leak between cases.
Call it for a sub-app, widget, or route-scoped graph that unmounts while the page lives on.
A short-lived script, or a page-wide graph that ends when the tab closes, does not need it. The runtime reclaims everything. The quick start above is in that category.
stop() synchronously closes inject() across the whole app, then runs registered hooks newest-first. Later injection throws Cannot inject after the app has stopped, including cached instances and private subtrees. Capture a dependency before registering the hook:
import { bootstrapApp, provide } from 'dn-ioc'
const storeRef = provide(() => ({ closed: false }))
const serviceRef = provide(({ inject, onDispose }) => {
const store = inject(storeRef)
onDispose(async () => {
store.closed = true
})
return { read: () => inject(storeRef).closed }
})
let service!: { read: () => boolean }
const app = bootstrapApp(({ inject }) => {
service = inject(serviceRef)
})
await app.start()
service.read() // false — deferred injection is allowed while the app is running
await app.stop()
service.read() // throws Cannot inject after the app has stopped
Hook rules
A hook may be sync or async. It must resolve to nothing: void, or a Promise<void> that stop() awaits. Returning anything else is a type error. Discard a return value with braces: onDispose(() => { server.close() }).
onDispose is callable only while its own factory is running, and only before stop(). A sync factory closes that window when it returns or throws. An async factory closes it when its result settles.
Registering later throws onDispose can only be called while the factory is running, or Cannot register cleanup after the app has stopped if the app is already stopping.
Concurrent and repeated stop() calls return the same Promise and run each hook once. If a hook fails, the remaining hooks still run. One failure is rethrown unchanged. Several produce an AggregateError.
A hook must not await app.stop(). That is its own completion and would deadlock.
If start() fails, it stops the app, then rejects. A lone failure is rethrown unchanged. A startup failure plus cleanup failures produce an AggregateError. A successful start() never stops the app, and neither do runtime failures afterwards.
stop() does not wait for unfinished factories, cancel their I/O, or revoke objects you already hold. A detached factory that started before shutdown keeps running and reports through the Promise inject() returned. Request admission, task cancellation, and shutdown ordering stay with the application.
Wire stop() to the runtime
The kernel installs no listeners. Shutdown signals have no common subset across runtimes.
Runtime
Trigger
Async cleanup
Node.js, Bun
process.on('SIGINT' | 'SIGTERM', handler)
Awaited, if the handler keeps the process alive
Deno
Deno.addSignalListener('SIGINT', handler)
Awaited
Browser page
addEventListener('pagehide', handler)
Not reliable
Browser sub-app
Your own unmount call
Awaited
Web Worker
A message from the host before worker.terminate()
Only if the host waits before terminating
Serverless, edge
End of the request or invocation you scoped the app to
Depends on the platform's keep-alive API
A server on Node or Bun. The listener is registered before start(), because bootstrapApp() runs no provider yet:
import { createServer } from 'node:http'
import { bootstrapApp, provide } from 'dn-ioc'
const serverRef = provide(({ onDispose }) => {
const server = createServer().listen(3000)
onDispose(() => new Promise<void>(resolve => server.close(() => resolve())))
return server
})
const app = bootstrapApp(({ inject }) => {
inject(serverRef)
})
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
process.on(signal, () => void app.stop())
}
try {
await app.start()
} catch (error) {
console.error(error)
await app.stop()
}
The same graph on Deno only changes the listener: Deno.addSignalListener('SIGINT', () => void app.stop()).
In a browser, scope the app to something you unmount yourself, so cleanup runs while the page is still alive. Call stop() from a React effect cleanup, Vue's onScopeDispose, a custom element's disconnectedCallback, or a router leave hook.
pagehide is the least-bad unload event, and the browser may still discard the page before an async hook resolves. beforeunload is worse: the back/forward cache can skip it. If a resource must be released on unload, keep that hook synchronous.
App implements AsyncDisposable, so a scoped app can drop the explicit stop(). This needs TypeScript 5.2+, or a runtime that supports the syntax. When TypeScript downlevels it, the lookup falls back to Symbol.for('Symbol.asyncDispose'). dn-ioc implements both keys.
{
await using app = bootstrapApp(({ inject }) => {
inject(serverRef)
})
await app.start()
} // app.stop() runs when this scope exits, including on throw
Async factories share one Promise
inject() returns a synchronous value as a value, and a shared Promise for an async provider. Repeated injection in the same resolution scope reuses that Promise. A rejected provider is removed from the cache, so a later injection can retry while the app is running.
start() follows the root factory and the Promises it actually awaits or returns. Await startup dependencies inside it; keep the Promise for detached work so its result or failure remains observable. Each injection Promise tracks only its own provider, not unrelated work. See shutdown limits for what stop() does not wait for or cancel.
Import direction decides between a ref and a token
A ref carries its factory: importing the ref imports the implementation. A token carries only a type: the implementation can live in any module that imports the token. In a layered app, look at which way the imports point.
Ref
The code that injects it may import the implementation. Each MVC layer imports the one below it, so repositories, services, and controllers are all refs.
Token
The implementation lives in an outer layer that imports the inner one. A DDD domain declares its repository interface, and infrastructure implements it as an adapter. The domain declares the token; infrastructure binds the adapter to it. The same goes for any port the inner layer defines: mail, payments, a clock.
MVC: each layer imports the one below
File
Exports
Imports
models/user.ts
User
nothing
repositories/user-repository.ts
userRepositoryRef
models
services/user-service.ts
userServiceRef
repositories
controllers/user-controller.ts
userControllerRef
services
main.ts
nothing
controllers, repositories
// models/user.ts
export interface User {
email: string
name: string
}
// repositories/user-repository.ts
import { provide } from 'dn-ioc'
import type { User } from '../models/user'
export const userRepositoryRef = provide(function UserRepository() {
const table = new Map<string, User>() // Stands in for a database client.
return {
find: async (email: string) => table.get(email),
create: async (user: User) => {
table.set(user.email, user)
return user
},
}
})
// services/user-service.ts
import { provide } from 'dn-ioc'
import { userRepositoryRef } from '../repositories/user-repository'
export const userServiceRef = provide(function UserService({ inject }) {
const users = inject(userRepositoryRef)
return {
async register(email: string, name: string) {
if (!email.includes('@')) throw new Error('Invalid email')
if (await users.find(email)) throw new Error('Email taken')
return users.create({ email, name })
},
}
})
// controllers/user-controller.ts
import { provide } from 'dn-ioc'
import { userServiceRef } from '../services/user-service'
export const userControllerRef = provide(function UserController({ inject }) {
const users = inject(userServiceRef)
return {
async post(body: { email: string; name: string }) {
return { status: 201, body: await users.register(body.email, body.name) }
},
}
})
Nothing needs registering: each ref installs itself where it is first injected. main.ts lists the repository anyway, so the app holds one instance however many subtrees reach it. Do the same for any ref that holds a connection. See provide().
DDD: the domain owns the interface
File
Exports
Imports
domain/order.ts
Order, OrderRepository, orderRepositoryToken
no other layer
application/order-service.ts
orderServiceRef
domain
infra/order-repository.ts
orderRepositoryProvider
domain
infra/providers.ts
infraProviders
infra
main.ts
nothing
application, infra
The domain declares the interface and a token typed by it. It imports no other layer.
The application service injects the token. It never learns which adapter is bound.
// application/order-service.ts
import { provide } from 'dn-ioc'
import { orderRepositoryToken } from '../domain/order'
export const orderServiceRef = provide(function OrderService({ inject }) {
const orders = inject(orderRepositoryToken)
return {
async submit(id: string) {
const order = await orders.find(id)
if (!order) throw new Error(`Order ${id} not found`)
const submitted = { ...order, status: 'submitted' as const }
await orders.save(submitted)
return submitted
},
}
})
Infrastructure imports the domain and binds the token. A bundle collects its adapters.
// infra/order-repository.ts
import { provide, provideFor } from 'dn-ioc'
import { type Order, orderRepositoryToken } from '../domain/order'
// Stands in for a database client.
const tableRef = provide(() => new Map<string, Order>([['o-1', { id: 'o-1', status: 'draft' }]]))
export const orderRepositoryProvider = provideFor(orderRepositoryToken, ({ inject }) => {
const table = inject(tableRef)
return {
find: async id => table.get(id),
save: async order => {
table.set(order.id, order)
},
}
})
// infra/providers.ts
import { bundleProviders } from 'dn-ioc'
import { orderRepositoryProvider } from './order-repository'
export const infraProviders = bundleProviders(
orderRepositoryProvider,
// One line per adapter. The entry never changes.
)
The entry is the only module that imports both sides. It installs the bundle once.
Two edits, both in infrastructure: its provideFor() and one line in the bundle. Every entry already installs the bundle.
Missing binding
Inject what an entry uses inside its root factory. A missing binding then rejects start(). A token first injected later, from a request handler, fails on that request instead.
Direction
The kernel never sees imports. Enforce “the domain imports no other layer” with a lint rule.
Do not export a DDD adapter as a ref for the domain or application to import. That import points outward. Infrastructure already imports the domain’s types, so the two modules form a cycle, and every domain or application test loads infrastructure.
Tests swap implementations with provideFor()
provideFor() accepts a ref or a token, so both layouts replace a repository the same way: provideFor(userRepositoryRef, …) in MVC, provideFor(orderRepositoryToken, …) in DDD.
Install only fakes, never the real bundle. A forgotten token fake rejects start() with No provider for token: OrderRepository. A forgotten ref fake is not an error: the ref builds its real implementation.
Integration tests
List the real bundle first and the overrides after it: providers: [infraProviders, provideFor(orderRepositoryToken, …)]. Last-write-wins applies: the bundle silently replaces an override listed before it.
Names
Name a token after its interface. A ref takes its name from its factory function: provide(function OrderService(…) {…}) reports OrderService in a cycle, and an inline arrow reports <anonymous>. A minifier that renames functions changes the name.
Errors and failure propagation
Error messages
Match these messages. Do not paraphrase them.
Situation
Result
Unbound Token
No provider for token: Name
Construction-time or concurrent async cycle
Circular dependency detected: A -> B -> A
Invalid inject key
Invalid inject key received
Invalid root provider input
Invalid provider input received, thrown by bootstrapApp() before an App exists
inject after stop()
Cannot inject after the app has stopped, before cache lookup or key validation
onDispose after factory completion
onDispose can only be called while the factory is running
onDispose after stop()
Cannot register cleanup after the app has stopped
start() on a stopped app
Cannot start an app that has been stopped
Failure propagation
Nested provider inputs are validated when their subtree is first resolved. Invalid nested input throws from that inject() call; if the root does not handle it, start() rejects.
Situation
Result
Synchronous provider failure
inject() throws; the caller may catch it
Async provider failure
Its inject() Promise rejects; the caller may catch it
Root factory failure
start() rejects after registered cleanup runs
Root factory returns a value
Type error: the root factory must return void
Cleanup failure
Rejects stop(), and start() too when it triggered the stop
Public API
Signatures below omit the opaque brands on handles. Create handles with the exported functions. isProvideRef is true only for a Ref from provide(), not for a token, a binding, a bundle, or a copy.
Handles returned by token, provide, provideFor, and bundleProviders are frozen opaque objects. A copied object is rejected. This is an in-process kernel for trusted application code, not a JavaScript sandbox.
interface Token<T> {}
interface Ref<T> extends Token<T> {}
interface ProviderDef<T> {}
interface ProviderBundle {}
type RefType<T> = T extends Ref<infer U> ? U : never
type InjectKey<T> = Token<T> | Ref<T>
type ProviderInput = Ref<unknown> | ProviderDef<unknown> | ProviderBundle | readonly ProviderInput[]
type ProviderOptions = { providers?: readonly ProviderInput[] }
type InjectFn = <T>(key: InjectKey<T>) => T
type OnDisposeFn = (fn: () => void | Promise<void>) => void
interface Context {
inject: InjectFn
onDispose: OnDisposeFn
}
type Factory<T> = (ctx: Context) => T
type BootstrapAppFn = (ctx: Context) => void | Promise<void>
interface BootstrapAppOptions { providers?: readonly ProviderInput[] }
interface App extends AsyncDisposable {
start(): Promise<void> // idempotent; rejects once the app is stopped
stop(): Promise<void> // idempotent
[Symbol.asyncDispose](): Promise<void> // same operation as stop()
}
function token<T>(description?: string): Token<T>
function provide<T>(factory: Factory<T>, options?: ProviderOptions): Ref<T>
function provideFor<T>(key: InjectKey<T>, factory: Factory<T>, options?: ProviderOptions): ProviderDef<T>
function bundleProviders(...inputs: ProviderInput[]): ProviderBundle
function isProvideRef(value: unknown): value is Ref<unknown>
function bootstrapApp(fn: BootstrapAppFn, options?: BootstrapAppOptions): App