@codefast/di 0.13.0 → 0.15.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.
- package/CHANGELOG.md +161 -0
- package/README.md +48 -32
- package/dist/ambient-container.d.ts +46 -0
- package/dist/ambient-container.js +72 -1
- package/dist/container/binding-chain.js +3 -3
- package/dist/container/container.d.ts +41 -29
- package/dist/container/container.js +49 -264
- package/dist/container/introspect.d.ts +47 -0
- package/dist/container/introspect.js +53 -0
- package/dist/core/binding-builders.d.ts +22 -1
- package/dist/core/binding-declaration.js +2 -2
- package/dist/core/module.d.ts +4 -25
- package/dist/core/module.js +3 -27
- package/dist/core/state-epoch.d.ts +1 -1
- package/dist/core/state-epoch.js +1 -1
- package/dist/core/types.d.ts +16 -7
- package/dist/decorators/inject.js +27 -22
- package/dist/decorators/injectable.d.ts +14 -18
- package/dist/decorators/injectable.js +23 -2
- package/dist/errors.d.ts +11 -2
- package/dist/errors.js +6 -3
- package/dist/index.d.ts +8 -7
- package/dist/index.js +3 -2
- package/dist/injection/dependency-slot.d.ts +17 -0
- package/dist/injection/dependency-slot.js +46 -0
- package/dist/injection/descriptor.d.ts +9 -3
- package/dist/injection/descriptor.js +10 -1
- package/dist/introspection/validation.d.ts +28 -0
- package/dist/introspection/validation.js +244 -0
- package/dist/lifecycle/hooks.d.ts +11 -2
- package/dist/lifecycle/hooks.js +30 -18
- package/dist/resolution/cache/class-introspector.d.ts +7 -8
- package/dist/resolution/cache/class-introspector.js +40 -3
- package/dist/resolution/cache/lookup.d.ts +10 -0
- package/dist/resolution/cache/lookup.js +27 -0
- package/dist/resolution/context.d.ts +12 -12
- package/dist/resolution/plan/codegen.d.ts +2 -1
- package/dist/resolution/plan/codegen.js +1 -1
- package/dist/resolution/plan/compiler.d.ts +6 -6
- package/dist/resolution/plan/compiler.js +152 -22
- package/dist/resolution/resolver.d.ts +2 -8
- package/dist/resolution/resolver.js +17 -93
- package/package.json +10 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,166 @@
|
|
|
1
1
|
# @codefast/di
|
|
2
2
|
|
|
3
|
+
## 0.15.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#1188](https://github.com/codefastlabs/codefast/pull/1188) Every `@codefast/*` package now requires Node.js 24.15 or later and drops Node 22. The packages ship as one set, so they
|
|
8
|
+
share one floor instead of each sitting on its own 22.x release. `@codefast/typescript-config` removes the `node22.json`
|
|
9
|
+
and `node22-dom.json` overlays; extend a preset alone. `codefast audit engines` reports a published package whose floor
|
|
10
|
+
differs from the highest one any published package declares.
|
|
11
|
+
|
|
12
|
+
## 0.14.0
|
|
13
|
+
|
|
14
|
+
### Minor Changes
|
|
15
|
+
|
|
16
|
+
- [#1101](https://github.com/codefastlabs/codefast/pull/1101) **Breaking:** an auto-register registry is now a `SyncModule`, and `Container#loadAutoRegistered` is removed.
|
|
17
|
+
`createAutoRegisterRegistry(name)` takes the module's display name, and the registry loads like any other module —
|
|
18
|
+
deduplicated by identity, ref-counted, and torn down by `unload()` / `unloadAsync()`, which deactivates every singleton
|
|
19
|
+
it bound. `loadAutoRegistered` was a bare bind loop: it could not be unloaded, and a second call rebound the whole set
|
|
20
|
+
over the first.
|
|
21
|
+
|
|
22
|
+
Migrate:
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
// before
|
|
26
|
+
const registry = createAutoRegisterRegistry();
|
|
27
|
+
const count = container.loadAutoRegistered(registry);
|
|
28
|
+
|
|
29
|
+
// after
|
|
30
|
+
const registry = createAutoRegisterRegistry("app:Services");
|
|
31
|
+
container.load(registry); // or Container.fromModules(registry)
|
|
32
|
+
const count = registry.entries().length; // if you used the returned count
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
A load binds the classes registered by then; a second `load()` of the same registry only adds a reference, so a class
|
|
36
|
+
decorated after the first load is bound by unloading the registry to zero and loading it again.
|
|
37
|
+
|
|
38
|
+
- [#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.
|
|
39
|
+
|
|
40
|
+
- `@injectable()` with no deps now compiles only on a class whose constructor needs nothing. It used to accept a class
|
|
41
|
+
with required parameters — a subclass inheriting its base's constructor included — and build it with those parameters
|
|
42
|
+
left `undefined`, silently. List the deps, as `@injectable([...])`.
|
|
43
|
+
- A `ModuleBuilder` and an `AsyncModuleBuilder` now narrow slot names as a container does: `whenNamed` inside
|
|
44
|
+
`Module.create` took any string. A container and both builders bind through one new `Binder` interface, so the three
|
|
45
|
+
can no longer drift apart.
|
|
46
|
+
- `toSelf()` exists only on a chain whose key is a class (`ClassBindToBuilder`); on a token it was accepted by the
|
|
47
|
+
compiler and threw `SelfBindingRequiresClassError` at runtime. An untyped caller still gets that error.
|
|
48
|
+
|
|
49
|
+
`Binder` and `ClassBindToBuilder` are exported from the package root. Runtime behaviour is unchanged.
|
|
50
|
+
|
|
51
|
+
- [#1101](https://github.com/codefastlabs/codefast/pull/1101) **Breaking:** `Container#dispose()` is renamed `disposeAsync()`. It returns a `Promise`, so the bare name broke the
|
|
52
|
+
package's own rule — unqualified is sync, the `Async` suffix is async — and the spec carried an exception for it that is
|
|
53
|
+
now gone. `disposeAsync` is the name TC39's `AsyncDisposableStack` gives the same method, and `[Symbol.asyncDispose]()`
|
|
54
|
+
still delegates to it, so `await using` is unchanged. Replace `await container.dispose()` with
|
|
55
|
+
`await container.disposeAsync()`; an `AggregateError` from a teardown with several throwing hooks now reads
|
|
56
|
+
"disposeAsync() completed, but deactivation hooks threw".
|
|
57
|
+
|
|
58
|
+
- [#1094](https://github.com/codefastlabs/codefast/pull/1094) **Breaking:** the `ContainerInterface` type export is removed. It aliased the `Container` interface, which `Container`
|
|
59
|
+
already exports under its own name beside the value, so replace `ContainerInterface` with `Container`.
|
|
60
|
+
|
|
61
|
+
- [#1063](https://github.com/codefastlabs/codefast/pull/1063) **Breaking:** `validate`, `inspect`, `lookupBindings`, `explain` and `generateDependencyGraph` are functions that take
|
|
62
|
+
the container instead of `Container` methods, so a bundle that only binds and resolves leaves them out: importing
|
|
63
|
+
`Container` and `token` alone drops from 23.2 KB to about 20.6 KB gzipped. `has` and `hasOwn` stay methods. Replace
|
|
64
|
+
`container.validate()` with `validate(container)`, `container.explain(token, options)` with
|
|
65
|
+
`explain(container, token, options)`, and likewise for the other three, importing each from `@codefast/di`. They refuse
|
|
66
|
+
a disposed container with `DisposedContainerError` as the methods did, and an object `Container` did not create with a
|
|
67
|
+
`TypeError`.
|
|
68
|
+
|
|
69
|
+
- [#1120](https://github.com/codefastlabs/codefast/pull/1120) **Breaking:** two spellings of the same API collapse into one.
|
|
70
|
+
|
|
71
|
+
- `Module` is the one module factory: `Module.create`, `Module.createAsync` and `Module.fromBindings`. The
|
|
72
|
+
`SyncModule.create`, `SyncModule.fromBindings` and `AsyncModule.create` companions are removed; `SyncModule` and
|
|
73
|
+
`AsyncModule` remain as the types those factories return. Replace `SyncModule.create(` with `Module.create(`,
|
|
74
|
+
`SyncModule.fromBindings(` with `Module.fromBindings(` and `AsyncModule.create(` with `Module.createAsync(`.
|
|
75
|
+
- `optional()` is renamed `injectOptional()`, so the descriptor family reads as the resolve family does —
|
|
76
|
+
`inject`/`injectOptional`/`injectAll` beside `resolve`/`resolveOptional`/`resolveAll`. Replace `optional(` with
|
|
77
|
+
`injectOptional(`.
|
|
78
|
+
|
|
79
|
+
- [#1111](https://github.com/codefastlabs/codefast/pull/1111) **Breaking:** a root-level `resolveAll` / `resolveAllAsync` with no options now hands every caller the same memoized
|
|
80
|
+
list while the chain and its activation hooks are unchanged, instead of a fresh copy per read. The result was already
|
|
81
|
+
typed `ReadonlyArray`; it is now read-only in fact, and a caller that needs a list of its own copies it (`[...list]`).
|
|
82
|
+
Dropping the copy reads `resolve-all-strategies-10` +22%, `resolve-all-strategies-100` +67% and
|
|
83
|
+
`production-event-bus-dispatch` +32% in a paired run, with the cold collection rows and the canaries level.
|
|
84
|
+
|
|
85
|
+
- [#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:
|
|
86
|
+
22.12 for `@codefast/cli` and `@codefast/tailwind-variants`, 22.18 for `@codefast/di` and `@codefast/di-testing`, and
|
|
87
|
+
22.22.2 for `@codefast/theme`, `@codefast/tracking` and `@codefast/ui`. Each floor is type-checked against what Node 22
|
|
88
|
+
ships and proven by running the package's tests on that release in CI.
|
|
89
|
+
|
|
90
|
+
### Patch Changes
|
|
91
|
+
|
|
92
|
+
- [#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
|
|
93
|
+
it before `new` and the accessor's `init` takes the value, instead of each accessor resolving again through the
|
|
94
|
+
container as the instance initializes. An accessor-injected class may now sit anywhere in a plan, not only at its root.
|
|
95
|
+
`@inject` returns an `init` rather than adding an initializer that writes through `context.access.set`, so the value is
|
|
96
|
+
the field's initial value. A standalone probe built with `tsc` puts one accessor at 46 ns → 31 ns per resolve and two at
|
|
97
|
+
59 ns → 41 ns; a paired run reads `accessor-injection-construct` +26%, with the canaries level. A custom
|
|
98
|
+
`MetadataReader`'s accessor records are not prepared, so such a class keeps resolving its accessors itself.
|
|
99
|
+
|
|
100
|
+
- [#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.
|
|
101
|
+
The plan keeps the interpreted async lane's order: the constructor params settle first, then the accessors resolve on
|
|
102
|
+
the sync lane and the class constructs. A standalone probe puts `resolveAsync` of a one-accessor class at 120 ns → 78
|
|
103
|
+
ns, against 66 ns for the same class taking its dependency as a constructor param.
|
|
104
|
+
|
|
105
|
+
- [#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
|
|
106
|
+
`Container#resolve` already did: inside `toDynamic((ctx) => ctx.resolve(LoggerToken, { name: "fiel" }))`, a name the
|
|
107
|
+
token does not declare is now a compile error instead of a `NoMatchingBindingError` at resolve time. A token that
|
|
108
|
+
declares no names, and a class key, still take any string.
|
|
109
|
+
|
|
110
|
+
- [#1100](https://github.com/codefastlabs/codefast/pull/1100) The README writes `validate`, `inspect` and the other introspection functions as the free functions they are —
|
|
111
|
+
`validate(container)` rather than a method-style `validate()` — and notes that guarding `validate(container)` with a
|
|
112
|
+
dev-only check keeps the introspection code out of a production bundle.
|
|
113
|
+
|
|
114
|
+
- [#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
|
|
115
|
+
decorators spec imported `optional` while calling `injectOptional`, and the modules spec imported `SyncModule` while
|
|
116
|
+
calling `Module.create`. They import what they call now.
|
|
117
|
+
|
|
118
|
+
- [#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 —
|
|
119
|
+
`tagKeyMaskOf`, `coversTagKeys` and `NO_TAG_KEYS`, the ones the built-in tag constraints use — with an example that
|
|
120
|
+
rules a parent out by its tag keys before comparing any value.
|
|
121
|
+
|
|
122
|
+
- [#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,
|
|
123
|
+
so a `switch (error.code)` is checked by the compiler and a misspelled code no longer compiles. An
|
|
124
|
+
`AsyncActivationError` raised by a `@postConstruct` hook now names the token it was building —
|
|
125
|
+
`@postConstruct method 'init' of 'app:Cache' returned a Promise` — where it named only the method.
|
|
126
|
+
|
|
127
|
+
- [#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
|
|
128
|
+
ancestor-registry list on every call, so they cost what the methods did before they became functions. A paired run
|
|
129
|
+
against the method-shaped build reads `lookup-bindings` at −2% and `inspect-snapshot` at −4%, from −13% and −9%.
|
|
130
|
+
|
|
131
|
+
- [#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
|
|
132
|
+
supplies their metadata without `Symbol.metadata`. Bun 1.4.2 and earlier still inject the wrong values into a module
|
|
133
|
+
holding two decorated classes; 1.4.3 fixes that, checked with two accessor-injected and two constructor-injected classes
|
|
134
|
+
in one module, run directly and after `bun build`.
|
|
135
|
+
|
|
136
|
+
- Move three cold paths out of the resolver to the modules they belong to: a class's constructor-parameter settle (and its
|
|
137
|
+
`MissingMetadataError`) to the class introspector, a root collection's stable-value check beside its memo in
|
|
138
|
+
`resolution/cache/lookup`, and `validate`'s miss check to `introspection/validation`, which reads the chain through the
|
|
139
|
+
new `DependencyResolver.bindingsForValidate()` in place of `missForValidate()`. `ARCHITECTURE.md` replaces the
|
|
140
|
+
resolver's line budget with the rule for what `resolution/resolver.ts` holds.
|
|
141
|
+
|
|
142
|
+
- [#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,
|
|
143
|
+
and a factory's dependencies when it is bound or declared, each with its resolve options and criterion already filled. A
|
|
144
|
+
process that has resolved many kinds of slot no longer meets the cold class lane megamorphic, so booting an application
|
|
145
|
+
gets faster where it was slowest — `app-boot-40` +13%, `realistic-graph-class-cold-resolve` +16% and the interpreted
|
|
146
|
+
`slot-injected-*` rows +31% in a paired run — with the warm rows level.
|
|
147
|
+
|
|
148
|
+
- [#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
|
|
149
|
+
`ResolutionContext` extend, so a call through a factory's `ctx` can never again narrow a token's slot names differently
|
|
150
|
+
from the same call on the container. Types only: the emitted JavaScript is unchanged.
|
|
151
|
+
|
|
152
|
+
- [#1101](https://github.com/codefastlabs/codefast/pull/1101) A sync `unbind()`, `unbindAll()`, `rebind()` or `unload()` that meets an async deactivation hook now runs every
|
|
153
|
+
deactivation stage of that instance — container `onDeactivation` hooks, the binding's own `onDeactivation`, then each
|
|
154
|
+
`@preDestroy()` — before it throws `AsyncDeactivationError`. It used to stop at the first stage that returned a promise,
|
|
155
|
+
and since the binding was already removed, the stages after it could never run. The error is still thrown, and each
|
|
156
|
+
returned promise is still left unawaited with its rejection swallowed, so use `unbindAsync()` / `unloadAsync()` wherever
|
|
157
|
+
a deactivation hook may be async.
|
|
158
|
+
|
|
159
|
+
- [#1109](https://github.com/codefastlabs/codefast/pull/1109) `validate`, `explain` and `generateDependencyGraph` read a container's internals from an object built once per container
|
|
160
|
+
instead of rebuilding it, with the ancestor-registry list, on every call. `validate` also walks the container's bindings
|
|
161
|
+
once rather than twice and allocates nothing for a container with no container-level hooks, so it costs less than the
|
|
162
|
+
`container.validate()` method did in 0.13.0.
|
|
163
|
+
|
|
3
164
|
## 0.13.0
|
|
4
165
|
|
|
5
166
|
### 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`, `
|
|
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
|
|
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 24.15 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.
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
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(
|
|
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`,
|
|
274
|
-
`injectAll` alike. Chain `.whenTagged(...)` once per criterion a slot carries, and request several
|
|
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
|
-
- `
|
|
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,
|
|
331
|
+
import { inject, injectable, injectAll, injectOptional, postConstruct, preDestroy } from "@codefast/di";
|
|
324
332
|
|
|
325
|
-
@injectable([DbToken,
|
|
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()
|
|
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
|
-
} //
|
|
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
|
|
427
|
-
|
|
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
|
-
|
|
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
|
-
`
|
|
446
|
-
token's bindings; and `
|
|
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
|
-
`
|
|
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 =
|
|
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.
|
|
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
|
|
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
|
|
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
|
-
|
|
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 {
|
|
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
|
|
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
|
|
158
|
+
this.deps = settledDescriptorsOf(deps);
|
|
159
159
|
return this.#register("resolved-async", "transient");
|
|
160
160
|
}
|
|
161
161
|
toAlias(target) {
|