API reference
Introduction · Complete tutorial · Server recipes
Use this page to find an API and understand its role. The complete tutorial teaches the concepts with examples; the generated reference provides exact signatures, generic constraints, overloads, parameters, return types, and links to source declarations.
Generated reference
| Entry point | What it exposes |
|---|---|
di-bag | Portable facade, public types, and structured library errors. |
Start with the DiBagApi, Builder, and Container. The same builder seals a reusable Module. The reference represents these type-only exports as interfaces; construct values through DiBag.
The generated Markdown is committed alongside the source. CI compares it with fresh output and verifies public export and callable-overload coverage against the TypeScript compiler. See documentation maintenance for how to regenerate it.
API at a glance
Import DiBag and the error classes from di-bag. On Node, Bun, and Deno it detects native Promises itself; elsewhere see portable mode. The root import works on every supported runtime. Each table links to explanations and examples in the tutorial; the server guide puts them into an application.
Configure and describe services
These methods are available on DiBag and every derived facade. A provider is a reusable declaration; creating one does not acquire a service.
| Method | Result and purpose |
|---|---|
createProvider(factory, options?) | Describe a named-dependency factory; specify a factory return kind outside Node, Bun, and Deno. |
createProviderFromFunction({ dependencies, factoryFunction, ... }) | Inject positional token dependencies into a function. |
createProviderFromClass({ dependencies, serviceClass, ... }) | Adapt a constructor to positional dependencies. |
createProviderFromPlugin({ dependencies, pluginDescriptor, ... }) | Validate a selected plugin and its output. |
createToken(symbol).forService<Service>() / .forCollectionOf<Service>() | Create a single-service or collection token. |
withConfiguration(options) | Return a facade with inherited runtime settings and appended lifecycle observers. |
optional(token) | Supply undefined when a positional token dependency is unregistered. |
lazy(token) | Supply a function that resolves a positional token dependency when called. |
createBuilder() | Create an immutable builder for a container or module. |
providerWithDisposal({ provider, disposeService }) | Give the container ownership of this provider's acquired value. |
providerWithLifetime({ provider, lifetime }) | Choose singleton, scoped, or transient caching; scoped is the default. |
providerWithRegistrationMetadata({ provider, registrationMetadata }) | Attach metadata available without acquiring the service. |
providerWithAcquisitionMetadata({ provider, callbackReceives, describeAcquisition }) | Append one synchronous acquisition-metadata frame. |
providerWithTransformedService({ provider, callbackReceives, transformService }) | Project an exposed service while retaining its ownership and graph contracts. |
Build and reuse a graph
Builder operations return a new builder. Keep the returned value or chain the next call; they do not mutate the original.
| Method | Available on | Purpose |
|---|---|---|
withServices(providersByName) | Builder | Add new string-named providers. |
withTokenService(token, provider) | Builder | Bind a single-service token. |
withServiceAlias({ aliasKey, targetServiceKey }) | Builder | Add another lookup name for a service. |
withCollectionContribution({ collectionToken, provider }) | Builder | Append an ordered collection contribution. |
withReplacedService(serviceKey, provider) | Builder | Replace an existing binding with a compatible provider. |
withInstalledModules(modules) | Builder | Install sealed modules in list order. |
verifyGraphAtCompileTime() | Builder | Report an incomplete graph through its TypeScript return type. |
buildModule({ exportedServiceKeys, moduleLabel? }) | Builder | Seal public exports; unmet dependencies become module requirements. |
buildContainer() | Builder | Check graph completeness and create a lazy owning container. |
moduleLabel | Sealed Module | Read the exact optional label supplied at sealing without acquiring a service; rename views preserve it. |
withRenamedExport({ currentExportKey, newExportKey }) | Sealed Module | Return a module view with a renamed string export. |
withRenamedRequirement({ currentRequirementKey, newRequirementKey }) | Sealed Module | Return a module view that asks its host for a renamed string requirement. |
There is one builder. buildContainer() requires a complete graph; buildModule() records unmet dependencies as requirements. Modules do not resolve services or have a close method. Each installation allocates fresh private bindings.
Use and close a container
For each server request, create a child container, resolve its services, then close it after the response. Unmarked providers are scoped to each container.
| Method | Purpose |
|---|---|
resolve(serviceKey) | Lazily acquire a single service with its inferred return type. |
resolveCollection(token) | Resolve ordered contributions as a frozen readonly list. |
serviceSnapshot(serviceKey) | Inspect service or collection metadata and acquisition state without acquiring anything. |
graphSnapshot() | Describe every binding, module installation, and dependency edge observed so far. |
createChildContainer(options?) / createChildContainer(keys, providers, options?) | Create a tracked child container with optional sharing and checked scoped or transient replacements. |
createIndependentContainer() / createIndependentContainer(keys, providers) | Create an independent container with fresh instances and optional checked replacements. |
ensureServicesReady(serviceKeys, options?) | Wait for selected services to become ready. |
close(options?) | Stop resolutions, drain work, and dispose owned resources; a timed or aborted wait can be cancelled. |
Errors and recovery
Each library error code names a kind of failure, while details.operation names the method where it occurred. The errors page lists all codes and compile-time messages. Catch specialized error classes with instanceof when choosing a recovery path.
| Error | When it appears | Public information |
|---|---|---|
DiBagDisposalError | close() attempted every disposer and one or more failed. | failures records each binding label and original error. |
DiBagServiceReadinessError | ensureServicesReady() could not make a selected service ready. | cause, disposalFailures, and disposalError retain the failure and disposal outcome. |
DiBagServiceReadinessCancelledError | An abort signal or timeout stopped a readiness wait. | reason, details.acquisitionsStillPending, and disposalPromise describe the cancellation and eventual disposal. |
DiBagCloseCancelledError | An abort signal or timeout stopped a close() wait. | details lists pending work; disposalPromise settles when disposal finishes. |
DiBagPluginValidationError | A plugin descriptor or acquired output failed validation. | phase identifies the boundary and reason describes the rejection. |
For a container whose disposer fails:
import { DiBag, DiBagDisposalError } from 'di-bag';
const app = DiBag.createBuilder().withServices({
resource: DiBag.providerWithDisposal({
provider: () => ({ name: 'example' }),
disposeService: () => { throw new Error('disposal failed'); },
}),
}).buildContainer();
app.resolve('resource');
try {
await app.close();
} catch (error) {
if (error instanceof DiBagDisposalError) {
for (const failure of error.failures) {
console.error(failure.bindingLabel, failure.error);
}
}
throw error;
}Factory errors and transformation errors retain their original identity on resolution. Library-created failures expose stable DI_BAG_* codes and frozen structured details; inspect those fields instead of parsing message text. Observer callback failures are delivered to the observer's onObserverFailure callback and do not become service or shutdown failures. DI_BAG_INVALID_DEPENDENCY_ACCESS reports enumeration or in checks on a factory's dependency object; its details.consumer names the factory.
Exported TypeScript types
All names in this section are type-only exports from di-bag. Use import type for them. They provide annotations and preserve contracts in generated declarations; they do not provide unchecked runtime constructors.
For application code, prefer inferred values and typeof or ReturnType when passing a graph across a module boundary:
import { DiBag, type ProviderOutput, type TokenService } from 'di-bag';
const clockSymbol = Symbol('clock');
const clock = DiBag.createToken(clockSymbol).forService<{ now(): number }>();
const stamp = DiBag.createProviderFromFunction({
dependencies: [clock],
factoryFunction: source => source.now(),
});
const app = DiBag.createBuilder()
.withTokenService(clock, () => ({ now: () => 42 }))
.withServices({ stamp })
.buildContainer();
type Clock = TokenService<typeof clock>;
type Stamp = ProviderOutput<typeof stamp>;
type Application = typeof app;
await app.close();These names refer to the clock, stamp provider, and app in the tutorial's typed-token example. Inferred types retain private-consumer, token, lifetime, and ownership contracts.
Application-facing types
| Exports | Purpose |
|---|---|
DiBagApi | The complete DiBag method surface, including configured and observed facades. |
ConfigurationOptions | Runtime classification and observer options for withConfiguration. |
Builder, Container | A checked immutable builder and a resolving, owning container. |
Module | A sealed export view of a builder graph, installable in other builders. |
ModuleOptions | Optional non-empty moduleLabel for naming private bindings; labels are descriptive and may repeat or contain /. |
ProviderOrFactory | Accepted provider or factory shapes. |
Provider | A provider description retaining its factory, metadata, frames, graph contracts, and acquired-value type. |
FactoryReturnKind, RuntimeOptions | Factory return-kind literals and the isNativePromise configuration callback. |
Lifetime | Singleton, scoped, and transient caching choices; scoped is the default. |
FactoryContext, ContextualFactory, DisposerContext | Factory cancellation, contextual factory, and disposal callback contracts. |
EnsureServicesReadyOptions | Optional abortSignal, totalTimeoutMs, and maxConcurrentServiceKeys fields for ensureServicesReady. |
CloseOptions, CloseProgress | Close wait controls and pending work reported after cancellation. |
CreateChildContainerOptions, CreateIndependentContainerOptions | Checked selections accepted when deriving child and independent containers. |
Token, TokenBase, TokenKey, TokenKind, TokenService | Single-service token identity, common handle, kind, and key/service projections. |
CollectionToken, CollectionTokenBase, CollectionItem | Collection token identity and the type of one contribution. |
OptionalDependency, LazyDependency, DependencyReference | The token reference forms accepted in positional dependency tuples. |
PositionalFactoryArguments, PositionalFactoryFunction | Positional argument compatibility and callback signatures for function/constructor adaptation. |
Presence | { isPresent: false } or { isPresent: true, value }, including a present undefined value. |
AcquisitionMetadataPresence, AcquisitionSnapshot, RegistrationSnapshot | Inspection frames, acquisition state, and registration metadata snapshots. |
GraphSnapshot, BindingSnapshot, ModuleInstallationSnapshot | The frozen graph description, per-binding origin, and installation records with parent IDs. |
DisposalFailure | The detached acquisition identity, label, and original disposal error. |
DiBagErrorCode, DiBagDiagnostic | Stable library error codes and their structured diagnostic fields. |
LifecycleObserver, ObserverCallback, ObserverErrorCallback | Observer configuration and its event/failure callbacks. |
LifecycleEvent, ObserverFailure, ContainerEventFields, AcquisitionEventFields | Discriminated lifecycle events and observer failure context. |
PluginReturnKind, CreateProviderFromPluginOptions, PluginOutputValidator, PluginProvider | Plugin return policy, validation options, output predicate, and resulting provider. |
CreateProviderFromPlugin | The callable type of DiBag.createProviderFromPlugin; use it directly as a type. |
CompositionReport | The compile-time verdict for a builder: void when buildable, otherwise the buildContainer() failure with details. |
DiBagPolicy | Empty interface for project-wide compile-time switches; augment with structuralThenables: 'allow' to relax the thenable check. |
Provider and module projections
| Exports | Purpose |
|---|---|
ProviderFactory, ProviderOutput, ProviderAcquiredValue, ProviderNamedDependencies | Extract the factory, exposed result, acquired value, and named requirements from a registration. Output and acquired value can differ across async boundaries. |
ProviderRegistrationMetadata, ProviderAcquisitionMetadata | Extract static metadata and the tuple of acquisition metadata frames. |
ProviderGraphContract | Retain a provider's token and other graph obligations. |
ProviderRequiredTokens, ProviderOptionalTokens, ProviderCollectionTokens | Extract required/lazy, optional, and collection token requirements. |
ModuleExportedServices, ModuleRequiredServices | Extract the readonly service exports and external requirements of a sealed module. |
ModuleConstraints | Compute retained private-consumer and lifetime constraints for a registration map and public selection. |
SealedConstraints, ModuleSealedConstraints | Rebase constraints retained from installed modules when a builder seals; the complete constraint set of a sealed module. |
PublicProviders, ModulePublicProviders | Preserve provider contracts when projecting public module registrations. |
Renamed | Represent the checked renaming of a module's public view. |
Graph composition support types
These exports support reusable generic helpers and portable declaration output. Most applications can let the builder infer them. They express compile-time contracts; they do not perform runtime validation.
| Exports | Purpose |
|---|---|
ServicesOf | Map providers to their exposed service types. |
RegistrationEntries, RegistrationsFromEntries | Convert between a registration map and its entry representation. |
OverrideRegistrations, SelectedRegistrations | Model merged registration maps and selected override registrations. |
CheckDependencyCompatibility, CheckDependencyCompleteness | Check dependency shape compatibility and graph completeness. |
Selection, Overrides, OverrideFactoryContext | Validate selections and replacement compatibility while preserving contextual inference. |
TokenBinding, TokenMember, TokenDependencyContract | Retain typed bindings, validate token membership, and represent token obligations. |
CollectionTokenMember, SingleServiceTokenMember | Check collection and single-service token membership. |
ReboundProviders, ReboundSelection, SelectionKey | Preserve token bindings across replacement and map selections to their string/symbol keys. |
AliasRegistration, AliasEntries, AliasOutput | Model an alias registration, its graph entries, and its exposed result. |
Contribution, ContributionConstraint | Describe an ordered contribution and its retained requirements. |
ModuleContributions, ModuleContributionConstraints | Preserve contributions and their requirements in modules. |
BuilderWithCollectionContribution | The checked collection-contribution callable on the builder. |
BuilderBuildModule, BuilderWithInstalledModules, BuilderWithReplacedService | Checked module sealing, installation, and replacement call signatures. |
BuilderWithServiceAlias, BuilderWithServices, BuilderWithTokenService | Checked alias and service registration call signatures. |
DisjointChildContainerSelection | Enforce separate override and sharing selections. |
UnsharedAliases, ScopedAliases, SharedAliasProviders | Preserve alias contracts as child containers inherit or explicitly share services. |
CanonicalLifetime, LifetimeObligation, Reach | Normalize lifetimes and retain compact module lifetime obligations. |
CheckedLifetimes, CheckedChildContainerLifetimes, ChildReplacementAdmission | Check singleton capture and child replacement compatibility. |
The authoritative export list is src/index.ts. Internal helpers in other source files are not package exports.
Boundaries
- Token maps and dependency parameters must have finite string keys. Index signatures, including open template keys, cannot prove that tokens exist.
- Containers are created through checked builders and independent containers.
Containeris exported as a type only; there is no public unchecked constructor. - Parameters may be omitted or be a single object type. Optional dependency properties still require providers. Union, callable, and symbol-keyed dependency parameter types are rejected.
- Dependency proxies support named property reads. Do not enumerate, spread, or use rest destructuring on them: parameter types are erased at runtime, so the container cannot enumerate a particular factory's declared requirements.
- Use a single, explicit factory signature. TypeScript utility types see the last signature of overloaded functions; arbitrary overload behavior cannot be inferred. As with other TypeScript APIs, casts and unchecked JavaScript can bypass compile-time checks; runtime resolution still checks missing tokens.
- JavaScript output targets ES2022. The CommonJS package supports Node
requireand ESM named imports, and browsers through a bundler. Bun is only needed to run the development tests. The supported compiler floor and development type checks use TypeScript 6.0.3.
Usage topics
The detailed examples live in the complete tutorial. These links also preserve existing bookmarks into the earlier combined guide.