@codefast/di 0.13.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 (43) hide show
  1. package/CHANGELOG.md +152 -0
  2. package/README.md +48 -32
  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 -29
  7. package/dist/container/container.js +49 -264
  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 +22 -1
  11. package/dist/core/binding-declaration.js +2 -2
  12. package/dist/core/module.d.ts +4 -25
  13. package/dist/core/module.js +3 -27
  14. package/dist/core/state-epoch.d.ts +1 -1
  15. package/dist/core/state-epoch.js +1 -1
  16. package/dist/core/types.d.ts +16 -7
  17. package/dist/decorators/inject.js +27 -22
  18. package/dist/decorators/injectable.d.ts +14 -18
  19. package/dist/decorators/injectable.js +23 -2
  20. package/dist/errors.d.ts +11 -2
  21. package/dist/errors.js +6 -3
  22. package/dist/index.d.ts +8 -7
  23. package/dist/index.js +3 -2
  24. package/dist/injection/dependency-slot.d.ts +17 -0
  25. package/dist/injection/dependency-slot.js +46 -0
  26. package/dist/injection/descriptor.d.ts +9 -3
  27. package/dist/injection/descriptor.js +10 -1
  28. package/dist/introspection/validation.d.ts +28 -0
  29. package/dist/introspection/validation.js +244 -0
  30. package/dist/lifecycle/hooks.d.ts +11 -2
  31. package/dist/lifecycle/hooks.js +30 -18
  32. package/dist/resolution/cache/class-introspector.d.ts +7 -8
  33. package/dist/resolution/cache/class-introspector.js +40 -3
  34. package/dist/resolution/cache/lookup.d.ts +10 -0
  35. package/dist/resolution/cache/lookup.js +27 -0
  36. package/dist/resolution/context.d.ts +12 -12
  37. package/dist/resolution/plan/codegen.d.ts +2 -1
  38. package/dist/resolution/plan/codegen.js +1 -1
  39. package/dist/resolution/plan/compiler.d.ts +6 -6
  40. package/dist/resolution/plan/compiler.js +152 -22
  41. package/dist/resolution/resolver.d.ts +2 -8
  42. package/dist/resolution/resolver.js +17 -93
  43. package/package.json +10 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,157 @@
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
+
3
155
  ## 0.13.0
4
156
 
5
157
  ### Minor Changes
