@codefast/di 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CHANGELOG.md +192 -0
  2. package/README.md +142 -43
  3. package/dist/ambient-container.d.ts +46 -0
  4. package/dist/ambient-container.js +72 -1
  5. package/dist/container/binding-chain.js +3 -3
  6. package/dist/container/container.d.ts +41 -30
  7. package/dist/container/container.js +59 -243
  8. package/dist/container/introspect.d.ts +47 -0
  9. package/dist/container/introspect.js +53 -0
  10. package/dist/core/binding-builders.d.ts +27 -3
  11. package/dist/core/binding-declaration.d.ts +2 -2
  12. package/dist/core/binding-declaration.js +4 -4
  13. package/dist/core/module.d.ts +4 -25
  14. package/dist/core/module.js +3 -27
  15. package/dist/core/state-epoch.d.ts +1 -1
  16. package/dist/core/state-epoch.js +1 -1
  17. package/dist/core/types.d.ts +16 -7
  18. package/dist/decorators/inject.d.ts +3 -1
  19. package/dist/decorators/inject.js +27 -22
  20. package/dist/decorators/injectable.d.ts +14 -18
  21. package/dist/decorators/injectable.js +23 -2
  22. package/dist/decorators/lifecycle.d.ts +9 -3
  23. package/dist/decorators/lifecycle.js +5 -1
  24. package/dist/errors.d.ts +33 -15
  25. package/dist/errors.js +41 -21
  26. package/dist/index.d.ts +9 -8
  27. package/dist/index.js +4 -3
  28. package/dist/injection/dependency-slot.d.ts +17 -0
  29. package/dist/injection/dependency-slot.js +46 -0
  30. package/dist/injection/descriptor.d.ts +9 -3
  31. package/dist/injection/descriptor.js +10 -1
  32. package/dist/introspection/explanation.js +26 -8
  33. package/dist/introspection/validation.d.ts +28 -0
  34. package/dist/introspection/validation.js +244 -0
  35. package/dist/lifecycle/hooks.d.ts +13 -2
  36. package/dist/lifecycle/hooks.js +36 -18
  37. package/dist/lifecycle/scopes.d.ts +21 -2
  38. package/dist/lifecycle/scopes.js +86 -2
  39. package/dist/metadata/keys.d.ts +1 -1
  40. package/dist/metadata/keys.js +1 -1
  41. package/dist/resolution/cache/class-introspector.d.ts +7 -8
  42. package/dist/resolution/cache/class-introspector.js +40 -3
  43. package/dist/resolution/cache/lookup.d.ts +10 -0
  44. package/dist/resolution/cache/lookup.js +27 -0
  45. package/dist/resolution/context.d.ts +12 -12
  46. package/dist/resolution/path.d.ts +12 -2
  47. package/dist/resolution/path.js +22 -2
  48. package/dist/resolution/plan/codegen.d.ts +2 -1
  49. package/dist/resolution/plan/codegen.js +1 -1
  50. package/dist/resolution/plan/compiler.d.ts +6 -6
  51. package/dist/resolution/plan/compiler.js +152 -22
  52. package/dist/resolution/resolver.d.ts +6 -0
  53. package/dist/resolution/resolver.js +39 -84
  54. package/package.json +11 -3
package/CHANGELOG.md CHANGED
@@ -1,5 +1,197 @@
1
1
  # @codefast/di
2
2
 
