@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
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { BindingRegistry } from "#core/registry";
|
|
2
|
+
import type { LifecycleManager } from "#lifecycle/hooks";
|
|
3
|
+
import type { MetadataReader } from "#metadata/types";
|
|
4
|
+
import type { DependencyResolver } from "#resolution/resolver";
|
|
5
|
+
/**
|
|
6
|
+
* What `validate` reads off a container.
|
|
7
|
+
*
|
|
8
|
+
* @remarks `registries` lists the container's own registry first, then each ancestor's, nearest first — the order
|
|
9
|
+
* every chain walk reads them in.
|
|
10
|
+
*
|
|
11
|
+
* @since 0.14.0
|
|
12
|
+
*/
|
|
13
|
+
export interface ValidationTarget {
|
|
14
|
+
readonly registries: readonly [BindingRegistry, ...ReadonlyArray<BindingRegistry>];
|
|
15
|
+
readonly resolver: DependencyResolver;
|
|
16
|
+
readonly metadataReader: MetadataReader;
|
|
17
|
+
readonly lifecycle: Pick<LifecycleManager, "hookedTokens">;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Runs every static check over a container's chain, throwing the first error a resolve would meet.
|
|
21
|
+
*
|
|
22
|
+
* @throws `CircularDependencyError`, `ScopeViolationError`, `TokenNotBoundError` or `NoMatchingBindingError` for a
|
|
23
|
+
* singleton graph that cannot resolve, `UnreachableLifecycleHookError` or `UnreachableConstraintError` for a hook or
|
|
24
|
+
* constraint that can never fire.
|
|
25
|
+
*
|
|
26
|
+
* @since 0.14.0
|
|
27
|
+
*/
|
|
28
|
+
export declare function validateChain(target: ValidationTarget): void;
|
|
@@ -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
|
*
|
|
@@ -20,7 +22,7 @@ export declare class LifecycleManager {
|
|
|
20
22
|
/** Whether deactivating an instance of a binding runs anything: a container hook, the binding's own, or `@preDestroy()`. */
|
|
21
23
|
owesDeactivation(binding: Binding, metadataReader: MetadataReader): boolean;
|
|
22
24
|
/** Every token carrying a container-level hook, paired with the phase that registered it. */
|
|
23
|
-
hookedTokens():
|
|
25
|
+
hookedTokens(): ReadonlyArray<HookedToken>;
|
|
24
26
|
/**
|
|
25
27
|
* Runs the activation pipeline on the async lane: the activated instance, or its promise once a
|
|
26
28
|
* hook has returned one.
|
|
@@ -31,7 +33,14 @@ export declare class LifecycleManager {
|
|
|
31
33
|
runActivation<Value>(resolutionContext: ResolutionContext, binding: Binding<Value>, instance: Value, metadataReader: MetadataReader): Value | Promise<Value>;
|
|
32
34
|
runActivationSync<Value>(resolutionContext: ResolutionContext, binding: Binding<Value>, instance: Value, metadataReader: MetadataReader): Value;
|
|
33
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
|
+
*/
|
|
34
42
|
runDeactivationSync<Value>(binding: Binding<Value>, instance: Value, metadataReader: MetadataReader): void;
|
|
35
43
|
/** Whether the deferred activation-hook table has had to be built. */
|
|
36
44
|
get isActivationTableBuilt(): boolean;
|
|
37
|
-
}
|
|
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
|
*
|
|
@@ -70,6 +71,10 @@ export class LifecycleManager {
|
|
|
70
71
|
}
|
|
71
72
|
/** Every token carrying a container-level hook, paired with the phase that registered it. */
|
|
72
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
|
+
}
|
|
73
78
|
const hooked = [];
|
|
74
79
|
for (const key of this.#activationHooks?.keys() ?? []) {
|
|
75
80
|
hooked.push([key, "onActivation"]);
|
|
@@ -88,7 +93,7 @@ export class LifecycleManager {
|
|
|
88
93
|
*/
|
|
89
94
|
runActivation(resolutionContext, binding, instance, metadataReader) {
|
|
90
95
|
let activated = instance;
|
|
91
|
-
// 1. @postConstruct() — after TC39 construction (
|
|
96
|
+
// 1. @postConstruct() — after TC39 construction (accessor initial values + constructor)
|
|
92
97
|
for (const methodName of this.#lifecycleMethods(binding, metadataReader, "postConstruct")) {
|
|
93
98
|
activated = afterActivationStep(activated, (current) => {
|
|
94
99
|
const hookResult = callHook(current, methodName);
|
|
@@ -170,36 +175,32 @@ export class LifecycleManager {
|
|
|
170
175
|
}
|
|
171
176
|
}
|
|
172
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
|
+
*/
|
|
173
184
|
runDeactivationSync(binding, instance, metadataReader) {
|
|
174
185
|
const tokenKey = binding.token;
|
|
186
|
+
let returnedPromise = false;
|
|
175
187
|
// 1. container-level onDeactivation
|
|
176
188
|
const containerHooks = this.#deactivationHooks?.get(tokenKey);
|
|
177
189
|
if (containerHooks !== undefined) {
|
|
178
190
|
for (const hook of containerHooks) {
|
|
179
|
-
|
|
180
|
-
if (hookResult instanceof Promise) {
|
|
181
|
-
// The hook has already run; adopt its rejection so a failing async hook cannot become an
|
|
182
|
-
// unhandled rejection that ends the process, then report the sync-lane violation.
|
|
183
|
-
void hookResult.catch(() => { });
|
|
184
|
-
throw new AsyncDeactivationError(tokenName(binding.token));
|
|
185
|
-
}
|
|
191
|
+
returnedPromise = adoptPromise(hook(instance)) || returnedPromise;
|
|
186
192
|
}
|
|
187
193
|
}
|
|
188
194
|
// 2. per-binding onDeactivation
|
|
189
195
|
if (binding.kind !== "alias" && binding.deactivationHook !== undefined) {
|
|
190
|
-
|
|
191
|
-
if (hookResult instanceof Promise) {
|
|
192
|
-
void hookResult.catch(() => { });
|
|
193
|
-
throw new AsyncDeactivationError(tokenName(binding.token));
|
|
194
|
-
}
|
|
196
|
+
returnedPromise = adoptPromise(binding.deactivationHook(instance)) || returnedPromise;
|
|
195
197
|
}
|
|
196
198
|
// 3. @preDestroy()
|
|
197
199
|
for (const methodName of this.#lifecycleMethods(binding, metadataReader, "preDestroy")) {
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
}
|
|
200
|
+
returnedPromise = adoptPromise(callHook(instance, methodName)) || returnedPromise;
|
|
201
|
+
}
|
|
202
|
+
if (returnedPromise) {
|
|
203
|
+
throw new AsyncDeactivationError(tokenName(binding.token));
|
|
203
204
|
}
|
|
204
205
|
}
|
|
205
206
|
/** The `@postConstruct` / `@preDestroy` methods a binding declares — only a class can declare any. */
|
|
@@ -221,6 +222,17 @@ export class LifecycleManager {
|
|
|
221
222
|
}
|
|
222
223
|
}
|
|
223
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
|
+
}
|
|
224
236
|
/** Applies one activation step now, or once the step before it has settled. */
|
|
225
237
|
function afterActivationStep(activated, step) {
|
|
226
238
|
return activated instanceof Promise ? activated.then(step) : step(activated);
|
|
@@ -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
|
}
|
|
@@ -36,6 +36,16 @@ export interface CollectionEntry {
|
|
|
36
36
|
activationVersion: number;
|
|
37
37
|
readBefore: boolean;
|
|
38
38
|
}
|
|
39
|
+
/**
|
|
40
|
+
* A collection's value list when every member answers with a fixed value, else `undefined`.
|
|
41
|
+
*
|
|
42
|
+
* @remarks A fixed value is a hook-free constant, or a hook-free singleton whose instance is cached — anything that
|
|
43
|
+
* changes either bumps a registry version the memo is keyed on. The list is kept unfrozen: a frozen array reads
|
|
44
|
+
* through a slow elements kind, and every read copies it anyway.
|
|
45
|
+
*
|
|
46
|
+
* @since 0.14.0
|
|
47
|
+
*/
|
|
48
|
+
export declare function stableCollectionValuesOf(candidates: ReadonlyArray<Binding>): Array<unknown> | undefined;
|
|
39
49
|
/**
|
|
40
50
|
* A version-stamped cache of binding lookups by token and criterion across the container chain.
|
|
41
51
|
*
|
|
@@ -1,5 +1,32 @@
|
|
|
1
|
+
import { NO_INSTANCE } from "#core/binding";
|
|
1
2
|
import { getOrInsertComputed } from "#core/map-upsert";
|
|
2
3
|
import { stateEpoch } from "#core/state-epoch";
|
|
4
|
+
/**
|
|
5
|
+
* A collection's value list when every member answers with a fixed value, else `undefined`.
|
|
6
|
+
*
|
|
7
|
+
* @remarks A fixed value is a hook-free constant, or a hook-free singleton whose instance is cached — anything that
|
|
8
|
+
* changes either bumps a registry version the memo is keyed on. The list is kept unfrozen: a frozen array reads
|
|
9
|
+
* through a slow elements kind, and every read copies it anyway.
|
|
10
|
+
*
|
|
11
|
+
* @since 0.14.0
|
|
12
|
+
*/
|
|
13
|
+
export function stableCollectionValuesOf(candidates) {
|
|
14
|
+
for (let index = 0; index < candidates.length; index += 1) {
|
|
15
|
+
if (!isStableCollectionMember(candidates[index])) {
|
|
16
|
+
return undefined;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return candidates.map(stableMemberValue);
|
|
20
|
+
}
|
|
21
|
+
function isStableCollectionMember(binding) {
|
|
22
|
+
if (binding.kind === "alias" || binding.activationHook !== undefined) {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
return binding.kind === "constant" || (binding.scope === "singleton" && binding.instance !== NO_INSTANCE);
|
|
26
|
+
}
|
|
27
|
+
function stableMemberValue(binding) {
|
|
28
|
+
return binding.kind === "constant" ? binding.value : binding.instance;
|
|
29
|
+
}
|
|
3
30
|
const newTagToEntryMap = () => new Map();
|
|
4
31
|
const newNameToTagMap = () => new Map();
|
|
5
32
|
/**
|
|
@@ -27,12 +27,12 @@ export declare class DefaultResolutionContext implements ResolutionContext {
|
|
|
27
27
|
constructor(resolver: ResolverCallbacks, resolutionStack: Array<ResolutionFrame>, currentOptions: ResolveOptions | undefined);
|
|
28
28
|
get graph(): ConstraintContext;
|
|
29
29
|
reset(resolver: ResolverCallbacks, resolutionStack: Array<ResolutionFrame>, currentOptions: ResolveOptions | undefined): void;
|
|
30
|
-
resolve<Value>(token: Token<Value> | Constructor<Value>, options?: ResolveOptions): Value;
|
|
31
|
-
resolveAsync<Value>(token: Token<Value> | Constructor<Value>, options?: ResolveOptions): Promise<Value>;
|
|
32
|
-
resolveOptional<Value>(token: Token<Value> | Constructor<Value>, options?: ResolveOptions): Value | undefined;
|
|
33
|
-
resolveOptionalAsync<Value>(token: Token<Value> | Constructor<Value>, options?: ResolveOptions): Promise<Value | undefined>;
|
|
34
|
-
resolveAll<Value>(token: Token<Value> | Constructor<Value>, options?: ResolveOptions): ReadonlyArray<Value>;
|
|
35
|
-
resolveAllAsync<Value>(token: Token<Value> | Constructor<Value>, options?: ResolveOptions): Promise<ReadonlyArray<Value>>;
|
|
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
36
|
}
|
|
37
37
|
/**
|
|
38
38
|
* One async level's resolution context, which is also its branch of the resolution stack.
|
|
@@ -55,12 +55,12 @@ export declare class AsyncLevelContext implements ResolutionContext {
|
|
|
55
55
|
get graph(): ConstraintContext;
|
|
56
56
|
/** This level's own path, fixed for its lifetime, for a caller that names it in an error. */
|
|
57
57
|
get ownPath(): ReadonlyArray<ResolutionFrame>;
|
|
58
|
-
resolve<Value>(token: Token<Value> | Constructor<Value>, options?: ResolveOptions): Value;
|
|
59
|
-
resolveAsync<Value>(token: Token<Value> | Constructor<Value>, options?: ResolveOptions): Promise<Value>;
|
|
60
|
-
resolveOptional<Value>(token: Token<Value> | Constructor<Value>, options?: ResolveOptions): Value | undefined;
|
|
61
|
-
resolveOptionalAsync<Value>(token: Token<Value> | Constructor<Value>, options?: ResolveOptions): Promise<Value | undefined>;
|
|
62
|
-
resolveAll<Value>(token: Token<Value> | Constructor<Value>, options?: ResolveOptions): ReadonlyArray<Value>;
|
|
63
|
-
resolveAllAsync<Value>(token: Token<Value> | Constructor<Value>, options?: ResolveOptions): Promise<ReadonlyArray<Value>>;
|
|
58
|
+
resolve<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<ResolveOptions<Names>>): Value;
|
|
59
|
+
resolveAsync<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<ResolveOptions<Names>>): Promise<Value>;
|
|
60
|
+
resolveOptional<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<ResolveOptions<Names>>): Value | undefined;
|
|
61
|
+
resolveOptionalAsync<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<ResolveOptions<Names>>): Promise<Value | undefined>;
|
|
62
|
+
resolveAll<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<ResolveOptions<Names>>): ReadonlyArray<Value>;
|
|
63
|
+
resolveAllAsync<Value, Names extends string = string>(token: Token<Value, Names> | Constructor<Value>, options?: NoInfer<ResolveOptions<Names>>): Promise<ReadonlyArray<Value>>;
|
|
64
64
|
}
|
|
65
65
|
/**
|
|
66
66
|
* The one constraint context every predicate reads, whatever lane built it.
|
|
@@ -26,8 +26,9 @@ export type PlanNode = {
|
|
|
26
26
|
readonly deps: ReadonlyArray<PlanNode>;
|
|
27
27
|
} | {
|
|
28
28
|
readonly kind: "accessors";
|
|
29
|
-
readonly construct: (deps: Array<unknown>) => unknown;
|
|
29
|
+
readonly construct: (deps: Array<unknown>, accessorValues: Array<unknown>) => unknown;
|
|
30
30
|
readonly deps: ReadonlyArray<PlanNode>;
|
|
31
|
+
readonly accessors: ReadonlyArray<PlanNode>;
|
|
31
32
|
} | {
|
|
32
33
|
readonly kind: "call";
|
|
33
34
|
readonly factory: (...args: Array<unknown>) => unknown;
|
|
@@ -106,7 +106,7 @@ class PlanEmitter {
|
|
|
106
106
|
case "construct":
|
|
107
107
|
return this.#define(`new ${this.#slot(node.target, "C")}(${this.#list(node.deps)})`);
|
|
108
108
|
case "accessors":
|
|
109
|
-
return this.#define(`${this.#slot(node.construct, "A")}([${this.#list(node.deps)}])`);
|
|
109
|
+
return this.#define(`${this.#slot(node.construct, "A")}([${this.#list(node.deps)}], [${this.#list(node.accessors)}])`);
|
|
110
110
|
case "call": {
|
|
111
111
|
// The settle only ever throws, so it runs on the promise branch alone and the plain result stands.
|
|
112
112
|
const local = this.#define(`${this.#slot(node.factory, "F")}(${this.#list(node.deps)})`);
|