package/README.md CHANGED
@@ -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
- - **Standard decorators.** `@injectable`, `inject`, `optional`, `injectAll`, `@postConstruct`, and `@preDestroy` declare
24
- dependencies explicitly — no runtime reflection.
23
+ - **Standard decorators.** `@injectable`, `inject`, `injectOptional`, `injectAll`, `@postConstruct`, and `@preDestroy`
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, missing bindings and cycles 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,13 @@ 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
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
39
  ([support policy](../../SUPPORT.md#browsers)). It requires TypeScript 7 or later, with standard 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
42
- `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.
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.
46
45
 
47
46
  ### Toolchain
48
47
 
@@ -52,6 +51,7 @@ decorated class always passes through a transform that lowers it. What that take
52
51
  | Toolchain | What it needs |
53
52
  | ------------------------- | ----------------------------------------------------------------------------------------------------------- |
54
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
55
  | esbuild | A `target` below `esnext`, such as `es2024` or `node24`: at its default, `esnext`, decorators pass through. |
56
56
  | Vite 8, and Vitest on it | The Babel decorators plugin: their Oxc transform lowers only `experimentalDecorators`. |
57
57
  | SWC 1.15.21 or later | `jsc.parser.decorators: true` and `jsc.transform.decoratorVersion: "2023-11"`. |
@@ -99,12 +99,19 @@ without `Symbol.metadata` it hands them no metadata object, which every decorato
99
99
 
100
100
  Not every toolchain lowers them yet. Node's own type stripping rejects decorators; Next.js cannot select the `2023-11`
101
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).
102
+ holds two decorated classes (oven-sh/bun#28316, fixed in 1.4.3).
103
103
 
104
104
  [The specification → tsconfig setup](./spec/decorators.md#tsconfig-setup) covers the compiler options. And
105
105
  [decorators](#decorators) are optional: an app wired through `toResolved`, `toDynamic` and `Module.fromBindings` needs
106
106
  none of this.
107
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
112
+ `ESNext.Disposable` to `lib` once its runtime ships explicit resource management. A browser program that targets Safari,
113
+ which has not shipped it, keeps `skipLibCheck` on and calls `disposeAsync()` instead of `await using`.
114
+
108
115
  ## Quick start
109
116
 
110
117
  ```ts
@@ -142,7 +149,8 @@ container.rebind(LoggerToken).toConstantValue({
142
149
 
143
150
  `@injectable([...])` declares a class's constructor dependencies, in parameter order. The decorator checks the list
144
151
  against the constructor signature, so a dependency of the wrong type — or a list of the wrong length — is a compile-time
145
- 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.
146
154
 
147
155
  ## Tokens
148
156
 
@@ -200,7 +208,7 @@ no scope produces a new instance every time.
200
208
 
201
209
  ```ts
202
210
  container.bind(DbToken).toDynamic(createDb).singleton();
203
- container.bind(RequestContextToken).toSelf().scoped();
211
+ container.bind(RequestContext).toSelf().scoped();
204
212
  ```
205
213
 
206
214
  > **Important.** Resolving a `scoped` binding from a container with no child scope throws `MissingScopeContextError`.
@@ -270,9 +278,9 @@ container.resolve(StorageToken, { tag: Provider.of("s3") }); // → S3Storage
270
278
  > **Note.** `key.of(value)` interns each value: the same value always yields the same criterion object, which lets
271
279
  > lookup compare by identity. A criterion built by hand — not through `.of()` — matches nothing.
272
280
 
273
- `{ tag: criterion }` and `{ tags: [criterion] }` are the same request — for `resolve`, and for `inject`, `optional`, and
274
- `injectAll` alike. Chain `.whenTagged(...)` once per criterion a slot carries, and request several at once with
275
- `{ 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: [...] }`.
276
284
 
277
285
  **One binding per slot; a collection with `many()`.** Binding a token again in a slot it already fills replaces the
278
286
  earlier binding — `bind` is last-wins per slot, so `resolveAll` then finds only the newer one. To register several
@@ -314,15 +322,15 @@ them:
314
322
 
315
323
  - `@injectable([...deps])` — declares a class's constructor dependencies, in parameter order.
316
324
  - `inject(token, options)` — wraps one dependency with slot options (`name`, `tag`, `tags`).
317
- - `optional(token)` — resolves to `undefined` when nothing is bound.
325
+ - `injectOptional(token)` — resolves to `undefined` when nothing is bound.
318
326
  - `injectAll(token)` — collects every matching binding into an array.
319
327
  - `@postConstruct()` — runs after wiring; `@preDestroy()` runs on disposal. An async `@postConstruct` needs
320
328
  `resolveAsync`.
321
329
 
322
330
  ```ts
323
- import { inject, injectable, injectAll, optional, postConstruct, preDestroy } from "@codefast/di";
331
+ import { inject, injectable, injectAll, injectOptional, postConstruct, preDestroy } from "@codefast/di";
324
332
 
325
- @injectable([DbToken, optional(CacheToken), injectAll(PluginToken), inject(LoggerToken, { name: "audit" })])
333
+ @injectable([DbToken, injectOptional(CacheToken), injectAll(PluginToken), inject(LoggerToken, { name: "audit" })])
326
334
  class UserRepository {
327
335
  constructor(
328
336
  private readonly db: Database,
@@ -369,7 +377,8 @@ only**: the context does not survive an `await`, so a callback returning a `Prom
369
377
 
370
378
  To avoid binding classes one by one, let them register themselves.
371
379
  `@injectable(deps, { autoRegister: registry, scope })` records the class in a registry from
372
- `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.
373
382
 
374
383
  ### Custom metadata
375
384
 
@@ -417,23 +426,29 @@ parent's singletons, while each `scoped` binding gets a fresh instance per child
417
426
  await using requestContainer = container.createChild();
418
427
  requestContainer.bind(RequestIdToken).toConstantValue(crypto.randomUUID());
419
428
  const service = requestContainer.resolve(RequestScopedService);
420
- } // dispose() runs here and releases what this child owns
429
+ } // disposeAsync() runs here and releases what this child owns
421
430
  ```
422
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
+
423
435
  ### Validation
424
436
 
425
437
  A captive dependency is a long-lived binding that holds a shorter-lived one — a `singleton` that depends on a `scoped`
426
- or `transient` binding — which silently freezes that dependency for the singleton's whole life. `validate()` fails fast
427
- on captive dependencies, and on constraints no request can satisfy, before the first resolve. It also throws the error
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
428
440
  `resolve()` would for a singleton graph that cannot resolve: a required dependency nothing binds, a slot nothing
429
441
  matches, or a cycle.
430
442
 
431
443
  ```ts
432
- container.validate(); // throws on the first violation — ScopeViolationError, TokenNotBoundError, …
444
+ validate(container); // throws on the first violation — ScopeViolationError, TokenNotBoundError, …
433
445
  ```
434
446
 
435
447
  A transient or scoped consumer's dependencies are left to `resolve()`, because a child container may still bind them.
436
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
+
437
452
  ### Disposal
438
453
 
439
454
  `Container` implements `AsyncDisposable`, so `await using` runs every deactivation hook automatically as the block
@@ -442,17 +457,17 @@ deactivation hook may be async, so the container implements `Symbol.asyncDispose
442
457
 
443
458
  ### Introspection
444
459
 
445
- `container.inspect()` returns a `ContainerSnapshot`; `container.lookupBindings(token)` returns the snapshots of one
446
- 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
447
462
  viewers: `toDotGraph`, `toMermaidGraph`, `toCytoscapeGraph`, and `toReactFlowGraph`.
448
463
 
449
- `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:
450
465
  every candidate each registry offered and what selection made of it, the rule that decided, and the binding it ends on.
451
466
  It evaluates `when()` predicates the way `resolve` does, and `options.ancestors` explains a request made from inside
452
467
  other resolutions, so a predicate that reads the parent sees the one it would:
453
468
 
454
469
  ```ts
455
- const explanation = container.explain(Logger, { ancestors: [Settlement] });
470
+ const explanation = explain(container, LoggerToken, { ancestors: [CheckoutService] });
456
471
 
457
472
  explanation.selected?.id; // the binding `resolve` would answer with
458
473
  explanation.steps[0]?.rule; // "sole-predicate": the only candidate with a `when()` beat the rest
@@ -511,7 +526,7 @@ beforeEach(() => {
511
526
  });
512
527
 
513
528
  afterEach(async () => {
514
- await container.dispose();
529
+ await container.disposeAsync();
515
530
  });
516
531
  ```
517
532
 
@@ -539,7 +554,8 @@ mocks from the class's own declared dependencies, through a real container.
539
554
 
540
555
  ## Errors
541
556
 
542
- 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:
543
559
 
544
560
  | Error | Code | Raised when |
545
561
  | ------------------------------ | --------------------------- | -------------------------------------------------------------------------- |
@@ -549,7 +565,7 @@ Every error extends `DiError` and carries a stable `code`, so you can branch on
549
565
  | `CircularDependencyError` | `CIRCULAR_DEPENDENCY` | A cycle appears on the resolution path |
550
566
  | `AsyncResolutionError` | `ASYNC_RESOLUTION` | A sync `resolve()` reaches an async factory |
551
567
  | `AsyncActivationError` | `ASYNC_ACTIVATION` | A `@postConstruct` or `onActivation` hook returns a promise on a sync path |
552
- | `ScopeViolationError` | `SCOPE_VIOLATION` | `validate()` finds a captive dependency |
568
+ | `ScopeViolationError` | `SCOPE_VIOLATION` | `validate` finds a captive dependency |
553
569
  | `MissingScopeContextError` | `MISSING_SCOPE_CONTEXT` | A `scoped` binding is resolved outside a child container |
554
570
  | `MissingContainerContextError` | `MISSING_CONTAINER_CONTEXT` | An `@inject` accessor initializes with no container open |
555
571
  | `DisposedContainerError` | `DISPOSED_CONTAINER` | A disposed container is used |
@@ -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.
@@ -1,3 +1,73 @@
1
+ // Slots whose initializer asks for a prepared value — an `@inject` accessor's own descriptor.
2
+ const preparableSlots = new WeakSet();
3
+ /**
4
+ * Marks a slot whose accessor initializer takes a prepared value when one is offered.
5
+ *
6
+ * @since 0.14.0
7
+ */
8
+ export function markPreparableSlot(slot) {
9
+ preparableSlots.add(slot);
10
+ }
11
+ /**
12
+ * Whether an initializer will ask for this slot's prepared value, so preparing it is never wasted.
13
+ *
14
+ * @since 0.14.0
15
+ */
16
+ export function isPreparableSlot(slot) {
17
+ return preparableSlots.has(slot);
18
+ }
19
+ /**
20
+ * The answer {@link AmbientResolution.takePrepared} gives for an accessor it holds no value for.
21
+ *
22
+ * @since 0.14.0
23
+ */
24
+ export const NOT_PREPARED = Symbol("di:not-prepared");
25
+ /**
26
+ * Accessor values a compiled plan resolved before construction, handed to the initializers in order.
27
+ *
28
+ * @remarks An initializer takes the next value only when its slot is the next one prepared and it
29
+ * initializes the instance that took the first, so a class constructed inside the constructor
30
+ * resolves for itself instead of taking another instance's value.
31
+ *
32
+ * @since 0.14.0
33
+ */
34
+ export class PreparedAccessorResolution {
35
+ #fallback;
36
+ #slots;
37
+ #values;
38
+ #next = 0;
39
+ #owner = undefined;
40
+ /**
41
+ * @param fallback - Resolves an accessor the plan did not prepare, with the class on the path.
42
+ * @param slots - The accessors' slots, in the order their initializers run.
43
+ * @param values - One resolved value per slot.
44
+ */
45
+ constructor(fallback, slots, values) {
46
+ this.#fallback = fallback;
47
+ this.#slots = slots;
48
+ this.#values = values;
49
+ }
50
+ resolve(token, options) {
51
+ return this.#fallback.resolve(token, options);
52
+ }
53
+ resolveOptional(token, options) {
54
+ return this.#fallback.resolveOptional(token, options);
55
+ }
56
+ takePrepared(instance, slot) {
57
+ const index = this.#next;
58
+ if (this.#slots[index] !== slot) {
59
+ return NOT_PREPARED;
60
+ }
61
+ if (index === 0) {
62
+ this.#owner = instance;
63
+ }
64
+ else if (this.#owner !== instance) {
65
+ return NOT_PREPARED;
66
+ }
67
+ this.#next = index + 1;
68
+ return this.#values[index];
69
+ }
70
+ }
1
71
  let activeContainer;
2
72
  let activeResolution;
3
73
  /**
@@ -45,7 +115,8 @@ export function constructWithAmbientResolution(container, resolution, target, de
45
115
  activeContainer = container;
46
116
  activeResolution = resolution;
47
117
  try {
48
- return new target(...deps);
118
+ // A spread call is not inlined, and most accessor classes take no constructor arguments.
119
+ return deps.length === 0 ? new target() : new target(...deps);
49
120
  }
50
121
  finally {
51
122
  activeContainer = previousContainer;
@@ -3,7 +3,7 @@ import { mergingConstraintRequirements } from "#core/constraint-requirement";
3
3
  import { slotName } from "#core/tag";
4
4
  import { tokenName } from "#core/token";
5
5
  import { ChainAlreadyRegisteredError, ChainNotRegisteredError, ManyBindingSlotError, SelfBindingRequiresClassError, } from "#errors";
6
- import { normalizeToDescriptor } from "#injection/descriptor";
6
+ import { settledDescriptorsOf } from "#injection/descriptor";
7
7
  // ── BindingChain ─────────────────────────────────────────────────────────────────────────────────────────────────────
8
8
  /**
9
9
  * The one builder behind `bind()` and every `to*()` return type — and the binding it registers.
@@ -149,13 +149,13 @@ export class BindingChain {
149
149
  toResolved(factory, deps) {
150
150
  this.#requireUnregistered();
151
151
  this.factory = factory;
152
- this.deps = deps.map((dependency) => normalizeToDescriptor(dependency));
152
+ this.deps = settledDescriptorsOf(deps);
153
153
  return this.#register("resolved", "transient");
154
154
  }
155
155
  toResolvedAsync(factory, deps) {
156
156
  this.#requireUnregistered();
157
157
  this.factory = factory;
158
- this.deps = deps.map((dependency) => normalizeToDescriptor(dependency));
158
+ this.deps = settledDescriptorsOf(deps);
159
159
  return this.#register("resolved-async", "transient");
160
160
  }
161
161
  toAlias(target) {
@@ -1,56 +1,38 @@
1
- import type { BindToBuilder } from "#core/binding-builders";
1
+ import type { Binder, BindToBuilder, ClassBindToBuilder } from "#core/binding-builders";
2
2
  import type { AsyncModule, SyncModule } from "#core/module";
3
+ import { BindingRegistry } from "#core/registry";
3
4
  import type { Token } from "#core/token";
4
- import type { ActivationHandler, BindingIdentifier, Constructor, DeactivationHandler, ResolveOptions } from "#core/types";
5
- import type { AutoRegisterRegistry } from "#decorators/injectable";
6
- import type { ContainerGraphJson, GraphOptions } from "#introspection/dependency-graph";
7
- import type { ExplainOptions, ResolutionExplanation } from "#introspection/explanation";
8
- import type { BindingSnapshot, ContainerSnapshot } from "#introspection/inspector";
5
+ import type { ActivationHandler, BindingIdentifier, Constructor, DeactivationHandler, Resolver, ResolveOptions } from "#core/types";
6
+ import { Inspector } from "#introspection/inspector";
7
+ import { LifecycleManager } from "#lifecycle/hooks";
9
8
  import type { MetadataReader } from "#metadata/types";
9
+ import { DependencyResolver } from "#resolution/resolver";
10
10
  /**
11
11
  * The public surface: binding, resolving, modules, lifecycle hooks, child scopes, and disposal.
12
12
  *
13
13
  * @since 0.3.16-canary.0
14
14
  */
15
- export interface Container {
15
+ export interface Container extends Resolver, Binder {
16
16
  readonly isDisposed: boolean;
17
- bind<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>): BindToBuilder<Value, Names>;
18
17
  unbind(tokenOrId: Token<unknown> | Constructor | BindingIdentifier): void;
19
18
  unbindAsync(tokenOrId: Token<unknown> | Constructor | BindingIdentifier): Promise<void>;
20
19
  unbindAll(): void;
21
20
  unbindAllAsync(): Promise<void>;
22
- rebind<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>): BindToBuilder<Value, Names>;
21
+ rebind<Value>(type: Constructor<Value>): ClassBindToBuilder<Value>;
22
+ rebind<Value, Names extends string = string>(token: Token<Value, Names>): BindToBuilder<Value, Names>;
23
+ rebind<Value, Names extends string = string>(key: Token<Value, Names> | Constructor<Value>): BindToBuilder<Value, Names>;
23
24
  load(...modules: Array<SyncModule>): void;
24
25
  loadAsync(...modules: Array<SyncModule | AsyncModule>): Promise<void>;
25
26
  unload(...modules: Array<SyncModule>): void;
26
27
  unloadAsync(...modules: Array<SyncModule | AsyncModule>): Promise<void>;
27
- loadAutoRegistered(registry: AutoRegisterRegistry): number;
28
28
  onActivation<Value>(token: Token<Value> | Constructor<Value>, handler: ActivationHandler<Value>): void;
29
29
  onDeactivation<Value>(token: Token<Value> | Constructor<Value>, handler: DeactivationHandler<Value>): void;
30
- resolve<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<ResolveOptions<Names>>): Value;
31
- resolveAsync<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<ResolveOptions<Names>>): Promise<Value>;
32
- resolveOptional<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<ResolveOptions<Names>>): Value | undefined;
33
- resolveOptionalAsync<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<ResolveOptions<Names>>): Promise<Value | undefined>;
34
- resolveAll<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<ResolveOptions<Names>>): ReadonlyArray<Value>;
35
- resolveAllAsync<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<ResolveOptions<Names>>): Promise<ReadonlyArray<Value>>;
36
30
  createChild(): Container;