3
+ ## 0.14.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#1101](https://github.com/codefastlabs/codefast/pull/1101) **Breaking:** an auto-register registry is now a `SyncModule`, and `Container#loadAutoRegistered` is removed.
8
+ `createAutoRegisterRegistry(name)` takes the module's display name, and the registry loads like any other module —
9
+ deduplicated by identity, ref-counted, and torn down by `unload()` / `unloadAsync()`, which deactivates every singleton
10
+ it bound. `loadAutoRegistered` was a bare bind loop: it could not be unloaded, and a second call rebound the whole set
11
+ over the first.
12
+
13
+ Migrate:
14
+
15
+ ```ts
16
+ // before
17
+ const registry = createAutoRegisterRegistry();
18
+ const count = container.loadAutoRegistered(registry);
19
+
20
+ // after
21
+ const registry = createAutoRegisterRegistry("app:Services");
22
+ container.load(registry); // or Container.fromModules(registry)
23
+ const count = registry.entries().length; // if you used the returned count
24
+ ```
25
+
26
+ A load binds the classes registered by then; a second `load()` of the same registry only adds a reference, so a class
27
+ decorated after the first load is bound by unloading the registry to zero and loading it again.
28
+
29
+ - [#1119](https://github.com/codefastlabs/codefast/pull/1119) **Breaking (types only):** three places the types let through what the library then did wrong or rejected late.
30
+
31
+ - `@injectable()` with no deps now compiles only on a class whose constructor needs nothing. It used to accept a class
32
+ with required parameters — a subclass inheriting its base's constructor included — and build it with those parameters
33
+ left `undefined`, silently. List the deps, as `@injectable([...])`.
34
+ - A `ModuleBuilder` and an `AsyncModuleBuilder` now narrow slot names as a container does: `whenNamed` inside
35
+ `Module.create` took any string. A container and both builders bind through one new `Binder` interface, so the three
36
+ can no longer drift apart.
37
+ - `toSelf()` exists only on a chain whose key is a class (`ClassBindToBuilder`); on a token it was accepted by the
38
+ compiler and threw `SelfBindingRequiresClassError` at runtime. An untyped caller still gets that error.
39
+
40
+ `Binder` and `ClassBindToBuilder` are exported from the package root. Runtime behaviour is unchanged.
41
+
42
+ - [#1101](https://github.com/codefastlabs/codefast/pull/1101) **Breaking:** `Container#dispose()` is renamed `disposeAsync()`. It returns a `Promise`, so the bare name broke the
43
+ package's own rule — unqualified is sync, the `Async` suffix is async — and the spec carried an exception for it that is
44
+ now gone. `disposeAsync` is the name TC39's `AsyncDisposableStack` gives the same method, and `[Symbol.asyncDispose]()`
45
+ still delegates to it, so `await using` is unchanged. Replace `await container.dispose()` with
46
+ `await container.disposeAsync()`; an `AggregateError` from a teardown with several throwing hooks now reads
47
+ "disposeAsync() completed, but deactivation hooks threw".
48
+
49
+ - [#1094](https://github.com/codefastlabs/codefast/pull/1094) **Breaking:** the `ContainerInterface` type export is removed. It aliased the `Container` interface, which `Container`
50
+ already exports under its own name beside the value, so replace `ContainerInterface` with `Container`.
51
+
52
+ - [#1063](https://github.com/codefastlabs/codefast/pull/1063) **Breaking:** `validate`, `inspect`, `lookupBindings`, `explain` and `generateDependencyGraph` are functions that take
53
+ the container instead of `Container` methods, so a bundle that only binds and resolves leaves them out: importing
54
+ `Container` and `token` alone drops from 23.2 KB to about 20.6 KB gzipped. `has` and `hasOwn` stay methods. Replace
55
+ `container.validate()` with `validate(container)`, `container.explain(token, options)` with
56
+ `explain(container, token, options)`, and likewise for the other three, importing each from `@codefast/di`. They refuse
57
+ a disposed container with `DisposedContainerError` as the methods did, and an object `Container` did not create with a
58
+ `TypeError`.
59
+
60
+ - [#1120](https://github.com/codefastlabs/codefast/pull/1120) **Breaking:** two spellings of the same API collapse into one.
61
+
62
+ - `Module` is the one module factory: `Module.create`, `Module.createAsync` and `Module.fromBindings`. The
63
+ `SyncModule.create`, `SyncModule.fromBindings` and `AsyncModule.create` companions are removed; `SyncModule` and
64
+ `AsyncModule` remain as the types those factories return. Replace `SyncModule.create(` with `Module.create(`,
65
+ `SyncModule.fromBindings(` with `Module.fromBindings(` and `AsyncModule.create(` with `Module.createAsync(`.
66
+ - `optional()` is renamed `injectOptional()`, so the descriptor family reads as the resolve family does —
67
+ `inject`/`injectOptional`/`injectAll` beside `resolve`/`resolveOptional`/`resolveAll`. Replace `optional(` with
68
+ `injectOptional(`.
69
+
70
+ - [#1111](https://github.com/codefastlabs/codefast/pull/1111) **Breaking:** a root-level `resolveAll` / `resolveAllAsync` with no options now hands every caller the same memoized
71
+ list while the chain and its activation hooks are unchanged, instead of a fresh copy per read. The result was already
72
+ typed `ReadonlyArray`; it is now read-only in fact, and a caller that needs a list of its own copies it (`[...list]`).
73
+ Dropping the copy reads `resolve-all-strategies-10` +22%, `resolve-all-strategies-100` +67% and
74
+ `production-event-bus-dispatch` +32% in a paired run, with the cold collection rows and the canaries level.
75
+
76
+ - [#1068](https://github.com/codefastlabs/codefast/pull/1068) Lower the Node.js floor from 24 to the lowest release the package, its dependencies and its full test suite run on:
77
+ 22.12 for `@codefast/cli` and `@codefast/tailwind-variants`, 22.18 for `@codefast/di` and `@codefast/di-testing`, and
78
+ 22.22.2 for `@codefast/theme`, `@codefast/tracking` and `@codefast/ui`. Each floor is type-checked against what Node 22
79
+ ships and proven by running the package's tests on that release in CI.
80
+
81
+ ### Patch Changes
82
+
83
+ - [#1110](https://github.com/codefastlabs/codefast/pull/1110) An `@inject` accessor now compiles into its class's instantiation plan, like a constructor parameter: the plan resolves
84
+ it before `new` and the accessor's `init` takes the value, instead of each accessor resolving again through the
85
+ container as the instance initializes. An accessor-injected class may now sit anywhere in a plan, not only at its root.
86
+ `@inject` returns an `init` rather than adding an initializer that writes through `context.access.set`, so the value is
87
+ the field's initial value. A standalone probe built with `tsc` puts one accessor at 46 ns → 31 ns per resolve and two at
88
+ 59 ns → 41 ns; a paired run reads `accessor-injection-construct` +26%, with the canaries level. A custom
89
+ `MetadataReader`'s accessor records are not prepared, so such a class keeps resolving its accessors itself.
90
+
91
+ - [#1113](https://github.com/codefastlabs/codefast/pull/1113) An `@inject`-accessor class now compiles into an async plan too, so `resolveAsync` stops interpreting it on every call.
92
+ The plan keeps the interpreted async lane's order: the constructor params settle first, then the accessors resolve on
93
+ the sync lane and the class constructs. A standalone probe puts `resolveAsync` of a one-accessor class at 120 ns → 78
94
+ ns, against 66 ns for the same class taking its dependency as a constructor param.
95
+
96
+ - [#1091](https://github.com/codefastlabs/codefast/pull/1091) The `ResolutionContext` a factory or activation hook receives narrows `name` to the slot names its token declares, as
97
+ `Container#resolve` already did: inside `toDynamic((ctx) => ctx.resolve(LoggerToken, { name: "fiel" }))`, a name the
98
+ token does not declare is now a compile error instead of a `NoMatchingBindingError` at resolve time. A token that
99
+ declares no names, and a class key, still take any string.
100
+
101
+ - [#1100](https://github.com/codefastlabs/codefast/pull/1100) The README writes `validate`, `inspect` and the other introspection functions as the free functions they are —
102
+ `validate(container)` rather than a method-style `validate()` — and notes that guarding `validate(container)` with a
103
+ dev-only check keeps the introspection code out of a production bundle.
104
+
105
+ - [#1121](https://github.com/codefastlabs/codefast/pull/1121) Three code samples still imported a name the previous release removed or renamed: the README's decorator sample and the
106
+ decorators spec imported `optional` while calling `injectOptional`, and the modules spec imported `SyncModule` while
107
+ calling `Module.create`. They import what they call now.
108
+
109
+ - [#1116](https://github.com/codefastlabs/codefast/pull/1116) The foundation-types spec now documents the helpers a custom `when()` constraint reads a frame's `slot.keyMask` with —
110
+ `tagKeyMaskOf`, `coversTagKeys` and `NO_TAG_KEYS`, the ones the built-in tag constraints use — with an example that
111
+ rules a parent out by its tag keys before comparing any value.
112
+
113
+ - [#1115](https://github.com/codefastlabs/codefast/pull/1115) `DiError.code` is now typed as `DiErrorCode`, a union of every code the library throws, exported from the package root,
114
+ so a `switch (error.code)` is checked by the compiler and a misspelled code no longer compiles. An
115
+ `AsyncActivationError` raised by a `@postConstruct` hook now names the token it was building —
116
+ `@postConstruct method 'init' of 'app:Cache' returned a Promise` — where it named only the method.
117
+
118
+ - [#1065](https://github.com/codefastlabs/codefast/pull/1065) `inspect` and `lookupBindings` read the container's inspector directly instead of building an internals object and the
119
+ ancestor-registry list on every call, so they cost what the methods did before they became functions. A paired run
120
+ against the method-shaped build reads `lookup-bindings` at −2% and `inspect-snapshot` at −4%, from −13% and −9%.
121
+
122
+ - [#1117](https://github.com/codefastlabs/codefast/pull/1117) The README's toolchain table lists Bun 1.4.3 or later as needing nothing: its transpiler lowers standard decorators and
123
+ supplies their metadata without `Symbol.metadata`. Bun 1.4.2 and earlier still inject the wrong values into a module
124
+ holding two decorated classes; 1.4.3 fixes that, checked with two accessor-injected and two constructor-injected classes
125
+ in one module, run directly and after `bun build`.
126
+
127
+ - Move three cold paths out of the resolver to the modules they belong to: a class's constructor-parameter settle (and its
128
+ `MissingMetadataError`) to the class introspector, a root collection's stable-value check beside its memo in
129
+ `resolution/cache/lookup`, and `validate`'s miss check to `introspection/validation`, which reads the chain through the
130
+ new `DependencyResolver.bindingsForValidate()` in place of `missForValidate()`. `ARCHITECTURE.md` replaces the
131
+ resolver's line budget with the rule for what `resolution/resolver.ts` holds.
132
+
133
+ - [#1067](https://github.com/codefastlabs/codefast/pull/1067) Every dependency slot the engine resolves now has one shape: a class's parameters are copied once when they are settled,
134
+ and a factory's dependencies when it is bound or declared, each with its resolve options and criterion already filled. A
135
+ process that has resolved many kinds of slot no longer meets the cold class lane megamorphic, so booting an application
136
+ gets faster where it was slowest — `app-boot-40` +13%, `realistic-graph-class-cold-resolve` +16% and the interpreted
137
+ `slot-injected-*` rows +31% in a paired run — with the warm rows level.
138
+
139
+ - [#1093](https://github.com/codefastlabs/codefast/pull/1093) The six resolve methods are declared once, on a new exported `Resolver` interface that both `Container` and
140
+ `ResolutionContext` extend, so a call through a factory's `ctx` can never again narrow a token's slot names differently
141
+ from the same call on the container. Types only: the emitted JavaScript is unchanged.
142
+
143
+ - [#1101](https://github.com/codefastlabs/codefast/pull/1101) A sync `unbind()`, `unbindAll()`, `rebind()` or `unload()` that meets an async deactivation hook now runs every
144
+ deactivation stage of that instance — container `onDeactivation` hooks, the binding's own `onDeactivation`, then each
145
+ `@preDestroy()` — before it throws `AsyncDeactivationError`. It used to stop at the first stage that returned a promise,
146
+ and since the binding was already removed, the stages after it could never run. The error is still thrown, and each
147
+ returned promise is still left unawaited with its rejection swallowed, so use `unbindAsync()` / `unloadAsync()` wherever
148
+ a deactivation hook may be async.
149
+
150
+ - [#1109](https://github.com/codefastlabs/codefast/pull/1109) `validate`, `explain` and `generateDependencyGraph` read a container's internals from an object built once per container
151
+ instead of rebuilding it, with the ancestor-registry list, on every call. `validate` also walks the container's bindings
152
+ once rather than twice and allocates nothing for a container with no container-level hooks, so it costs less than the
153
+ `container.validate()` method did in 0.13.0.
154
+
155
+ ## 0.13.0
156
+
157
+ ### Minor Changes
158
+
159
+ - [#1022](https://github.com/codefastlabs/codefast/pull/1022) **Breaking:** `Container` no longer declares `[Symbol.dispose]`, and `SyncDisposalNotSupportedError` is removed. A
160
+ deactivation hook may be async, so a container disposes through `await using` or `dispose()` only, and a synchronous
161
+ `using` on one is now a compile error instead of a `SyncDisposalNotSupportedError` at runtime. Replace `using` with
162
+ `await using`, and drop any `instanceof SyncDisposalNotSupportedError` check.
163
+
164
+ - [#1024](https://github.com/codefastlabs/codefast/pull/1024) **Breaking:** `@postConstruct()` and `@preDestroy()` now reject a private (`#name`) method, as they already rejected a
165
+ static or symbol-keyed one. The lifecycle manager calls a hook by name on the instance, so a private hook passed
166
+ `validate()` and then failed at resolve with an `InvalidMetadataError` that blamed the metadata reader, or at
167
+ `dispose()` for `@preDestroy()`. Decorating one now throws the new `PrivateLifecycleMethodError` when the class is
168
+ defined. The decorators' types also accept only a public, instance, string-named method, and `@inject` only an instance
169
+ accessor, so TypeScript reports all of these at the decoration site (TS1240, TS1241). To run private code from a hook,
170
+ call it from a public one.
171
+
172
+ - [#1022](https://github.com/codefastlabs/codefast/pull/1022) `TokenNotBoundError` and `NoMatchingBindingError` now carry `path`: the token names from the outermost request down to
173
+ the one that missed, alias hops included. A miss below the token asked for ends its message with that path —
174
+ `Path: UserService → UserRepository → Database → app:Logger` — so a deep graph says which consumer needed the binding; a
175
+ miss on the token asked for keeps its message as it was. Every lane reports the same path: sync and async, generated
176
+ plans, factory bodies, and `explain()` for an ancestor that selects nothing.
177
+
178
+ - [#1022](https://github.com/codefastlabs/codefast/pull/1022) **Breaking:** a `scoped` instance is now deactivated with the child container that cached it. Disposing that child runs
179
+ the binding's `onDeactivation`, the container-level `onDeactivation` hooks of the container that owns the binding, and
180
+ `@preDestroy()` for every scoped instance it cached, latest first and before its own singletons; unbinding a scoped
181
+ binding on the child that cached it deactivates that instance too. `.scoped()` now offers `onDeactivation`, and
182
+ `Module.fromBindings` accepts `onDeactivation` with `scope: "scoped"`, so per-request resources — a transaction, a
183
+ connection — can be released where they are declared. `validate()` no longer reports a deactivation hook on a
184
+ scoped-only token as unreachable. Code that relied on a scoped instance never being torn down, or that closed one by
185
+ hand after `dispose()`, should drop the manual close.
186
+
187
+ - [#1022](https://github.com/codefastlabs/codefast/pull/1022) **Breaking:** `validate()` now throws the error `resolve()` would for a singleton graph that cannot resolve — a required
188
+ dependency nothing binds (`TokenNotBoundError`), a slot nothing matches (`NoMatchingBindingError`), or a cycle
189
+ (`CircularDependencyError`) — with the path from that singleton down to the problem. A parent-owned singleton reached
190
+ from a child is now read from the parent's chain, as `resolve` reads it. It still leaves alone what it cannot decide: a
191
+ transient or scoped consumer, whose dependencies a child container may bind, and a request only a `when()` candidate
192
+ matches. A container that passed `validate()` while holding such a graph now fails it; bind the missing dependency, or
193
+ mark it `optional()` when it may be absent.
194
+
3
195
  ## 0.12.0
4
196
 
5
197
  ### Minor Changes
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @codefast/di
2
2
 
3
- Lightweight, type-safe dependency injection for TypeScript applications, built on TC39 Stage 3 decorators with no
3
+ Type-safe dependency injection for TypeScript applications, with zero dependencies, built on standard decorators with no
4
4
  `reflect-metadata` and no `experimentalDecorators`.
5
5
 
6
6
  [![npm version](https://img.shields.io/npm/v/@codefast/di)](https://www.npmjs.com/package/@codefast/di)
@@ -20,12 +20,12 @@ its keep as the dependency graph grows.
20
20
 
21
21
  - **Typed tokens.** `Token<Value>` flows through every `bind → resolve` path, so `resolve()` returns exactly the type
22
22
  you registered.
23
- - **Native Stage 3 decorators.** `@injectable`, `inject`, `optional`, `injectAll`, `@postConstruct`, and `@preDestroy`
23
+ - **Standard decorators.** `@injectable`, `inject`, `injectOptional`, `injectAll`, `@postConstruct`, and `@preDestroy`
24
24
  declare dependencies explicitly — no runtime reflection.
25
25
  - **Fluent bindings.** Constants, classes, sync and async factories, aliases, named/tagged/predicate constraints, and
26
26
  lifecycle hooks compose in one invariant chain order.
27
- - **Scopes with validation.** Choose `singleton`, `scoped`, or `transient`, and call `validate()` to catch captive
28
- dependencies before the first request.
27
+ - **Scopes with validation.** Choose `singleton`, `scoped`, or `transient`, and call `validate(container)` to catch
28
+ captive dependencies, missing bindings and cycles before the first request.
29
29
  - **Modules and introspection.** Bundle bindings into reusable modules, and inspect a container or render its dependency
30
30
  graph as DOT, Mermaid, Cytoscape, or React Flow.
31
31
 
@@ -35,14 +35,82 @@ its keep as the dependency graph grows.
35
35
  pnpm add @codefast/di
36
36
  ```
37
37
 
38
- `@codefast/di` runs on Node.js 24 or later and in Chrome and Edge 136, Firefox 136, or Safari 18.4 or later
39
- ([support policy](../../SUPPORT.md#browsers)). It requires TypeScript 7 or later, with native Stage 3 decorators. Leave
40
- `experimentalDecorators` off — it's off by default. Its declarations use explicit resource management, which no numbered
41
- `lib` declares yet, so your program needs those types: `@types/node` 24 or later loads them, and any other program adds
38
+ `@codefast/di` runs on Node.js 22.18 or later and in Chrome and Edge 136, Firefox 136, or Safari 18.4 or later
39
+ ([support policy](../../SUPPORT.md#browsers)). It requires TypeScript 7 or later, with standard decorators. Leave
40
+ `experimentalDecorators` off — it's off by default. A browser program also needs the
41
+ [disposal types](#explicit-resource-management-types).
42
+
43
+ The package is published on 0.x and versioned on its own track: breaking changes ship as minor versions, so pin the
44
+ minor version when you need stability.
45
+
46
+ ### Toolchain
47
+
48
+ No JavaScript engine runs decorators natively yet — the TC39 proposal went back to Stage 2.7 in May 2026 — so a
49
+ decorated class always passes through a transform that lowers it. What that takes depends on the toolchain:
50
+
51
+ | Toolchain | What it needs |
52
+ | ------------------------- | ----------------------------------------------------------------------------------------------------------- |
53
+ | tsx | Nothing: it lowers standard decorators for the Node it runs on. |
54
+ | Bun 1.4.3 or later | Nothing: its transpiler lowers standard decorators, and supplies their metadata without `Symbol.metadata`. |
55
+ | esbuild | A `target` below `esnext`, such as `es2024` or `node24`: at its default, `esnext`, decorators pass through. |
56
+ | Vite 8, and Vitest on it | The Babel decorators plugin: their Oxc transform lowers only `experimentalDecorators`. |
57
+ | SWC 1.15.21 or later | `jsc.parser.decorators: true` and `jsc.transform.decoratorVersion: "2023-11"`. |
58
+ | `tsc`, then Node directly | A `target` below `ESNext`, and `Symbol.metadata` installed before any decorated class is defined. |
59
+
60
+ For Vite and Vitest, add `@babel/core`, `@babel/plugin-proposal-decorators` and `@rolldown/plugin-babel` as dev
61
+ dependencies, then the decorators preset to the config — `vitest.config.ts` takes the same one:
62
+
63
+ ```ts
64
+ // vite.config.ts
65
+ import babel, { defineRolldownBabelPreset } from "@rolldown/plugin-babel";
66
+ import { defineConfig } from "vite";
67
+
68
+ export default defineConfig({
69
+ plugins: [
70
+ babel({
71
+ presets: [
72
+ defineRolldownBabelPreset({
73
+ preset: () => ({ plugins: [["@babel/plugin-proposal-decorators", { version: "2023-11" }]] }),
74
+ // Every decorator holds an `@`, so Babel skips only files that cannot hold one.
75
+ rolldown: { filter: { code: "@" } },
76
+ }),
77
+ ],
78
+ }),
79
+ ],
80
+ });
81
+ ```
82
+
83
+ The filter is what keeps Babel off the files without decorators; the plugin applies it only when every preset carries
84
+ one and `plugins` is left empty. Keep it the plain `"@"`: a narrower pattern can miss a legal position such as
85
+ `export @injectable() class`, and a missed file ships its decorators raw. Beside other presets, list this one last,
86
+ since Babel runs presets last to first.
87
+
88
+ > **Warning.** Without the plugin the decorators pass through untouched, and nothing flags it at build time:
89
+ > `vite build` succeeds, then the bundle throws `SyntaxError: Invalid or unexpected token` as it loads — the same error
90
+ > Vitest reports for a test file that imports a decorated class.
91
+
92
+ `tsc` leaves decorators in its output at `target: "ESNext"`. At any lower target it lowers them, but on a runtime
93
+ without `Symbol.metadata` it hands them no metadata object, which every decorator here reports as
94
+ `MissingDecoratorMetadataError`. Install the symbol in a module the entry point imports first:
95
+
96
+ ```ts
97
+ (Symbol as { metadata?: symbol }).metadata ??= Symbol.for("Symbol.metadata");
98
+ ```
99
+
100
+ Not every toolchain lowers them yet. Node's own type stripping rejects decorators; Next.js cannot select the `2023-11`
101
+ version (vercel/next.js#96328 adds it); and Bun 1.4.2 and earlier inject the wrong values, silently, into a module that
102
+ holds two decorated classes (oven-sh/bun#28316, fixed in 1.4.3).
103
+
104
+ [The specification → tsconfig setup](./spec/decorators.md#tsconfig-setup) covers the compiler options. And
105
+ [decorators](#decorators) are optional: an app wired through `toResolved`, `toDynamic` and `Module.fromBindings` needs
106
+ none of this.
107
+
108
+ ### Explicit resource management types
109
+
110
+ The declarations use explicit resource management (`AsyncDisposable`, behind `await using`), which no numbered `lib`
111
+ declares yet. `@types/node` 22 or later loads those types, so a Node program needs nothing more. Any other program adds
42
112
  `ESNext.Disposable` to `lib` once its runtime ships explicit resource management. A browser program that targets Safari,
43
- which has not shipped it, keeps `skipLibCheck` on and calls `dispose()` instead of `await using`. The package is
44
- published on 0.x and versioned on its own track: breaking changes ship as minor versions, so pin the minor version when
45
- you need stability.
113
+ which has not shipped it, keeps `skipLibCheck` on and calls `disposeAsync()` instead of `await using`.
46
114
 
47
115
  ## Quick start
48
116
 
@@ -81,7 +149,8 @@ container.rebind(LoggerToken).toConstantValue({
81
149
 
82
150
  `@injectable([...])` declares a class's constructor dependencies, in parameter order. The decorator checks the list
83
151
  against the constructor signature, so a dependency of the wrong type — or a list of the wrong length — is a compile-time
84
- error.
152
+ error. `@injectable()` with no list declares none, so it compiles only on a class whose constructor needs nothing, a
153
+ subclass inheriting its base's constructor included.
85
154
 
86
155
  ## Tokens
87
156
 
@@ -98,9 +167,9 @@ A class constructor works as a key too: `container.bind(UserService).toSelf()`,
98
167
 
99
168
  ## Bindings
100
169
 
101
- A binding describes how the container produces a value for a token. You declare it as a chain, in one fixed order: a
102
- strategy (the `to*` step, which produces the value), then optional constraints, a scope, and lifecycle hooks. Only
103
- `container.bind(key).to*(…)` is required; everything after it is optional.
170
+ A binding describes how the container produces a value for a token. You declare it as a chain, in one fixed order:
171
+ optional [constraints](#constraints), then a strategy (the `to*` step, which produces the value and registers the
172
+ binding), then an optional scope and lifecycle hooks. Only `container.bind(key).to*(…)` is required.
104
173
 
105
174
  | Strategy | Produces |
106
175
  | --------------------------------- | ----------------------------------------------------------------- |
@@ -134,12 +203,12 @@ no scope produces a new instance every time.
134
203
  | Scope | Lifetime |
135
204
  | -------------- | ---------------------------------------------------------------------------------------- |
136
205
  | `.singleton()` | One instance for the container that owns the binding; children resolve the same instance |
137
- | `.scoped()` | One instance per child container — resolving from a container with no child scope throws |
206
+ | `.scoped()` | One instance per child container, deactivated with it — resolving outside a child throws |
138
207
  | `.transient()` | A new instance on every resolution — the default |
139
208
 
140
209
  ```ts
141
210
  container.bind(DbToken).toDynamic(createDb).singleton();
142
- container.bind(RequestContextToken).toSelf().scoped();
211
+ container.bind(RequestContext).toSelf().scoped();
143
212
  ```
144
213
 
145
214
  > **Important.** Resolving a `scoped` binding from a container with no child scope throws `MissingScopeContextError`.
@@ -148,9 +217,10 @@ container.bind(RequestContextToken).toSelf().scoped();
148
217
  ### Lifecycle hooks
149
218
 
150
219
  A lifecycle hook runs your code as an instance is created or torn down. `.onActivation(fn)` runs right after an instance
151
- is created, and may replace it; `.onDeactivation(fn)` runs when the owning container is disposed or the binding is
152
- unbound. Both are also available container-wide, through `container.onActivation(token, fn)` and
153
- `container.onDeactivation(token, fn)`:
220
+ is created, and may replace it; `.onDeactivation(fn)` runs as the instance's lifetime ends — a singleton's when its
221
+ container is disposed or the binding is unbound, a scoped instance's when the child container that cached it is
222
+ disposed. A transient instance has no deactivation. Both hooks are also available container-wide, through
223
+ `container.onActivation(token, fn)` and `container.onDeactivation(token, fn)`:
154
224
 
155
225
  ```ts
156
226
  container
@@ -208,9 +278,22 @@ container.resolve(StorageToken, { tag: Provider.of("s3") }); // → S3Storage
208
278
  > **Note.** `key.of(value)` interns each value: the same value always yields the same criterion object, which lets
209
279
  > lookup compare by identity. A criterion built by hand — not through `.of()` — matches nothing.
210
280
 
211
- `{ tag: criterion }` and `{ tags: [criterion] }` are the same request — for `resolve`, and for `inject`, `optional`, and
212
- `injectAll` alike. Chain `.whenTagged(...)` once per criterion a slot carries, and request several at once with
213
- `{ tags: [...] }`.
281
+ `{ tag: criterion }` and `{ tags: [criterion] }` are the same request — for `resolve`, and for `inject`,
282
+ `injectOptional`, and `injectAll` alike. Chain `.whenTagged(...)` once per criterion a slot carries, and request several
283
+ at once with `{ tags: [...] }`.
284
+
285
+ **One binding per slot; a collection with `many()`.** Binding a token again in a slot it already fills replaces the
286
+ earlier binding — `bind` is last-wins per slot, so `resolveAll` then finds only the newer one. To register several
287
+ implementations for `resolveAll` and `injectAll` to gather, mark each one a collection member with `.many()`:
288
+
289
+ ```ts
290
+ container.bind(PluginToken).many().to(AuditPlugin);
291
+ container.bind(PluginToken).many().to(MetricsPlugin);
292
+
293
+ container.resolveAll(PluginToken); // → an AuditPlugin and a MetricsPlugin, in registration order
294
+ ```
295
+
296
+ A member keeps the default slot and is never what a single `resolve` selects.
214
297
 
215
298
  **Predicate constraints — graph-aware selection.** When a slot isn't enough — when you need to choose based on _who_ is
216
299
  resolving — pass a predicate to `.when(ctx => boolean)`. It runs at resolve time, after slot matching. These ready-made
@@ -239,20 +322,20 @@ them:
239
322
 
240
323
  - `@injectable([...deps])` — declares a class's constructor dependencies, in parameter order.
241
324
  - `inject(token, options)` — wraps one dependency with slot options (`name`, `tag`, `tags`).
242
- - `optional(token)` — resolves to `undefined` when nothing is bound.
325
+ - `injectOptional(token)` — resolves to `undefined` when nothing is bound.
243
326
  - `injectAll(token)` — collects every matching binding into an array.
244
327
  - `@postConstruct()` — runs after wiring; `@preDestroy()` runs on disposal. An async `@postConstruct` needs
245
328
  `resolveAsync`.
246
329
 
247
330
  ```ts
248
- import { inject, injectable, injectAll, optional, postConstruct, preDestroy } from "@codefast/di";
331
+ import { inject, injectable, injectAll, injectOptional, postConstruct, preDestroy } from "@codefast/di";
249
332
 
250
- @injectable([DbToken, optional(CacheToken), injectAll(PluginToken), inject(LoggerToken, { name: "audit" })])
333
+ @injectable([DbToken, injectOptional(CacheToken), injectAll(PluginToken), inject(LoggerToken, { name: "audit" })])
251
334
  class UserRepository {
252
335
  constructor(
253
336
  private readonly db: Database,
254
337
  private readonly cache: Cache | undefined,
255
- private readonly plugins: Array<Plugin>,
338
+ private readonly plugins: ReadonlyArray<Plugin>,
256
339
  private readonly audit: Logger,
257
340
  ) {}
258
341
 
@@ -294,7 +377,8 @@ only**: the context does not survive an `await`, so a callback returning a `Prom
294
377
 
295
378
  To avoid binding classes one by one, let them register themselves.
296
379
  `@injectable(deps, { autoRegister: registry, scope })` records the class in a registry from
297
- `createAutoRegisterRegistry()`, and `container.loadAutoRegistered(registry)` binds the whole set in one call.
380
+ `createAutoRegisterRegistry("app:Services")`. The registry is a `SyncModule`: `container.load(registry)` binds the whole
381
+ set in one call, and `container.unload(registry)` removes it again.
298
382
 
299
383
  ### Custom metadata
300
384
 
@@ -342,38 +426,48 @@ parent's singletons, while each `scoped` binding gets a fresh instance per child
342
426
  await using requestContainer = container.createChild();
343
427
  requestContainer.bind(RequestIdToken).toConstantValue(crypto.randomUUID());
344
428
  const service = requestContainer.resolve(RequestScopedService);
345
- } // dispose() runs here and releases what this child owns
429
+ } // disposeAsync() runs here and releases what this child owns
346
430
  ```
347
431
 
432
+ [Example 22](examples/22-per-request-scope/README.md) is the guide to this pattern: where each binding lives, the rules
433
+ that keep a scope from leaking, and how it lands in TanStack Start server functions and server routes.
434
+
348
435
  ### Validation
349
436
 
350
437
  A captive dependency is a long-lived binding that holds a shorter-lived one — a `singleton` that depends on a `scoped`
351
- or `transient` binding — which silently freezes that dependency for the singleton's whole life. `validate()` fails fast
352
- on captive dependencies, and on constraints no request can satisfy, before the first resolve.
438
+ or `transient` binding — which silently freezes that dependency for the singleton's whole life. `validate` fails fast on
439
+ captive dependencies, and on constraints no request can satisfy, before the first resolve. It also throws the error
440
+ `resolve()` would for a singleton graph that cannot resolve: a required dependency nothing binds, a slot nothing
441
+ matches, or a cycle.
353
442
 
354
443
  ```ts
355
- container.validate(); // throws ScopeViolationError on the first violation
444
+ validate(container); // throws on the first violation — ScopeViolationError, TokenNotBoundError, …
356
445
  ```
357
446
 
447
+ A transient or scoped consumer's dependencies are left to `resolve()`, because a child container may still bind them.
448
+
449
+ Guard the call with a dev-only check (`if (import.meta.env.DEV)` or `process.env.NODE_ENV !== "production"`) and the
450
+ production bundle drops `validate` and the introspection code behind it.
451
+
358
452
  ### Disposal
359
453
 
360
454
  `Container` implements `AsyncDisposable`, so `await using` runs every deactivation hook automatically as the block
361
- exits. Synchronous `using` isn't supported — `onDeactivation` may be async — and `Symbol.dispose` throws
362
- `SyncDisposalNotSupportedError`.
455
+ exits, and disposing a child deactivates the scoped instances it cached. Synchronous `using` is a compile error: a
456
+ deactivation hook may be async, so the container implements `Symbol.asyncDispose` only.
363
457
 
364
458
  ### Introspection
365
459
 
366
- `container.inspect()` returns a `ContainerSnapshot`; `container.lookupBindings(token)` returns the snapshots of one
367
- token's bindings; and `container.generateDependencyGraph()` returns a JSON graph. Adapters render that graph for common
460
+ `inspect(container)` returns a `ContainerSnapshot`; `lookupBindings(container, token)` returns the snapshots of one
461
+ token's bindings; and `generateDependencyGraph(container)` returns a JSON graph. Adapters render that graph for common
368
462
  viewers: `toDotGraph`, `toMermaidGraph`, `toCytoscapeGraph`, and `toReactFlowGraph`.
369
463
 
370
- `container.explain(token, options)` answers why a request selects the binding it does, without instantiating anything:
464
+ `explain(container, token, options)` answers why a request selects the binding it does, without instantiating anything:
371
465
  every candidate each registry offered and what selection made of it, the rule that decided, and the binding it ends on.
372
466
  It evaluates `when()` predicates the way `resolve` does, and `options.ancestors` explains a request made from inside
373
467
  other resolutions, so a predicate that reads the parent sees the one it would:
374
468
 
375
469
  ```ts
376
- const explanation = container.explain(Logger, { ancestors: [Settlement] });
470
+ const explanation = explain(container, LoggerToken, { ancestors: [CheckoutService] });
377
471
 
378
472
  explanation.selected?.id; // the binding `resolve` would answer with
379
473
  explanation.steps[0]?.rule; // "sole-predicate": the only candidate with a `when()` beat the rest
@@ -432,7 +526,7 @@ beforeEach(() => {
432
526
  });
433
527
 
434
528
  afterEach(async () => {
435
- await container.dispose();
529
+ await container.disposeAsync();
436
530
  });
437
531
  ```
438
532
 
@@ -460,7 +554,8 @@ mocks from the class's own declared dependencies, through a real container.
460
554
 
461
555
  ## Errors
462
556
 
463
- Every error extends `DiError` and carries a stable `code`, so you can branch on the code rather than the message:
557
+ Every error extends `DiError` and carries a stable `code`, typed as the `DiErrorCode` union, so you can branch on the
558
+ code rather than the message and the compiler checks every case:
464
559
 
465
560
  | Error | Code | Raised when |
466
561
  | ------------------------------ | --------------------------- | -------------------------------------------------------------------------- |
@@ -470,11 +565,14 @@ Every error extends `DiError` and carries a stable `code`, so you can branch on
470
565
  | `CircularDependencyError` | `CIRCULAR_DEPENDENCY` | A cycle appears on the resolution path |
471
566
  | `AsyncResolutionError` | `ASYNC_RESOLUTION` | A sync `resolve()` reaches an async factory |
472
567
  | `AsyncActivationError` | `ASYNC_ACTIVATION` | A `@postConstruct` or `onActivation` hook returns a promise on a sync path |
473
- | `ScopeViolationError` | `SCOPE_VIOLATION` | `validate()` finds a captive dependency |
568
+ | `ScopeViolationError` | `SCOPE_VIOLATION` | `validate` finds a captive dependency |
474
569
  | `MissingScopeContextError` | `MISSING_SCOPE_CONTEXT` | A `scoped` binding is resolved outside a child container |
475
570
  | `MissingContainerContextError` | `MISSING_CONTAINER_CONTEXT` | An `@inject` accessor initializes with no container open |
476
571
  | `DisposedContainerError` | `DISPOSED_CONTAINER` | A disposed container is used |
477
572
 
573
+ A miss below the token you asked for names its path: `TokenNotBoundError` and `NoMatchingBindingError` carry `path`, and
574
+ the message ends with it — `Path: UserService → UserRepository → app:Logger`.
575
+
478
576
  The full taxonomy — including `MissingMetadataError`, `InvalidMetadataError`, `RebindUnboundTokenError`,
479
577
  `AsyncModuleLoadError`, `InvalidBindingDeclarationError`, and the rest — is exported from the root entry and from
480
578
  `@codefast/di/errors`.
@@ -495,8 +593,9 @@ introspection under `introspection/*`: `@codefast/di/introspection/inspector`, `
495
593
  ## Benchmarks
496
594
 
497
595
  A first-party benchmark suite lives in the monorepo, at [`benchmarks/di`](../../benchmarks/di). It runs the same
498
- workloads through `@codefast/di`, InversifyJS, Awilix, and tsyringe, and its `RESULTS.md` ledger records the numbers
499
- alongside the method that produced them. Run it yourself rather than taking any figure on faith.
596
+ workloads through `@codefast/di`, InversifyJS, Awilix, tsyringe, Brandi, ditox, and injection-js, and its `RESULTS.md`
597
+ ledger records the numbers alongside the method that produced them. Run it yourself rather than taking any figure on
598
+ faith.
500
599
 
501
600
  ## Documentation
502
601
 
@@ -3,6 +3,7 @@ import type { Container } from "#container/container";
3
3
  import type { ConstructorInvocation } from "#core/constructor-type";
4
4
  import type { Token } from "#core/token";
5
5
  import type { Constructor, ResolveOptions } from "#core/types";
6
+ import type { DependencySlot } from "#injection/dependency-slot";
6
7
  /**
7
8
  * Path-continuing resolution the engine installs while constructing a class with `@inject` accessors.
8
9
  *
@@ -14,6 +15,51 @@ import type { Constructor, ResolveOptions } from "#core/types";
14
15
  export interface AmbientResolution {
15
16
  resolve<Value>(token: Token<Value> | Constructor<Value>, options?: ResolveOptions): Value;
16
17
  resolveOptional<Value>(token: Token<Value> | Constructor<Value>, options?: ResolveOptions): Value | undefined;
18
+ /**
19
+ * The value a plan resolved for this accessor ahead of construction, or {@link NOT_PREPARED}.
20
+ *
21
+ * @remarks Absent on a resolution that prepares nothing, which leaves every accessor to resolve itself.
22
+ */
23
+ takePrepared?(instance: unknown, slot: DependencySlot): unknown;
24
+ }
25
+ /**
26
+ * Marks a slot whose accessor initializer takes a prepared value when one is offered.
27
+ *
28
+ * @since 0.14.0
29
+ */
30
+ export declare function markPreparableSlot(slot: DependencySlot): void;
31
+ /**
32
+ * Whether an initializer will ask for this slot's prepared value, so preparing it is never wasted.
33
+ *
34
+ * @since 0.14.0
35
+ */
36
+ export declare function isPreparableSlot(slot: DependencySlot): boolean;
37
+ /**
38
+ * The answer {@link AmbientResolution.takePrepared} gives for an accessor it holds no value for.
39
+ *
40
+ * @since 0.14.0
41
+ */
42
+ export declare const NOT_PREPARED: unique symbol;
43
+ /**
44
+ * Accessor values a compiled plan resolved before construction, handed to the initializers in order.
45
+ *
46
+ * @remarks An initializer takes the next value only when its slot is the next one prepared and it
47
+ * initializes the instance that took the first, so a class constructed inside the constructor
48
+ * resolves for itself instead of taking another instance's value.
49
+ *
50
+ * @since 0.14.0
51
+ */
52
+ export declare class PreparedAccessorResolution implements AmbientResolution {
53
+ #private;
54
+ /**
55
+ * @param fallback - Resolves an accessor the plan did not prepare, with the class on the path.
56
+ * @param slots - The accessors' slots, in the order their initializers run.
57
+ * @param values - One resolved value per slot.
58
+ */
59
+ constructor(fallback: AmbientResolution, slots: ReadonlyArray<DependencySlot>, values: ReadonlyArray<unknown>);
60
+ resolve<Value>(token: Token<Value> | Constructor<Value>, options?: ResolveOptions): Value;
61
+ resolveOptional<Value>(token: Token<Value> | Constructor<Value>, options?: ResolveOptions): Value | undefined;
62
+ takePrepared(instance: unknown, slot: DependencySlot): unknown;
17
63
  }
18
64
  /**
19
65
  * Runs a synchronous callback with the given container installed as the ambient one and returns its result.