@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.
- package/CHANGELOG.md +192 -0
- package/README.md +142 -43
- 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 -30
- package/dist/container/container.js +59 -243
- package/dist/container/introspect.d.ts +47 -0
- package/dist/container/introspect.js +53 -0
- package/dist/core/binding-builders.d.ts +27 -3
- package/dist/core/binding-declaration.d.ts +2 -2
- package/dist/core/binding-declaration.js +4 -4
- 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.d.ts +3 -1
- package/dist/decorators/inject.js +27 -22
- package/dist/decorators/injectable.d.ts +14 -18
- package/dist/decorators/injectable.js +23 -2
- package/dist/decorators/lifecycle.d.ts +9 -3
- package/dist/decorators/lifecycle.js +5 -1
- package/dist/errors.d.ts +33 -15
- package/dist/errors.js +41 -21
- package/dist/index.d.ts +9 -8
- package/dist/index.js +4 -3
- 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/explanation.js +26 -8
- package/dist/introspection/validation.d.ts +28 -0
- package/dist/introspection/validation.js +244 -0
- package/dist/lifecycle/hooks.d.ts +13 -2
- package/dist/lifecycle/hooks.js +36 -18
- package/dist/lifecycle/scopes.d.ts +21 -2
- package/dist/lifecycle/scopes.js +86 -2
- package/dist/metadata/keys.d.ts +1 -1
- package/dist/metadata/keys.js +1 -1
- 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/path.d.ts +12 -2
- package/dist/resolution/path.js +22 -2
- 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 +6 -0
- package/dist/resolution/resolver.js +39 -84
- package/package.json +11 -3
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import { bindingSlotToString, effectiveBindingScope } from "#core/binding";
|
|
2
|
+
import { constraintRequirementsOf } from "#core/constraint-requirement";
|
|
3
|
+
import { getOrInsertComputed } from "#core/map-upsert";
|
|
4
|
+
import { tokenName } from "#core/token";
|
|
5
|
+
import { CircularDependencyError, InternalError, NoMatchingBindingError, ScopeViolationError, TokenNotBoundError, UnreachableConstraintError, UnreachableLifecycleHookError, } from "#errors";
|
|
6
|
+
import { injectionSlotToResolveOptions } from "#injection/dependency-slot";
|
|
7
|
+
import { matchesSlot } from "#resolution/select/candidates";
|
|
8
|
+
/**
|
|
9
|
+
* Runs every static check over a container's chain, throwing the first error a resolve would meet.
|
|
10
|
+
*
|
|
11
|
+
* @throws `CircularDependencyError`, `ScopeViolationError`, `TokenNotBoundError` or `NoMatchingBindingError` for a
|
|
12
|
+
* singleton graph that cannot resolve, `UnreachableLifecycleHookError` or `UnreachableConstraintError` for a hook or
|
|
13
|
+
* constraint that can never fire.
|
|
14
|
+
*
|
|
15
|
+
* @since 0.14.0
|
|
16
|
+
*/
|
|
17
|
+
export function validateChain(target) {
|
|
18
|
+
// One pass over the bindings; the constrained ones wait for the hook check, so the errors keep their order.
|
|
19
|
+
let constrained;
|
|
20
|
+
for (const binding of target.registries[0].allBindings()) {
|
|
21
|
+
if (isSingletonStaticAnalyzableBinding(binding)) {
|
|
22
|
+
validateSingletonBindingGraph(binding, target.resolver, target.metadataReader);
|
|
23
|
+
}
|
|
24
|
+
if (binding.predicate !== undefined) {
|
|
25
|
+
(constrained ??= []).push(binding);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
for (const [hookToken, phase] of target.lifecycle.hookedTokens()) {
|
|
29
|
+
if (!isBoundInChain(target.registries, hookToken)) {
|
|
30
|
+
throw new UnreachableLifecycleHookError(tokenName(hookToken), phase);
|
|
31
|
+
}
|
|
32
|
+
// A deactivation never runs for a transient, so a hook on a token whose every binding is transient
|
|
33
|
+
// can never fire — the builder blocks it, `container.onDeactivation` cannot.
|
|
34
|
+
if (phase === "onDeactivation" && !hasDeactivatableBindingInChain(target.registries, hookToken)) {
|
|
35
|
+
throw new UnreachableLifecycleHookError(tokenName(hookToken), phase, "no-deactivatable-binding");
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
if (constrained !== undefined) {
|
|
39
|
+
validateConstraintRequirements(constrained, target.registries);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** A constraint waiting on a slot name no binding declares can never hold. */
|
|
43
|
+
function validateConstraintRequirements(constrained, registries) {
|
|
44
|
+
let declaredSlotNames;
|
|
45
|
+
for (const binding of constrained) {
|
|
46
|
+
const { predicate } = binding;
|
|
47
|
+
if (predicate === undefined) {
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
const requirements = constraintRequirementsOf(predicate);
|
|
51
|
+
if (requirements.length === 0) {
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
declaredSlotNames ??= slotNamesInChain(registries);
|
|
55
|
+
for (const requirement of requirements) {
|
|
56
|
+
if (!isSlotNameDeclared(declaredSlotNames, requirement)) {
|
|
57
|
+
throw new UnreachableConstraintError(tokenName(binding.token), requirement);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/** Every slot name declared anywhere a resolve through this container could reach, by declaring token. */
|
|
63
|
+
function slotNamesInChain(registries) {
|
|
64
|
+
const names = new Map();
|
|
65
|
+
for (const registry of registries) {
|
|
66
|
+
for (const binding of registry.allBindings()) {
|
|
67
|
+
const name = binding.slot.name;
|
|
68
|
+
if (name !== undefined) {
|
|
69
|
+
getOrInsertComputed(names, tokenName(binding.token), newSlotNameSet).add(name);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return names;
|
|
74
|
+
}
|
|
75
|
+
/** Hoisted so the slot-name index's `getOrInsertComputed` allocates only on a miss, no closure per call. */
|
|
76
|
+
const newSlotNameSet = () => new Set();
|
|
77
|
+
/** Whether a requirement's name is declared — on its token when it names one, on any token otherwise. */
|
|
78
|
+
function isSlotNameDeclared(declared, requirement) {
|
|
79
|
+
if (requirement.tokenName !== undefined) {
|
|
80
|
+
return declared.get(requirement.tokenName)?.has(requirement.name) ?? false;
|
|
81
|
+
}
|
|
82
|
+
for (const names of declared.values()) {
|
|
83
|
+
if (names.has(requirement.name)) {
|
|
84
|
+
return true;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
// Ancestors count: a parent-owned binding is one this container can still resolve through.
|
|
90
|
+
function isBoundInChain(registries, token) {
|
|
91
|
+
return registries.some((registry) => registry.has(token));
|
|
92
|
+
}
|
|
93
|
+
// Whether the token has a binding a deactivation hook can run for — anything but a transient.
|
|
94
|
+
function hasDeactivatableBindingInChain(registries, token) {
|
|
95
|
+
return registries.some((registry) => registry.getAll(token).some((binding) => effectiveBindingScope(binding) !== "transient"));
|
|
96
|
+
}
|
|
97
|
+
function isSingletonStaticAnalyzableBinding(binding) {
|
|
98
|
+
if (effectiveBindingScope(binding) !== "singleton") {
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
return binding.kind === "class" || binding.kind === "resolved" || binding.kind === "resolved-async";
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* DFS over explicit constructor / `toResolved*` dependency edges, following `toAlias` chains to the terminal binding.
|
|
105
|
+
*
|
|
106
|
+
* @remarks Every binding reached is a singleton resolved from its owner's chain, so a required miss or a repeat
|
|
107
|
+
* on one path fails however the graph is entered; a `toDynamic*` edge is scope-checked, its factory not descended.
|
|
108
|
+
*/
|
|
109
|
+
function validateSingletonBindingGraph(root, resolver, reader) {
|
|
110
|
+
const rootName = tokenName(root.token);
|
|
111
|
+
const dfs = (current, view, pathNames, pathBindingIds) => {
|
|
112
|
+
if (pathBindingIds.has(current.identifier)) {
|
|
113
|
+
throw new CircularDependencyError(pathNames);
|
|
114
|
+
}
|
|
115
|
+
const extendedPathIds = new Set(pathBindingIds);
|
|
116
|
+
extendedPathIds.add(current.identifier);
|
|
117
|
+
for (const edge of collectStaticDependencyEdges(current, view, reader, pathNames)) {
|
|
118
|
+
const { terminal, owner, depTokenName } = edge;
|
|
119
|
+
const depScope = validationScopeFromTerminal(terminal);
|
|
120
|
+
if (depScope !== "singleton") {
|
|
121
|
+
throw new ScopeViolationError({
|
|
122
|
+
consumerToken: rootName,
|
|
123
|
+
consumerScope: "singleton",
|
|
124
|
+
dependencyToken: depTokenName,
|
|
125
|
+
dependencyScope: depScope,
|
|
126
|
+
path: [...pathNames, depTokenName],
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
if (terminal.kind === "class" || terminal.kind === "resolved" || terminal.kind === "resolved-async") {
|
|
130
|
+
dfs(terminal, owner, [...pathNames, depTokenName], extendedPathIds);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
dfs(root, resolver, [rootName], new Set());
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* The scope this edge is judged against.
|
|
138
|
+
*
|
|
139
|
+
* @remarks A factory's *body* is not statically analyzable, but the scope it was bound with is
|
|
140
|
+
* declared like any other — so the captive-dependency check applies to it too. The DFS still
|
|
141
|
+
* refuses to descend into a factory; only the edge is judged.
|
|
142
|
+
*/
|
|
143
|
+
function validationScopeFromTerminal(terminal) {
|
|
144
|
+
if (terminal.kind === "alias") {
|
|
145
|
+
throw new InternalError("validate: expected terminal binding after alias resolution");
|
|
146
|
+
}
|
|
147
|
+
return terminal.scope;
|
|
148
|
+
}
|
|
149
|
+
/** Where an alias chain ends as `resolve` walks it from `view`: its terminal binding, or the names up to a miss. */
|
|
150
|
+
function followAliasChainToTerminal(entry, view, options) {
|
|
151
|
+
const cyclePath = [];
|
|
152
|
+
const seenAliasIds = new Set();
|
|
153
|
+
let current = entry;
|
|
154
|
+
while (current.binding.kind === "alias") {
|
|
155
|
+
const alias = current.binding;
|
|
156
|
+
if (seenAliasIds.has(alias.identifier)) {
|
|
157
|
+
throw new CircularDependencyError(cyclePath);
|
|
158
|
+
}
|
|
159
|
+
seenAliasIds.add(alias.identifier);
|
|
160
|
+
cyclePath.push(tokenName(alias.token));
|
|
161
|
+
const next = view.peekBindingForValidate(alias.target, options);
|
|
162
|
+
if (next === undefined) {
|
|
163
|
+
return { found: false, missingToken: alias.target, hopNames: cyclePath };
|
|
164
|
+
}
|
|
165
|
+
current = next;
|
|
166
|
+
}
|
|
167
|
+
return { found: true, terminal: current.binding, owner: current.owner };
|
|
168
|
+
}
|
|
169
|
+
/** What one dependency could resolve to from `view`: every candidate for `injectAll`, else at most one. */
|
|
170
|
+
function peekDependencyCandidates(dep, view, options) {
|
|
171
|
+
if (dep.multi) {
|
|
172
|
+
return view
|
|
173
|
+
.peekCandidateBindingsForValidate(dep.token, options)
|
|
174
|
+
.map((binding) => ({ binding, owner: view.ownerForValidate(binding) }));
|
|
175
|
+
}
|
|
176
|
+
const found = view.peekBindingForValidate(dep.token, options);
|
|
177
|
+
return found === undefined ? [] : [found];
|
|
178
|
+
}
|
|
179
|
+
/** What a binding declares up front — a class's params, a factory's descriptors, else nothing. */
|
|
180
|
+
function staticDependencies(binding, reader) {
|
|
181
|
+
if (binding.kind === "class") {
|
|
182
|
+
return reader.getConstructorMetadata(binding.target)?.params ?? [];
|
|
183
|
+
}
|
|
184
|
+
if (binding.kind === "resolved" || binding.kind === "resolved-async") {
|
|
185
|
+
return binding.deps;
|
|
186
|
+
}
|
|
187
|
+
return [];
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* The error `resolve` raises for a request nothing selects, or `undefined` while a `when()` candidate leaves it open.
|
|
191
|
+
*
|
|
192
|
+
* @remarks A predicate reads the resolution path, which a static walk does not have, so a slot-matching candidate
|
|
193
|
+
* that carries one may still be selected when the request is really made.
|
|
194
|
+
*/
|
|
195
|
+
function missForValidate(view, token, options, path) {
|
|
196
|
+
const bound = view.bindingsForValidate(token);
|
|
197
|
+
if (bound.length === 0) {
|
|
198
|
+
return new TokenNotBoundError(tokenName(token), path);
|
|
199
|
+
}
|
|
200
|
+
for (const binding of bound) {
|
|
201
|
+
if (binding.predicate !== undefined && !binding.isMany && matchesSlot(binding.slot, options)) {
|
|
202
|
+
return undefined;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return new NoMatchingBindingError(tokenName(token), options ?? {}, bound.map((binding) => bindingSlotToString(binding.slot)), path);
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* The bindings a singleton's declared dependencies resolve to, throwing the error `resolve` would for a required one
|
|
209
|
+
* nothing selects.
|
|
210
|
+
*/
|
|
211
|
+
function collectStaticDependencyEdges(binding, view, reader, pathNames) {
|
|
212
|
+
const edges = [];
|
|
213
|
+
for (const dep of staticDependencies(binding, reader)) {
|
|
214
|
+
// An optional dependency that is absent peeks no candidate; one that is bound is captured like any other.
|
|
215
|
+
const depOptions = injectionSlotToResolveOptions(dep);
|
|
216
|
+
// A collection may be empty and an optional dependency absent, so only a required one can miss.
|
|
217
|
+
const required = !dep.multi && !dep.optional;
|
|
218
|
+
const candidates = peekDependencyCandidates(dep, view, depOptions);
|
|
219
|
+
if (required && candidates.length === 0) {
|
|
220
|
+
const miss = missForValidate(view, dep.token, depOptions, [...pathNames, tokenName(dep.token)]);
|
|
221
|
+
if (miss !== undefined) {
|
|
222
|
+
throw miss;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
for (const candidate of candidates) {
|
|
226
|
+
const end = followAliasChainToTerminal(candidate, view, depOptions);
|
|
227
|
+
if (end.found) {
|
|
228
|
+
edges.push({ terminal: end.terminal, owner: end.owner, depTokenName: tokenName(end.terminal.token) });
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
if (required) {
|
|
232
|
+
const miss = missForValidate(view, end.missingToken, depOptions, [
|
|
233
|
+
...pathNames,
|
|
234
|
+
...end.hopNames,
|
|
235
|
+
tokenName(end.missingToken),
|
|
236
|
+
]);
|
|
237
|
+
if (miss !== undefined) {
|
|
238
|
+
throw miss;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
return edges;
|
|
244
|
+
}
|
|
@@ -2,6 +2,8 @@ import type { Binding } from "#core/binding";
|
|
|
2
2
|
import type { Token } from "#core/token";
|
|
3
3
|
import type { ActivationHandler, Constructor, DeactivationHandler, DependencyKey, ResolutionContext } from "#core/types";
|
|
4
4
|
import type { MetadataReader } from "#metadata/types";
|
|
5
|
+
/** A token carrying a container-level hook, paired with the phase that registered it. */
|
|
6
|
+
type HookedToken = readonly [DependencyKey, "onActivation" | "onDeactivation"];
|
|
5
7
|
/**
|
|
6
8
|
* One container's registry of container-level activation and deactivation hooks, keyed by token.
|
|
7
9
|
*
|
|
@@ -17,8 +19,10 @@ export declare class LifecycleManager {
|
|
|
17
19
|
registerDeactivation<Value>(token: Token<Value> | Constructor<Value>, handler: DeactivationHandler<Value>): void;
|
|
18
20
|
/** Asked only while tearing down, so it reads the map directly rather than caching like activation. */
|
|
19
21
|
hasDeactivationHandlers<Value>(token: Token<Value> | Constructor<Value>): boolean;
|
|
22
|
+
/** Whether deactivating an instance of a binding runs anything: a container hook, the binding's own, or `@preDestroy()`. */
|
|
23
|
+
owesDeactivation(binding: Binding, metadataReader: MetadataReader): boolean;
|
|
20
24
|
/** Every token carrying a container-level hook, paired with the phase that registered it. */
|
|
21
|
-
hookedTokens():
|
|
25
|
+
hookedTokens(): ReadonlyArray<HookedToken>;
|
|
22
26
|
/**
|
|
23
27
|
* Runs the activation pipeline on the async lane: the activated instance, or its promise once a
|
|
24
28
|
* hook has returned one.
|
|
@@ -29,7 +33,14 @@ export declare class LifecycleManager {
|
|
|
29
33
|
runActivation<Value>(resolutionContext: ResolutionContext, binding: Binding<Value>, instance: Value, metadataReader: MetadataReader): Value | Promise<Value>;
|
|
30
34
|
runActivationSync<Value>(resolutionContext: ResolutionContext, binding: Binding<Value>, instance: Value, metadataReader: MetadataReader): Value;
|
|
31
35
|
runDeactivation<Value>(binding: Binding<Value>, instance: Value, metadataReader: MetadataReader): Promise<void>;
|
|
36
|
+
/**
|
|
37
|
+
* Runs the deactivation pipeline on the sync lane.
|
|
38
|
+
*
|
|
39
|
+
* @remarks A stage that returns a promise does not stop the ones after it: the binding is already
|
|
40
|
+
* gone, so nothing could run them later. Every stage runs, then one `AsyncDeactivationError` reports it.
|
|
41
|
+
*/
|
|
32
42
|
runDeactivationSync<Value>(binding: Binding<Value>, instance: Value, metadataReader: MetadataReader): void;
|
|
33
43
|
/** Whether the deferred activation-hook table has had to be built. */
|
|
34
44
|
get isActivationTableBuilt(): boolean;
|
|
35
|
-
}
|
|
45
|
+
}
|
|
46
|
+
export {};
|
package/dist/lifecycle/hooks.js
CHANGED
|
@@ -2,6 +2,7 @@ import { getOrInsert } from "#core/map-upsert";
|
|
|
2
2
|
import { advanceStateEpoch } from "#core/state-epoch";
|
|
3
3
|
import { tokenName } from "#core/token";
|
|
4
4
|
import { AsyncActivationError, AsyncDeactivationError, InvalidMetadataError } from "#errors";
|
|
5
|
+
const NO_HOOKED_TOKENS = [];
|
|
5
6
|
/**
|
|
6
7
|
* One container's registry of container-level activation and deactivation hooks, keyed by token.
|
|
7
8
|
*
|
|
@@ -62,8 +63,18 @@ export class LifecycleManager {
|
|
|
62
63
|
const list = this.#deactivationHooks?.get(token);
|
|
63
64
|
return list !== undefined && list.length > 0;
|
|
64
65
|
}
|
|
66
|
+
/** Whether deactivating an instance of a binding runs anything: a container hook, the binding's own, or `@preDestroy()`. */
|
|
67
|
+
owesDeactivation(binding, metadataReader) {
|
|
68
|
+
return (this.hasDeactivationHandlers(binding.token) ||
|
|
69
|
+
(binding.kind !== "alias" && binding.deactivationHook !== undefined) ||
|
|
70
|
+
this.#lifecycleMethods(binding, metadataReader, "preDestroy").length > 0);
|
|
71
|
+
}
|
|
65
72
|
/** Every token carrying a container-level hook, paired with the phase that registered it. */
|
|
66
73
|
hookedTokens() {
|
|
74
|
+
// Read on every `validate`, and most containers register no hook.
|
|
75
|
+
if (this.#activationHooks === undefined && this.#deactivationHooks === undefined) {
|
|
76
|
+
return NO_HOOKED_TOKENS;
|
|
77
|
+
}
|
|
67
78
|
const hooked = [];
|
|
68
79
|
for (const key of this.#activationHooks?.keys() ?? []) {
|
|
69
80
|
hooked.push([key, "onActivation"]);
|
|
@@ -82,7 +93,7 @@ export class LifecycleManager {
|
|
|
82
93
|
*/
|
|
83
94
|
runActivation(resolutionContext, binding, instance, metadataReader) {
|
|
84
95
|
let activated = instance;
|
|
85
|
-
// 1. @postConstruct() — after TC39 construction (
|
|
96
|
+
// 1. @postConstruct() — after TC39 construction (accessor initial values + constructor)
|
|
86
97
|
for (const methodName of this.#lifecycleMethods(binding, metadataReader, "postConstruct")) {
|
|
87
98
|
activated = afterActivationStep(activated, (current) => {
|
|
88
99
|
const hookResult = callHook(current, methodName);
|
|
@@ -164,36 +175,32 @@ export class LifecycleManager {
|
|
|
164
175
|
}
|
|
165
176
|
}
|
|
166
177
|
}
|
|
178
|
+
/**
|
|
179
|
+
* Runs the deactivation pipeline on the sync lane.
|
|
180
|
+
*
|
|
181
|
+
* @remarks A stage that returns a promise does not stop the ones after it: the binding is already
|
|
182
|
+
* gone, so nothing could run them later. Every stage runs, then one `AsyncDeactivationError` reports it.
|
|
183
|
+
*/
|
|
167
184
|
runDeactivationSync(binding, instance, metadataReader) {
|
|
168
185
|
const tokenKey = binding.token;
|
|
186
|
+
let returnedPromise = false;
|
|
169
187
|
// 1. container-level onDeactivation
|
|
170
188
|
const containerHooks = this.#deactivationHooks?.get(tokenKey);
|
|
171
189
|
if (containerHooks !== undefined) {
|
|
172
190
|
for (const hook of containerHooks) {
|
|
173
|
-
|
|
174
|
-
if (hookResult instanceof Promise) {
|
|
175
|
-
// The hook has already run; adopt its rejection so a failing async hook cannot become an
|
|
176
|
-
// unhandled rejection that ends the process, then report the sync-lane violation.
|
|
177
|
-
void hookResult.catch(() => { });
|
|
178
|
-
throw new AsyncDeactivationError(tokenName(binding.token));
|
|
179
|
-
}
|
|
191
|
+
returnedPromise = adoptPromise(hook(instance)) || returnedPromise;
|
|
180
192
|
}
|
|
181
193
|
}
|
|
182
194
|
// 2. per-binding onDeactivation
|
|
183
195
|
if (binding.kind !== "alias" && binding.deactivationHook !== undefined) {
|
|
184
|
-
|
|
185
|
-
if (hookResult instanceof Promise) {
|
|
186
|
-
void hookResult.catch(() => { });
|
|
187
|
-
throw new AsyncDeactivationError(tokenName(binding.token));
|
|
188
|
-
}
|
|
196
|
+
returnedPromise = adoptPromise(binding.deactivationHook(instance)) || returnedPromise;
|
|
189
197
|
}
|
|
190
198
|
// 3. @preDestroy()
|
|
191
199
|
for (const methodName of this.#lifecycleMethods(binding, metadataReader, "preDestroy")) {
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
}
|
|
200
|
+
returnedPromise = adoptPromise(callHook(instance, methodName)) || returnedPromise;
|
|
201
|
+
}
|
|
202
|
+
if (returnedPromise) {
|
|
203
|
+
throw new AsyncDeactivationError(tokenName(binding.token));
|
|
197
204
|
}
|
|
198
205
|
}
|
|
199
206
|
/** The `@postConstruct` / `@preDestroy` methods a binding declares — only a class can declare any. */
|
|
@@ -215,6 +222,17 @@ export class LifecycleManager {
|
|
|
215
222
|
}
|
|
216
223
|
}
|
|
217
224
|
const NO_METHODS = [];
|
|
225
|
+
/**
|
|
226
|
+
* Whether a sync-lane hook returned a promise, adopting its rejection so it cannot end the process
|
|
227
|
+
* as an unhandled one.
|
|
228
|
+
*/
|
|
229
|
+
function adoptPromise(hookResult) {
|
|
230
|
+
if (hookResult instanceof Promise) {
|
|
231
|
+
void hookResult.catch(() => { });
|
|
232
|
+
return true;
|
|
233
|
+
}
|
|
234
|
+
return false;
|
|
235
|
+
}
|
|
218
236
|
/** Applies one activation step now, or once the step before it has settled. */
|
|
219
237
|
function afterActivationStep(activated, step) {
|
|
220
238
|
return activated instanceof Promise ? activated.then(step) : step(activated);
|
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
import type { Binding } from "#core/binding";
|
|
2
2
|
import type { BindingIdentifier } from "#core/types";
|
|
3
|
+
/**
|
|
4
|
+
* What deactivates a scoped instance: the resolver owning its binding, which activated it.
|
|
5
|
+
*
|
|
6
|
+
* @remarks Answers `undefined` when the binding owes no teardown, so disposing a per-request child awaits nothing.
|
|
7
|
+
*
|
|
8
|
+
* @since 0.13.0
|
|
9
|
+
*/
|
|
10
|
+
export interface ScopedInstanceOwner {
|
|
11
|
+
deactivateScoped(binding: Binding, instance: unknown): Promise<void> | undefined;
|
|
12
|
+
}
|
|
3
13
|
/**
|
|
4
14
|
* One container's instance caches — singletons, in-flight async creations, and the scoped cache.
|
|
5
15
|
*
|
|
@@ -28,9 +38,18 @@ export declare class ScopeManager {
|
|
|
28
38
|
*/
|
|
29
39
|
readScoped(key: BindingIdentifier): unknown;
|
|
30
40
|
/** Takes the binding rather than its id, so a failure here can name the token — as `setSingleton` does. */
|
|
31
|
-
setScoped(binding: Binding, instance: unknown): void;
|
|
32
|
-
/**
|
|
41
|
+
setScoped(binding: Binding, instance: unknown, owner: ScopedInstanceOwner): void;
|
|
42
|
+
/** Drops the instance cached under a scoped cache key, owing it nothing — what a binding leaving `scoped` retires. */
|
|
33
43
|
deleteScoped(key: BindingIdentifier): void;
|
|
44
|
+
/** Removes the instance cached under a scoped cache key and hands it back, or {@link SCOPED_MISS} when none is. */
|
|
45
|
+
takeScoped(key: BindingIdentifier): unknown;
|
|
46
|
+
/**
|
|
47
|
+
* Deactivates every cached scoped instance through its owner, the latest cached first and one at a time, collecting
|
|
48
|
+
* each failure into `errors` — or answers `undefined` when no owner had a teardown to run.
|
|
49
|
+
*
|
|
50
|
+
* @remarks A binding cached again after its instance was taken is listed twice; only its current instance is owed.
|
|
51
|
+
*/
|
|
52
|
+
deactivateScoped(errors: Array<unknown>): Promise<void> | undefined;
|
|
34
53
|
/** Scoped instances currently cached — a structural count for diagnostics. */
|
|
35
54
|
get scopedCount(): number;
|
|
36
55
|
clearAll(): void;
|
package/dist/lifecycle/scopes.js
CHANGED
|
@@ -13,6 +13,12 @@ export class ScopeManager {
|
|
|
13
13
|
#inflight;
|
|
14
14
|
// Scoped cache — only a child container resolving a `scoped` binding ever needs it.
|
|
15
15
|
#scoped;
|
|
16
|
+
// Scoped bindings in the order their instances were cached, each beside its owner, so disposal can deactivate them
|
|
17
|
+
// latest first. The first sits in fields: a per-request child caching one scoped instance allocates nothing for it.
|
|
18
|
+
#firstScopedBinding;
|
|
19
|
+
#firstScopedOwner;
|
|
20
|
+
#laterScopedBindings;
|
|
21
|
+
#laterScopedOwners;
|
|
16
22
|
// Set once by the owning container's dispose — refuses new materializations into torn-down state.
|
|
17
23
|
#closed = false;
|
|
18
24
|
isChild;
|
|
@@ -101,16 +107,90 @@ export class ScopeManager {
|
|
|
101
107
|
return scoped.has(key) ? undefined : SCOPED_MISS;
|
|
102
108
|
}
|
|
103
109
|
/** Takes the binding rather than its id, so a failure here can name the token — as `setSingleton` does. */
|
|
104
|
-
setScoped(binding, instance) {
|
|
110
|
+
setScoped(binding, instance, owner) {
|
|
105
111
|
if (!this.isChild) {
|
|
106
112
|
throw new MissingScopeContextError(tokenName(binding.token));
|
|
107
113
|
}
|
|
108
114
|
(this.#scoped ??= new Map()).set(binding.scopedCacheKey, instance);
|
|
115
|
+
if (this.#firstScopedBinding === undefined) {
|
|
116
|
+
this.#firstScopedBinding = binding;
|
|
117
|
+
this.#firstScopedOwner = owner;
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
(this.#laterScopedBindings ??= []).push(binding);
|
|
121
|
+
(this.#laterScopedOwners ??= []).push(owner);
|
|
122
|
+
}
|
|
109
123
|
}
|
|
110
|
-
/**
|
|
124
|
+
/** Drops the instance cached under a scoped cache key, owing it nothing — what a binding leaving `scoped` retires. */
|
|
111
125
|
deleteScoped(key) {
|
|
112
126
|
this.#scoped?.delete(key);
|
|
113
127
|
}
|
|
128
|
+
/** Removes the instance cached under a scoped cache key and hands it back, or {@link SCOPED_MISS} when none is. */
|
|
129
|
+
takeScoped(key) {
|
|
130
|
+
const scoped = this.#scoped;
|
|
131
|
+
if (scoped === undefined || !scoped.has(key)) {
|
|
132
|
+
return SCOPED_MISS;
|
|
133
|
+
}
|
|
134
|
+
const instance = scoped.get(key);
|
|
135
|
+
scoped.delete(key);
|
|
136
|
+
return instance;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Deactivates every cached scoped instance through its owner, the latest cached first and one at a time, collecting
|
|
140
|
+
* each failure into `errors` — or answers `undefined` when no owner had a teardown to run.
|
|
141
|
+
*
|
|
142
|
+
* @remarks A binding cached again after its instance was taken is listed twice; only its current instance is owed.
|
|
143
|
+
*/
|
|
144
|
+
deactivateScoped(errors) {
|
|
145
|
+
if (this.#firstScopedBinding === undefined) {
|
|
146
|
+
return undefined;
|
|
147
|
+
}
|
|
148
|
+
return this.#deactivateScopedFrom(this.#laterScopedBindings?.length ?? 0, errors);
|
|
149
|
+
}
|
|
150
|
+
// Positions count down from the latest: `position - 1` in the later lists while positive, then the first at 0.
|
|
151
|
+
#deactivateScopedFrom(position, errors) {
|
|
152
|
+
for (let current = position; current >= 0; current -= 1) {
|
|
153
|
+
const pending = this.#deactivateScopedAt(current, errors);
|
|
154
|
+
if (pending !== undefined) {
|
|
155
|
+
return this.#finishDeactivatingScoped(pending, current - 1, errors);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return undefined;
|
|
159
|
+
}
|
|
160
|
+
// The rest of the walk once a teardown is pending: each one settles before the next starts.
|
|
161
|
+
async #finishDeactivatingScoped(pending, position, errors) {
|
|
162
|
+
let current = pending;
|
|
163
|
+
for (let next = position;; next -= 1) {
|
|
164
|
+
if (current !== undefined) {
|
|
165
|
+
try {
|
|
166
|
+
await current;
|
|
167
|
+
}
|
|
168
|
+
catch (error) {
|
|
169
|
+
errors.push(error);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
if (next < 0) {
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
current = this.#deactivateScopedAt(next, errors);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
#deactivateScopedAt(position, errors) {
|
|
179
|
+
const binding = position === 0 ? this.#firstScopedBinding : this.#laterScopedBindings[position - 1];
|
|
180
|
+
const owner = position === 0 ? this.#firstScopedOwner : this.#laterScopedOwners[position - 1];
|
|
181
|
+
// The first is read last, so only a later entry can find a key cached twice; taking it leaves the rest a miss.
|
|
182
|
+
const instance = position === 0 ? this.readScoped(binding.scopedCacheKey) : this.takeScoped(binding.scopedCacheKey);
|
|
183
|
+
if (instance === SCOPED_MISS) {
|
|
184
|
+
return undefined;
|
|
185
|
+
}
|
|
186
|
+
try {
|
|
187
|
+
return owner.deactivateScoped(binding, instance);
|
|
188
|
+
}
|
|
189
|
+
catch (error) {
|
|
190
|
+
errors.push(error);
|
|
191
|
+
return undefined;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
114
194
|
/** Scoped instances currently cached — a structural count for diagnostics. */
|
|
115
195
|
get scopedCount() {
|
|
116
196
|
return this.#scoped?.size ?? 0;
|
|
@@ -126,6 +206,10 @@ export class ScopeManager {
|
|
|
126
206
|
}
|
|
127
207
|
this.#inflight?.clear();
|
|
128
208
|
this.#scoped?.clear();
|
|
209
|
+
this.#firstScopedBinding = undefined;
|
|
210
|
+
this.#firstScopedOwner = undefined;
|
|
211
|
+
this.#laterScopedBindings = undefined;
|
|
212
|
+
this.#laterScopedOwners = undefined;
|
|
129
213
|
}
|
|
130
214
|
/** Whether the deferred scoped-instance cache has had to be built. */
|
|
131
215
|
get isScopedCacheBuilt() {
|
package/dist/metadata/keys.d.ts
CHANGED
|
@@ -17,7 +17,7 @@ export declare const LIFECYCLE_KEY: unique symbol;
|
|
|
17
17
|
*/
|
|
18
18
|
export declare const INJECT_ACCESSOR_KEY: unique symbol;
|
|
19
19
|
/**
|
|
20
|
-
* The symbol
|
|
20
|
+
* The symbol standard decorator transforms store class metadata under.
|
|
21
21
|
*
|
|
22
22
|
* @remarks Falls back to the global-registry symbol, which is what Babel and esbuild emit until
|
|
23
23
|
* a runtime ships `Symbol.metadata` natively.
|
package/dist/metadata/keys.js
CHANGED
|
@@ -17,7 +17,7 @@ export const LIFECYCLE_KEY = Symbol("di:lifecycle");
|
|
|
17
17
|
*/
|
|
18
18
|
export const INJECT_ACCESSOR_KEY = Symbol("di:inject-accessor");
|
|
19
19
|
/**
|
|
20
|
-
* The symbol
|
|
20
|
+
* The symbol standard decorator transforms store class metadata under.
|
|
21
21
|
*
|
|
22
22
|
* @remarks Falls back to the global-registry symbol, which is what Babel and esbuild emit until
|
|
23
23
|
* a runtime ships `Symbol.metadata` natively.
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import type { AmbientResolution } from "#ambient-container";
|
|
7
7
|
import type { Container } from "#container/container";
|
|
8
8
|
import type { Constructor } from "#core/types";
|
|
9
|
+
import type { DependencySlot } from "#injection/dependency-slot";
|
|
9
10
|
import type { ConstructorMetadata, MetadataReader, ParamMetadata } from "#metadata/types";
|
|
10
11
|
/**
|
|
11
12
|
* What one reader has answered about one class so far, each field unknown until first asked.
|
|
@@ -42,16 +43,12 @@ export declare class ClassIntrospector {
|
|
|
42
43
|
/** The constructor metadata of a class whose facts the caller already holds. */
|
|
43
44
|
constructorMetadataOf(target: Constructor, facts: ClassFacts): ConstructorMetadata | undefined;
|
|
44
45
|
/**
|
|
45
|
-
* The
|
|
46
|
+
* The parameters an instantiation of a class injects, each settled into the one slot shape.
|
|
46
47
|
*
|
|
47
|
-
* @remarks
|
|
48
|
-
*
|
|
49
|
-
* declared deps the subclass silently drops.
|
|
48
|
+
* @remarks A class the reader knows nothing about is constructible only if it declares no
|
|
49
|
+
* parameters; anything else is a missing `@injectable()`. The caller stores the answer on `facts`.
|
|
50
50
|
*/
|
|
51
|
-
|
|
52
|
-
base: Constructor;
|
|
53
|
-
metadata: ConstructorMetadata;
|
|
54
|
-
} | undefined;
|
|
51
|
+
settleParams(target: Constructor, facts: ClassFacts): ReadonlyArray<ParamMetadata>;
|
|
55
52
|
/**
|
|
56
53
|
* Whether the class has a `@postConstruct` hook, or `undefined` until {@link discoverPostConstruct}.
|
|
57
54
|
*
|
|
@@ -63,6 +60,8 @@ export declare class ClassIntrospector {
|
|
|
63
60
|
needsActiveContainer(target: Constructor): boolean;
|
|
64
61
|
/** Whether a class whose facts the caller already holds reads the container during construction. */
|
|
65
62
|
needsActiveContainerOf(target: Constructor, facts: ClassFacts): boolean;
|
|
63
|
+
/** The slots of a class's `@inject` accessors, in the order their initializers run. */
|
|
64
|
+
accessorSlots(target: Constructor): ReadonlyArray<DependencySlot>;
|
|
66
65
|
instantiate(target: Constructor, deps: Array<unknown>, resolution?: AmbientResolution): unknown;
|
|
67
66
|
/** Builds an instance whose accessor need the caller already knows; an empty `deps` is a call with no arguments. */
|
|
68
67
|
construct(target: Constructor, deps: ReadonlyArray<unknown>, needsActiveContainer: boolean, resolution: AmbientResolution | undefined): unknown;
|
|
@@ -4,6 +4,10 @@
|
|
|
4
4
|
* @remarks Metadata cannot change once a class is defined, so nothing here needs version stamping.
|
|
5
5
|
*/
|
|
6
6
|
import { constructWithAmbientResolution, runWithAmbientResolution } from "#ambient-container";
|
|
7
|
+
import { MissingMetadataError } from "#errors";
|
|
8
|
+
import { settledParam } from "#injection/dependency-slot";
|
|
9
|
+
const EMPTY_PARAM_LIST = [];
|
|
10
|
+
const NO_ACCESSOR_SLOTS = [];
|
|
7
11
|
// A reader answers from the class alone, so its facts are shared by every container reading through it.
|
|
8
12
|
const factsByReader = new WeakMap();
|
|
9
13
|
function factsFor(reader) {
|
|
@@ -67,14 +71,39 @@ export class ClassIntrospector {
|
|
|
67
71
|
}
|
|
68
72
|
return metadata === null ? undefined : metadata;
|
|
69
73
|
}
|
|
74
|
+
/**
|
|
75
|
+
* The parameters an instantiation of a class injects, each settled into the one slot shape.
|
|
76
|
+
*
|
|
77
|
+
* @remarks A class the reader knows nothing about is constructible only if it declares no
|
|
78
|
+
* parameters; anything else is a missing `@injectable()`. The caller stores the answer on `facts`.
|
|
79
|
+
*/
|
|
80
|
+
settleParams(target, facts) {
|
|
81
|
+
const meta = this.constructorMetadataOf(target, facts);
|
|
82
|
+
if (meta !== undefined) {
|
|
83
|
+
return meta.params.map(settledParam);
|
|
84
|
+
}
|
|
85
|
+
if (target.length === 0) {
|
|
86
|
+
// A subclass with an implicit constructor and no own metadata inherits its base's declared
|
|
87
|
+
// deps but would be built with zero arguments, injecting `undefined` silently — reject it.
|
|
88
|
+
const inherited = this.#inheritedConstructorMetadata(target);
|
|
89
|
+
if (inherited !== undefined && inherited.metadata.params.length > 0) {
|
|
90
|
+
throw new MissingMetadataError(target.name, {
|
|
91
|
+
baseName: inherited.base.name,
|
|
92
|
+
dependencyCount: inherited.metadata.params.length,
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
return EMPTY_PARAM_LIST;
|
|
96
|
+
}
|
|
97
|
+
throw new MissingMetadataError(target.name);
|
|
98
|
+
}
|
|
70
99
|
/**
|
|
71
100
|
* The nearest ancestor's own constructor metadata, for a subclass that declares none of its own.
|
|
72
101
|
*
|
|
73
102
|
* @remarks Constructor metadata is never borrowed down the chain, so a subclass with an implicit
|
|
74
|
-
* constructor would be built with zero arguments; this
|
|
75
|
-
*
|
|
103
|
+
* constructor would be built with zero arguments; this names the base whose declared deps the
|
|
104
|
+
* subclass silently drops.
|
|
76
105
|
*/
|
|
77
|
-
inheritedConstructorMetadata(target) {
|
|
106
|
+
#inheritedConstructorMetadata(target) {
|
|
78
107
|
let current = Object.getPrototypeOf(target);
|
|
79
108
|
while (typeof current === "function" && current !== Function.prototype) {
|
|
80
109
|
const metadata = this.constructorMetadata(current);
|
|
@@ -111,6 +140,14 @@ export class ClassIntrospector {
|
|
|
111
140
|
}
|
|
112
141
|
return needsActiveContainer;
|
|
113
142
|
}
|
|
143
|
+
/** The slots of a class's `@inject` accessors, in the order their initializers run. */
|
|
144
|
+
accessorSlots(target) {
|
|
145
|
+
const entries = this.#reader.getAccessorMetadata?.(target);
|
|
146
|
+
if (entries === undefined || entries.length === 0) {
|
|
147
|
+
return NO_ACCESSOR_SLOTS;
|
|
148
|
+
}
|
|
149
|
+
return entries.map((entry) => entry.descriptor);
|
|
150
|
+
}
|
|
114
151
|
instantiate(target, deps, resolution) {
|
|
115
152
|
return this.construct(target, deps, this.needsActiveContainer(target), resolution);
|
|
116
153
|
}
|