37
- dispose(): Promise<void>;
31
+ disposeAsync(): Promise<void>;
38
32
  [Symbol.asyncDispose](): Promise<void>;
39
33
  initializeAsync(): Promise<void>;
40
- validate(): void;
41
34
  has<Names extends string = string>(token: Token<unknown, Names> | Constructor, options?: NoInfer<ResolveOptions<Names>>): boolean;
42
35
  hasOwn<Names extends string = string>(token: Token<unknown, Names> | Constructor, options?: NoInfer<ResolveOptions<Names>>): boolean;
43
- lookupBindings<Value>(token: Token<Value> | Constructor<Value>): ReadonlyArray<BindingSnapshot>;
44
- inspect(): ContainerSnapshot;
45
- /**
46
- * Explains why a request selects the binding it does, reading each registry the way `resolve` does and deciding
47
- * by the same rules, without instantiating anything.
48
- *
49
- * @remarks A `when()` predicate runs here as it would in `resolve`. `options.ancestors` names the resolutions the
50
- * request is nested in, so a predicate that reads the parent sees the one it would.
51
- */
52
- explain<Names extends string = string>(token: Token<unknown, Names> | Constructor, options?: NoInfer<ExplainOptions<Names>>): ResolutionExplanation;
53
- generateDependencyGraph(options?: GraphOptions): ContainerGraphJson;
54
36
  }
55
37
  /**
56
38
  * What a container has to be told before it exists, as opposed to what it can be bound later.
@@ -77,6 +59,36 @@ export interface ContainerStatic {
77
59
  fromModules(...modules: Array<SyncModule>): Container;
78
60
  fromModulesAsync(...modules: Array<SyncModule | AsyncModule>): Promise<Container>;
79
61
  }
62
+ /**
63
+ * The state the container functions read off a container, kept off its public surface.
64
+ *
65
+ * @remarks `registries` lists the container's own registry, then each ancestor's nearest first — the order every chain
66
+ * walk reads them in.
67
+ *
68
+ * @since 0.14.0
69
+ */
70
+ export interface ContainerInternals {
71
+ readonly registries: readonly [BindingRegistry, ...Array<BindingRegistry>];
72
+ readonly resolver: DependencyResolver;
73
+ readonly metadataReader: MetadataReader;
74
+ readonly lifecycle: LifecycleManager;
75
+ }
76
+ /**
77
+ * Reads the internals of a live container `Container` created, built on first use.
78
+ *
79
+ * @throws `TypeError` for an object `Container` did not create, `DisposedContainerError` for a disposed chain.
80
+ *
81
+ * @since 0.14.0
82
+ */
83
+ export declare function containerInternals(container: Container): ContainerInternals;
84
+ /**
85
+ * Reads the inspector of a live container `Container` created, built on first use.
86
+ *
87
+ * @throws `TypeError` for an object `Container` did not create, `DisposedContainerError` for a disposed chain.
88
+ *
89
+ * @since 0.14.0
90
+ */
91
+ export declare function containerInspector(container: Container): Inspector;
80
92
  /**
81
93
  * The companion factory that creates containers, empty or preloaded from modules.
82
94
  *