@theokit/di 0.1.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 +46 -0
- package/LICENSE +201 -0
- package/README.md +65 -0
- package/dist/index.cjs +1000 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +506 -0
- package/dist/index.d.ts +506 -0
- package/dist/index.js +981 -0
- package/dist/index.js.map +1 -0
- package/package.json +70 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1000 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var async_hooks = require('async_hooks');
|
|
4
|
+
|
|
5
|
+
var __defProp = Object.defineProperty;
|
|
6
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
7
|
+
|
|
8
|
+
// src/errors.ts
|
|
9
|
+
function describeToken(token) {
|
|
10
|
+
if (typeof token === "string") {
|
|
11
|
+
return JSON.stringify(token);
|
|
12
|
+
}
|
|
13
|
+
if (typeof token === "function" && typeof token.name === "string" && token.name.length > 0) {
|
|
14
|
+
return token.name;
|
|
15
|
+
}
|
|
16
|
+
return "<unknown token>";
|
|
17
|
+
}
|
|
18
|
+
__name(describeToken, "describeToken");
|
|
19
|
+
var TokenNotFoundError = class extends Error {
|
|
20
|
+
static {
|
|
21
|
+
__name(this, "TokenNotFoundError");
|
|
22
|
+
}
|
|
23
|
+
token;
|
|
24
|
+
resolutionPath;
|
|
25
|
+
name = "TokenNotFoundError";
|
|
26
|
+
constructor(token, resolutionPath) {
|
|
27
|
+
const pathStr = resolutionPath.length === 0 ? "(top-level)" : resolutionPath.map(describeToken).join(" \u2192 ");
|
|
28
|
+
super(`No provider registered for token: ${describeToken(token)}
|
|
29
|
+
Resolution path: ${pathStr}`), this.token = token, this.resolutionPath = resolutionPath;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
var CyclicDependencyError = class extends Error {
|
|
33
|
+
static {
|
|
34
|
+
__name(this, "CyclicDependencyError");
|
|
35
|
+
}
|
|
36
|
+
cycle;
|
|
37
|
+
name = "CyclicDependencyError";
|
|
38
|
+
constructor(cycle) {
|
|
39
|
+
super(`Cyclic dependency detected: ${cycle.map(describeToken).join(" \u2192 ")}`), this.cycle = cycle;
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
var AsyncProviderInSyncResolveError = class extends Error {
|
|
43
|
+
static {
|
|
44
|
+
__name(this, "AsyncProviderInSyncResolveError");
|
|
45
|
+
}
|
|
46
|
+
token;
|
|
47
|
+
name = "AsyncProviderInSyncResolveError";
|
|
48
|
+
constructor(token) {
|
|
49
|
+
super(`Provider for token ${describeToken(token)} is async (factory returned a Promise). Use container.resolveAsync() instead of container.resolve().`), this.token = token;
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
var ScopeViolationError = class extends Error {
|
|
53
|
+
static {
|
|
54
|
+
__name(this, "ScopeViolationError");
|
|
55
|
+
}
|
|
56
|
+
token;
|
|
57
|
+
name = "ScopeViolationError";
|
|
58
|
+
constructor(token, message) {
|
|
59
|
+
super(`Scope violation for token ${describeToken(token)}: ${message}`), this.token = token;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
var MissingInjectableError = class extends Error {
|
|
63
|
+
static {
|
|
64
|
+
__name(this, "MissingInjectableError");
|
|
65
|
+
}
|
|
66
|
+
target;
|
|
67
|
+
name = "MissingInjectableError";
|
|
68
|
+
constructor(target) {
|
|
69
|
+
super(`Class ${target.name ?? "<anonymous>"} has no @Injectable() decorator. Add @Injectable() above the class declaration before registering it.`), this.target = target;
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
var ContainerDisposedError = class extends Error {
|
|
73
|
+
static {
|
|
74
|
+
__name(this, "ContainerDisposedError");
|
|
75
|
+
}
|
|
76
|
+
name = "ContainerDisposedError";
|
|
77
|
+
constructor() {
|
|
78
|
+
super("Container has been disposed; subsequent resolves are not allowed.");
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
var ContainerFrozenError = class extends Error {
|
|
82
|
+
static {
|
|
83
|
+
__name(this, "ContainerFrozenError");
|
|
84
|
+
}
|
|
85
|
+
token;
|
|
86
|
+
name = "ContainerFrozenError";
|
|
87
|
+
constructor(token) {
|
|
88
|
+
super(`Container is frozen \u2014 cannot register ${describeToken(token)} after first resolve(). Pass { allowDynamicRegistration: true } to the Container constructor to opt out (recommended for tests only).`), this.token = token;
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
var ReflectMetadataMissingError = class extends Error {
|
|
92
|
+
static {
|
|
93
|
+
__name(this, "ReflectMetadataMissingError");
|
|
94
|
+
}
|
|
95
|
+
name = "ReflectMetadataMissingError";
|
|
96
|
+
constructor() {
|
|
97
|
+
super('reflect-metadata is not loaded. Import \'reflect-metadata\' ONCE at your application entry point (e.g., the top of `src/main.ts`) and ensure your tsconfig has `"experimentalDecorators": true` and `"emitDecoratorMetadata": true`.');
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
// src/internal/graph.ts
|
|
102
|
+
function findCycles(snapshot) {
|
|
103
|
+
const adjacency = /* @__PURE__ */ new Map();
|
|
104
|
+
for (const edge of snapshot.edges) {
|
|
105
|
+
const list = adjacency.get(edge.from) ?? [];
|
|
106
|
+
list.push(edge.to);
|
|
107
|
+
adjacency.set(edge.from, list);
|
|
108
|
+
}
|
|
109
|
+
const cycles = [];
|
|
110
|
+
const seenCycles = /* @__PURE__ */ new Set();
|
|
111
|
+
const visited = /* @__PURE__ */ new Set();
|
|
112
|
+
for (const node of snapshot.nodes) {
|
|
113
|
+
if (visited.has(node.token)) continue;
|
|
114
|
+
iterativeDfs(node.token, adjacency, visited, cycles, seenCycles);
|
|
115
|
+
}
|
|
116
|
+
return cycles;
|
|
117
|
+
}
|
|
118
|
+
__name(findCycles, "findCycles");
|
|
119
|
+
function iterativeDfs(root, adjacency, visited, out, seenCycles) {
|
|
120
|
+
const stack = [];
|
|
121
|
+
const onPath = /* @__PURE__ */ new Set();
|
|
122
|
+
const pathOrder = [];
|
|
123
|
+
function push(node) {
|
|
124
|
+
if (visited.has(node)) return;
|
|
125
|
+
visited.add(node);
|
|
126
|
+
onPath.add(node);
|
|
127
|
+
pathOrder.push(node);
|
|
128
|
+
stack.push({
|
|
129
|
+
node,
|
|
130
|
+
neighbors: adjacency.get(node) ?? [],
|
|
131
|
+
next: 0
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
__name(push, "push");
|
|
135
|
+
push(root);
|
|
136
|
+
while (stack.length > 0) {
|
|
137
|
+
const frame = stack[stack.length - 1];
|
|
138
|
+
if (frame.next >= frame.neighbors.length) {
|
|
139
|
+
onPath.delete(frame.node);
|
|
140
|
+
pathOrder.pop();
|
|
141
|
+
stack.pop();
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
const neighbor = frame.neighbors[frame.next];
|
|
145
|
+
frame.next += 1;
|
|
146
|
+
if (onPath.has(neighbor)) {
|
|
147
|
+
const cycleStart = pathOrder.indexOf(neighbor);
|
|
148
|
+
const cycle = [
|
|
149
|
+
...pathOrder.slice(cycleStart),
|
|
150
|
+
neighbor
|
|
151
|
+
];
|
|
152
|
+
const key = canonicalCycleKey(cycle);
|
|
153
|
+
if (!seenCycles.has(key)) {
|
|
154
|
+
seenCycles.add(key);
|
|
155
|
+
out.push(cycle);
|
|
156
|
+
}
|
|
157
|
+
} else if (!visited.has(neighbor)) {
|
|
158
|
+
push(neighbor);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
__name(iterativeDfs, "iterativeDfs");
|
|
163
|
+
function canonicalCycleKey(cycle) {
|
|
164
|
+
const strs = cycle.map(stringifyToken);
|
|
165
|
+
let minIndex = 0;
|
|
166
|
+
for (let i = 1; i < strs.length; i += 1) {
|
|
167
|
+
if (strs[i] < strs[minIndex]) {
|
|
168
|
+
minIndex = i;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return [
|
|
172
|
+
...strs.slice(minIndex),
|
|
173
|
+
...strs.slice(0, minIndex)
|
|
174
|
+
].join("\u2192");
|
|
175
|
+
}
|
|
176
|
+
__name(canonicalCycleKey, "canonicalCycleKey");
|
|
177
|
+
function stringifyToken(token) {
|
|
178
|
+
if (typeof token === "string") return `s:${token}`;
|
|
179
|
+
if (typeof token === "function") return `c:${token.name ?? "<anon>"}`;
|
|
180
|
+
return "u:<unknown>";
|
|
181
|
+
}
|
|
182
|
+
__name(stringifyToken, "stringifyToken");
|
|
183
|
+
|
|
184
|
+
// src/internal/metadata.ts
|
|
185
|
+
var METADATA_KEYS = {
|
|
186
|
+
/** Marker that a class was decorated with `@Injectable()`. */
|
|
187
|
+
INJECTABLE: "usetheo:di:injectable",
|
|
188
|
+
/** Map<number, Token> from `@Inject(token)` parameter decorators. */
|
|
189
|
+
INJECT_TOKENS: "usetheo:di:inject-tokens",
|
|
190
|
+
/** Set<number> from `@Optional()` parameter decorators. */
|
|
191
|
+
OPTIONAL_FLAGS: "usetheo:di:optional",
|
|
192
|
+
/** TS-emitted constructor parameter types (requires `emitDecoratorMetadata`). */
|
|
193
|
+
DESIGN_PARAMTYPES: "design:paramtypes"
|
|
194
|
+
};
|
|
195
|
+
function hasReflectMetadata() {
|
|
196
|
+
return typeof Reflect !== "undefined" && typeof Reflect.getMetadata === "function";
|
|
197
|
+
}
|
|
198
|
+
__name(hasReflectMetadata, "hasReflectMetadata");
|
|
199
|
+
function readParamTypes(target) {
|
|
200
|
+
if (!hasReflectMetadata()) return [];
|
|
201
|
+
const out = Reflect.getMetadata(METADATA_KEYS.DESIGN_PARAMTYPES, target);
|
|
202
|
+
if (!Array.isArray(out)) return [];
|
|
203
|
+
return out;
|
|
204
|
+
}
|
|
205
|
+
__name(readParamTypes, "readParamTypes");
|
|
206
|
+
function readInjectTokens(target) {
|
|
207
|
+
if (!hasReflectMetadata()) return /* @__PURE__ */ new Map();
|
|
208
|
+
const out = Reflect.getMetadata(METADATA_KEYS.INJECT_TOKENS, target);
|
|
209
|
+
if (!(out instanceof Map)) return /* @__PURE__ */ new Map();
|
|
210
|
+
return out;
|
|
211
|
+
}
|
|
212
|
+
__name(readInjectTokens, "readInjectTokens");
|
|
213
|
+
function readOptionalFlags(target) {
|
|
214
|
+
if (!hasReflectMetadata()) return /* @__PURE__ */ new Set();
|
|
215
|
+
const out = Reflect.getMetadata(METADATA_KEYS.OPTIONAL_FLAGS, target);
|
|
216
|
+
if (!(out instanceof Set)) return /* @__PURE__ */ new Set();
|
|
217
|
+
return out;
|
|
218
|
+
}
|
|
219
|
+
__name(readOptionalFlags, "readOptionalFlags");
|
|
220
|
+
function readInjectableMetadata(target) {
|
|
221
|
+
if (!hasReflectMetadata()) return void 0;
|
|
222
|
+
const out = Reflect.getMetadata(METADATA_KEYS.INJECTABLE, target);
|
|
223
|
+
if (out === void 0 || out === null) return void 0;
|
|
224
|
+
if (typeof out !== "object") return void 0;
|
|
225
|
+
return out;
|
|
226
|
+
}
|
|
227
|
+
__name(readInjectableMetadata, "readInjectableMetadata");
|
|
228
|
+
function isInjectable(target) {
|
|
229
|
+
return readInjectableMetadata(target) !== void 0;
|
|
230
|
+
}
|
|
231
|
+
__name(isInjectable, "isInjectable");
|
|
232
|
+
var PRIMITIVE_WRAPPERS = /* @__PURE__ */ new Set([
|
|
233
|
+
Number,
|
|
234
|
+
String,
|
|
235
|
+
Boolean,
|
|
236
|
+
Object,
|
|
237
|
+
Array,
|
|
238
|
+
Function
|
|
239
|
+
]);
|
|
240
|
+
function isPrimitiveTypeMarker(value) {
|
|
241
|
+
return typeof value === "function" && PRIMITIVE_WRAPPERS.has(value);
|
|
242
|
+
}
|
|
243
|
+
__name(isPrimitiveTypeMarker, "isPrimitiveTypeMarker");
|
|
244
|
+
|
|
245
|
+
// src/decorators/module.ts
|
|
246
|
+
var MODULE_METADATA_KEY = "usetheo:di:module";
|
|
247
|
+
function Module(metadata) {
|
|
248
|
+
return (target) => {
|
|
249
|
+
Reflect.defineMetadata(MODULE_METADATA_KEY, metadata, target);
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
__name(Module, "Module");
|
|
253
|
+
function readModuleMetadata(target) {
|
|
254
|
+
if (typeof Reflect === "undefined" || typeof Reflect.getMetadata !== "function") {
|
|
255
|
+
return void 0;
|
|
256
|
+
}
|
|
257
|
+
const out = Reflect.getMetadata(MODULE_METADATA_KEY, target);
|
|
258
|
+
if (out === void 0 || out === null) return void 0;
|
|
259
|
+
if (typeof out !== "object") return void 0;
|
|
260
|
+
return out;
|
|
261
|
+
}
|
|
262
|
+
__name(readModuleMetadata, "readModuleMetadata");
|
|
263
|
+
|
|
264
|
+
// src/internal/module-loader.ts
|
|
265
|
+
var InvalidModuleError = class extends Error {
|
|
266
|
+
static {
|
|
267
|
+
__name(this, "InvalidModuleError");
|
|
268
|
+
}
|
|
269
|
+
target;
|
|
270
|
+
name = "InvalidModuleError";
|
|
271
|
+
constructor(target) {
|
|
272
|
+
super(`Class ${target.name ?? "<anonymous>"} has no @Module() decorator. Add @Module({ providers: [...], imports: [...], exports: [...] }) above the class declaration.`), this.target = target;
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
var InvalidExportError = class extends Error {
|
|
276
|
+
static {
|
|
277
|
+
__name(this, "InvalidExportError");
|
|
278
|
+
}
|
|
279
|
+
moduleName;
|
|
280
|
+
token;
|
|
281
|
+
name = "InvalidExportError";
|
|
282
|
+
constructor(moduleName, token) {
|
|
283
|
+
super(`Module ${moduleName} exports token ${describeToken(token)} but it is not in providers[]. Add it to providers[] or remove it from exports[].`), this.moduleName = moduleName, this.token = token;
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
var CyclicModuleImportError = class extends Error {
|
|
287
|
+
static {
|
|
288
|
+
__name(this, "CyclicModuleImportError");
|
|
289
|
+
}
|
|
290
|
+
cycle;
|
|
291
|
+
name = "CyclicModuleImportError";
|
|
292
|
+
constructor(cycle) {
|
|
293
|
+
super(`Cyclic module imports detected: ${cycle.join(" \u2192 ")}`), this.cycle = cycle;
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
function loadModule(rootModule, container) {
|
|
297
|
+
const visited = /* @__PURE__ */ new Set();
|
|
298
|
+
const loaded = [];
|
|
299
|
+
function visit(target, path) {
|
|
300
|
+
if (path.includes(target)) {
|
|
301
|
+
const cycleStart = path.indexOf(target);
|
|
302
|
+
const cycleNames = [
|
|
303
|
+
...path.slice(cycleStart).map((m) => m.name),
|
|
304
|
+
target.name
|
|
305
|
+
];
|
|
306
|
+
throw new CyclicModuleImportError(cycleNames);
|
|
307
|
+
}
|
|
308
|
+
if (visited.has(target)) return;
|
|
309
|
+
const metadata = readModuleMetadata(target);
|
|
310
|
+
if (metadata === void 0) {
|
|
311
|
+
throw new InvalidModuleError(target);
|
|
312
|
+
}
|
|
313
|
+
visited.add(target);
|
|
314
|
+
const childPath = [
|
|
315
|
+
...path,
|
|
316
|
+
target
|
|
317
|
+
];
|
|
318
|
+
for (const imported of metadata.imports ?? []) {
|
|
319
|
+
visit(imported, childPath);
|
|
320
|
+
}
|
|
321
|
+
loaded.push({
|
|
322
|
+
target,
|
|
323
|
+
metadata
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
__name(visit, "visit");
|
|
327
|
+
visit(rootModule, []);
|
|
328
|
+
for (const { target, metadata } of loaded) {
|
|
329
|
+
for (const provider of metadata.providers ?? []) {
|
|
330
|
+
container.register(provider);
|
|
331
|
+
}
|
|
332
|
+
validateExports(target.name, metadata);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
__name(loadModule, "loadModule");
|
|
336
|
+
function validateExports(moduleName, metadata) {
|
|
337
|
+
if (metadata.exports === void 0) return;
|
|
338
|
+
const providerTokens = /* @__PURE__ */ new Set();
|
|
339
|
+
for (const provider of metadata.providers ?? []) {
|
|
340
|
+
if (typeof provider === "function") {
|
|
341
|
+
providerTokens.add(provider);
|
|
342
|
+
} else {
|
|
343
|
+
providerTokens.add(provider.provide);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
for (const exported of metadata.exports) {
|
|
347
|
+
if (!providerTokens.has(exported)) {
|
|
348
|
+
throw new InvalidExportError(moduleName, exported);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
__name(validateExports, "validateExports");
|
|
353
|
+
|
|
354
|
+
// src/types.ts
|
|
355
|
+
var Scope = {
|
|
356
|
+
SINGLETON: "singleton",
|
|
357
|
+
TRANSIENT: "transient",
|
|
358
|
+
REQUEST: "request"
|
|
359
|
+
};
|
|
360
|
+
|
|
361
|
+
// src/container.ts
|
|
362
|
+
var Container = class {
|
|
363
|
+
static {
|
|
364
|
+
__name(this, "Container");
|
|
365
|
+
}
|
|
366
|
+
registrations = /* @__PURE__ */ new Map();
|
|
367
|
+
singletonCache = /* @__PURE__ */ new Map();
|
|
368
|
+
singletonInstances = [];
|
|
369
|
+
requestStorage = new async_hooks.AsyncLocalStorage();
|
|
370
|
+
options;
|
|
371
|
+
hasResolved = false;
|
|
372
|
+
disposed = false;
|
|
373
|
+
constructor(options = {}) {
|
|
374
|
+
this.options = {
|
|
375
|
+
providers: options.providers ?? [],
|
|
376
|
+
allowDynamicRegistration: options.allowDynamicRegistration ?? false
|
|
377
|
+
};
|
|
378
|
+
for (const provider of this.options.providers) {
|
|
379
|
+
this.register(provider);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* Register a provider. Accepts:
|
|
384
|
+
* - A full Provider (useClass / useFactory / useValue / useExisting)
|
|
385
|
+
* - A bare class (shorthand expands to ClassProvider { provide: X, useClass: X })
|
|
386
|
+
*
|
|
387
|
+
* Per v1.1 EC-1, ClassProvider validation runs via `validateClassProvider()`
|
|
388
|
+
* regardless of which API path was used.
|
|
389
|
+
*/
|
|
390
|
+
register(providerOrClass) {
|
|
391
|
+
this.assertNotDisposed();
|
|
392
|
+
this.assertNotFrozen(this.tokenOf(providerOrClass));
|
|
393
|
+
const provider = this.normalizeShorthand(providerOrClass);
|
|
394
|
+
this.validateProvider(provider);
|
|
395
|
+
const registration = this.normalizeProvider(provider);
|
|
396
|
+
if (this.registrations.has(registration.token)) {
|
|
397
|
+
process.stderr.write(`[@theokit/di] Warning: provider for token ${describeToken(registration.token)} replaced.
|
|
398
|
+
`);
|
|
399
|
+
}
|
|
400
|
+
this.registrations.set(registration.token, registration);
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Load a `@Module()`-decorated class plus all transitively imported
|
|
404
|
+
* modules. Walks imports BFS, registers every provider, validates
|
|
405
|
+
* exports.
|
|
406
|
+
*
|
|
407
|
+
* Per v1.1 EC-4: undecorated class throws `InvalidModuleError`.
|
|
408
|
+
* Per v1.2 EC-R2-5: respects the freeze-after-first-resolve guarantee
|
|
409
|
+
* (each child `register()` checks `assertNotFrozen`).
|
|
410
|
+
*/
|
|
411
|
+
registerModule(moduleClass) {
|
|
412
|
+
this.assertNotDisposed();
|
|
413
|
+
loadModule(moduleClass, this);
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* True if the container has a registration for `token`.
|
|
417
|
+
*/
|
|
418
|
+
has(token) {
|
|
419
|
+
return this.registrations.has(token);
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Synchronously resolve a token. Throws `AsyncProviderInSyncResolveError`
|
|
423
|
+
* if the resolution chain contains an async provider.
|
|
424
|
+
*/
|
|
425
|
+
resolve(token) {
|
|
426
|
+
this.assertNotDisposed();
|
|
427
|
+
this.hasResolved = true;
|
|
428
|
+
const ctx = this.createContext([]);
|
|
429
|
+
return this.resolveInContext(token, ctx);
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* Asynchronously resolve a token. Always returns a Promise even for sync
|
|
433
|
+
* providers (for API uniformity).
|
|
434
|
+
*/
|
|
435
|
+
async resolveAsync(token) {
|
|
436
|
+
this.assertNotDisposed();
|
|
437
|
+
this.hasResolved = true;
|
|
438
|
+
const ctx = this.createContextAsync([]);
|
|
439
|
+
return await this.resolveAsyncInContext(token, ctx);
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* Run `callback` inside a fresh REQUEST scope. All REQUEST-scoped
|
|
443
|
+
* providers resolved within `callback` (or any async continuation) share
|
|
444
|
+
* a single per-request cache.
|
|
445
|
+
*
|
|
446
|
+
* v1.1 EC-3: try/finally guarantees REQUEST-scoped instances are disposed
|
|
447
|
+
* even if the callback throws.
|
|
448
|
+
*/
|
|
449
|
+
async runInRequest(callback) {
|
|
450
|
+
this.assertNotDisposed();
|
|
451
|
+
const store = {
|
|
452
|
+
cache: /* @__PURE__ */ new Map(),
|
|
453
|
+
instances: []
|
|
454
|
+
};
|
|
455
|
+
try {
|
|
456
|
+
return await this.requestStorage.run(store, async () => callback());
|
|
457
|
+
} finally {
|
|
458
|
+
await this.disposeInstances(store.instances);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
/**
|
|
462
|
+
* Debug helper — returns a snapshot of the dependency graph.
|
|
463
|
+
*
|
|
464
|
+
* Per ADR D7: detects cycles in unused providers too (resolve-time
|
|
465
|
+
* detection only fires for resolves that actually traverse the cycle).
|
|
466
|
+
* Use this proactively in tests / dev mode to surface latent cycles.
|
|
467
|
+
*/
|
|
468
|
+
analyze() {
|
|
469
|
+
const nodes = [];
|
|
470
|
+
const edges = [];
|
|
471
|
+
for (const [token, registration] of this.registrations.entries()) {
|
|
472
|
+
nodes.push({
|
|
473
|
+
token,
|
|
474
|
+
scope: registration.scope,
|
|
475
|
+
isAsync: false
|
|
476
|
+
});
|
|
477
|
+
const deps = this.getDirectDependencies(token);
|
|
478
|
+
for (const dep of deps) {
|
|
479
|
+
edges.push({
|
|
480
|
+
from: token,
|
|
481
|
+
to: dep
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
const cycles = findCycles({
|
|
486
|
+
nodes,
|
|
487
|
+
edges
|
|
488
|
+
});
|
|
489
|
+
return {
|
|
490
|
+
nodes,
|
|
491
|
+
edges,
|
|
492
|
+
cycles
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
getDirectDependencies(token) {
|
|
496
|
+
const registration = this.registrations.get(token);
|
|
497
|
+
if (registration === void 0) return [];
|
|
498
|
+
if (registration.injectTokens !== void 0) {
|
|
499
|
+
return registration.injectTokens;
|
|
500
|
+
}
|
|
501
|
+
if (registration.aliasTarget !== void 0) {
|
|
502
|
+
return [
|
|
503
|
+
registration.aliasTarget
|
|
504
|
+
];
|
|
505
|
+
}
|
|
506
|
+
const classTarget = registration.classTarget;
|
|
507
|
+
if (classTarget !== void 0) {
|
|
508
|
+
const out = [];
|
|
509
|
+
const paramTypes = readParamTypes(classTarget);
|
|
510
|
+
const injectTokens = readInjectTokens(classTarget);
|
|
511
|
+
paramTypes.forEach((paramType, i) => {
|
|
512
|
+
const explicit = injectTokens.get(i);
|
|
513
|
+
if (explicit !== void 0) {
|
|
514
|
+
out.push(explicit);
|
|
515
|
+
} else if (!isPrimitiveTypeMarker(paramType)) {
|
|
516
|
+
out.push(paramType);
|
|
517
|
+
}
|
|
518
|
+
});
|
|
519
|
+
return out;
|
|
520
|
+
}
|
|
521
|
+
return [];
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* Dispose the container — runs `dispose()` (or `Symbol.asyncDispose`) on
|
|
525
|
+
* every singleton instance in reverse construction order. Idempotent.
|
|
526
|
+
* Subsequent `resolve()` throws `ContainerDisposedError`.
|
|
527
|
+
*/
|
|
528
|
+
async dispose() {
|
|
529
|
+
if (this.disposed) return;
|
|
530
|
+
this.disposed = true;
|
|
531
|
+
await this.disposeInstances(this.singletonInstances);
|
|
532
|
+
this.singletonCache.clear();
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* Symbol.asyncDispose alias — enables `await using container = new Container(...)`.
|
|
536
|
+
*/
|
|
537
|
+
[Symbol.asyncDispose]() {
|
|
538
|
+
return this.dispose();
|
|
539
|
+
}
|
|
540
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
541
|
+
// Internal: validation
|
|
542
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
543
|
+
normalizeShorthand(providerOrClass) {
|
|
544
|
+
if (typeof providerOrClass === "function") {
|
|
545
|
+
return {
|
|
546
|
+
provide: providerOrClass,
|
|
547
|
+
useClass: providerOrClass
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
return providerOrClass;
|
|
551
|
+
}
|
|
552
|
+
tokenOf(providerOrClass) {
|
|
553
|
+
if (typeof providerOrClass === "function") return providerOrClass;
|
|
554
|
+
return providerOrClass.provide;
|
|
555
|
+
}
|
|
556
|
+
validateProvider(provider) {
|
|
557
|
+
if (provider.provide === void 0 || provider.provide === null) {
|
|
558
|
+
throw new TypeError("Provider.provide must be a class or non-empty string token, got: " + String(provider.provide));
|
|
559
|
+
}
|
|
560
|
+
if ("useClass" in provider) {
|
|
561
|
+
this.validateClassProvider(provider);
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
/**
|
|
565
|
+
* v1.1 EC-1: shared by both declarative providers: [] AND imperative
|
|
566
|
+
* register() — every class provider must have @Injectable().
|
|
567
|
+
*/
|
|
568
|
+
validateClassProvider(provider) {
|
|
569
|
+
if (typeof provider.useClass !== "function") {
|
|
570
|
+
throw new TypeError(`ClassProvider.useClass must be a class constructor, got ${typeof provider.useClass}.`);
|
|
571
|
+
}
|
|
572
|
+
if (!isInjectable(provider.useClass)) {
|
|
573
|
+
throw new MissingInjectableError(provider.useClass);
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
assertNotDisposed() {
|
|
577
|
+
if (this.disposed) throw new ContainerDisposedError();
|
|
578
|
+
}
|
|
579
|
+
/**
|
|
580
|
+
* v1.2 EC-R2-5: container freezes on first resolve. Late registrations
|
|
581
|
+
* require explicit `allowDynamicRegistration: true` (testing escape hatch).
|
|
582
|
+
*/
|
|
583
|
+
assertNotFrozen(token) {
|
|
584
|
+
if (this.hasResolved && !this.options.allowDynamicRegistration) {
|
|
585
|
+
throw new ContainerFrozenError(token);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
589
|
+
// Internal: provider normalization to Registration
|
|
590
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
591
|
+
normalizeProvider(provider) {
|
|
592
|
+
if ("useClass" in provider) {
|
|
593
|
+
return this.fromClassProvider(provider);
|
|
594
|
+
}
|
|
595
|
+
if ("useFactory" in provider) {
|
|
596
|
+
return this.fromFactoryProvider(provider);
|
|
597
|
+
}
|
|
598
|
+
if ("useValue" in provider) {
|
|
599
|
+
return this.fromValueProvider(provider);
|
|
600
|
+
}
|
|
601
|
+
return this.fromExistingProvider(provider);
|
|
602
|
+
}
|
|
603
|
+
fromClassProvider(provider) {
|
|
604
|
+
const target = provider.useClass;
|
|
605
|
+
const scopeFromDecorator = readInjectableMetadata(target)?.scope;
|
|
606
|
+
const scope = provider.scope ?? scopeFromDecorator ?? Scope.SINGLETON;
|
|
607
|
+
return {
|
|
608
|
+
token: provider.provide,
|
|
609
|
+
scope,
|
|
610
|
+
factory: /* @__PURE__ */ __name((ctx) => this.constructClassWithAsyncFallback(target, ctx), "factory"),
|
|
611
|
+
classTarget: target
|
|
612
|
+
};
|
|
613
|
+
}
|
|
614
|
+
fromFactoryProvider(provider) {
|
|
615
|
+
const injectTokens = provider.inject ?? [];
|
|
616
|
+
return {
|
|
617
|
+
token: provider.provide,
|
|
618
|
+
scope: provider.scope ?? Scope.SINGLETON,
|
|
619
|
+
factory: /* @__PURE__ */ __name((ctx) => {
|
|
620
|
+
const result = this.tryResolveSyncDeps(injectTokens, ctx);
|
|
621
|
+
if ("args" in result) {
|
|
622
|
+
return provider.useFactory(...result.args);
|
|
623
|
+
}
|
|
624
|
+
return Promise.all(injectTokens.map((dep) => ctx.resolveAsync(dep))).then((asyncArgs) => provider.useFactory(...asyncArgs));
|
|
625
|
+
}, "factory"),
|
|
626
|
+
injectTokens
|
|
627
|
+
};
|
|
628
|
+
}
|
|
629
|
+
/**
|
|
630
|
+
* Attempt sync resolution of a flat dep list (factory provider shape).
|
|
631
|
+
* Returns `{ args }` on success or `{ needsAsync: true }` if any dep
|
|
632
|
+
* raised AsyncProviderInSyncResolveError. Throws for any other error.
|
|
633
|
+
* Extracted via D422 to keep fromFactoryProvider.factory below complexity 10.
|
|
634
|
+
*/
|
|
635
|
+
tryResolveSyncDeps(injectTokens, ctx) {
|
|
636
|
+
const args = [];
|
|
637
|
+
for (const dep of injectTokens) {
|
|
638
|
+
try {
|
|
639
|
+
args.push(ctx.resolve(dep));
|
|
640
|
+
} catch (err) {
|
|
641
|
+
if (err instanceof AsyncProviderInSyncResolveError) {
|
|
642
|
+
return {
|
|
643
|
+
needsAsync: true
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
throw err;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
return {
|
|
650
|
+
args
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
fromValueProvider(provider) {
|
|
654
|
+
return {
|
|
655
|
+
token: provider.provide,
|
|
656
|
+
scope: Scope.SINGLETON,
|
|
657
|
+
factory: /* @__PURE__ */ __name(() => provider.useValue, "factory")
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
fromExistingProvider(provider) {
|
|
661
|
+
return {
|
|
662
|
+
token: provider.provide,
|
|
663
|
+
scope: Scope.SINGLETON,
|
|
664
|
+
factory: /* @__PURE__ */ __name((ctx) => ctx.resolve(provider.useExisting), "factory"),
|
|
665
|
+
aliasTarget: provider.useExisting
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
/**
|
|
669
|
+
* Resolve constructor params + build instance. Tries sync first; if any
|
|
670
|
+
* dep is async, falls back to awaiting via `resolveAsync`.
|
|
671
|
+
*
|
|
672
|
+
* Refactored via Extract Method (ADR D422): orchestrates 3 helpers:
|
|
673
|
+
* - validateMetadata: EC-12 detect emitDecoratorMetadata off
|
|
674
|
+
* - tryResolveSync: sync resolution loop with AsyncProvider bailout
|
|
675
|
+
* - resolveAllAsync: Promise.all fallback when any dep is async
|
|
676
|
+
*/
|
|
677
|
+
constructClassWithAsyncFallback(target, ctx) {
|
|
678
|
+
if (!hasReflectMetadata()) {
|
|
679
|
+
throw new ReflectMetadataMissingError();
|
|
680
|
+
}
|
|
681
|
+
const paramTypes = readParamTypes(target);
|
|
682
|
+
const injectTokens = readInjectTokens(target);
|
|
683
|
+
const optionalFlags = readOptionalFlags(target);
|
|
684
|
+
this.validateMetadata(target, paramTypes);
|
|
685
|
+
const syncResult = this.tryResolveSync(target, paramTypes, injectTokens, optionalFlags, ctx);
|
|
686
|
+
if ("args" in syncResult) {
|
|
687
|
+
return new target(...syncResult.args);
|
|
688
|
+
}
|
|
689
|
+
return this.resolveAllAsync(target, paramTypes, injectTokens, optionalFlags, ctx);
|
|
690
|
+
}
|
|
691
|
+
/**
|
|
692
|
+
* EC-12 detection: zero paramTypes for a class that declares a non-empty
|
|
693
|
+
* constructor strongly suggests emitDecoratorMetadata is off.
|
|
694
|
+
*/
|
|
695
|
+
validateMetadata(target, paramTypes) {
|
|
696
|
+
if (paramTypes.length === 0 && target.length > 0) {
|
|
697
|
+
throw new TypeError(`Class ${target.name} has @Injectable() but no constructor metadata. Add \`"emitDecoratorMetadata": true\` to your tsconfig.json.`);
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
/**
|
|
701
|
+
* Handle a single primitive-marker param (e.g. `param: string` without
|
|
702
|
+
* explicit @Inject). Returns `undefined` for optional, throws for required.
|
|
703
|
+
* Extracted to keep tryResolveSync below the complexity-10 cap (D422).
|
|
704
|
+
*/
|
|
705
|
+
handlePrimitiveParam(target, paramType, index, isOptional) {
|
|
706
|
+
if (isOptional) return void 0;
|
|
707
|
+
throw new TypeError(`Class ${target.name} has a primitive/interface constructor parameter at index ${index} (emitted as ${paramType.name ?? "<unknown>"}). Primitives and interfaces cannot be auto-resolved \u2014 use \`@Inject('SOME_STRING_TOKEN')\` to provide an explicit token.`);
|
|
708
|
+
}
|
|
709
|
+
/**
|
|
710
|
+
* Attempt sync resolution. Returns `{ args }` on success, `{ needsAsync: true }`
|
|
711
|
+
* if any dep raised AsyncProviderInSyncResolveError. Throws for any other error.
|
|
712
|
+
*/
|
|
713
|
+
tryResolveSync(target, paramTypes, injectTokens, optionalFlags, ctx) {
|
|
714
|
+
const args = [];
|
|
715
|
+
for (let index = 0; index < paramTypes.length; index += 1) {
|
|
716
|
+
const paramType = paramTypes[index];
|
|
717
|
+
const explicit = injectTokens.get(index);
|
|
718
|
+
const isOptional = optionalFlags.has(index);
|
|
719
|
+
const tokenForParam = explicit ?? paramType;
|
|
720
|
+
if (explicit === void 0 && isPrimitiveTypeMarker(paramType)) {
|
|
721
|
+
args.push(this.handlePrimitiveParam(target, paramType, index, isOptional));
|
|
722
|
+
continue;
|
|
723
|
+
}
|
|
724
|
+
try {
|
|
725
|
+
args.push(this.resolveOrOptional(tokenForParam, ctx, isOptional));
|
|
726
|
+
} catch (err) {
|
|
727
|
+
if (err instanceof AsyncProviderInSyncResolveError) {
|
|
728
|
+
return {
|
|
729
|
+
needsAsync: true
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
throw err;
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
return {
|
|
736
|
+
args
|
|
737
|
+
};
|
|
738
|
+
}
|
|
739
|
+
/**
|
|
740
|
+
* Async fallback: resolve every dep via resolveAsync, then construct.
|
|
741
|
+
* Called when tryResolveSync returned `{ needsAsync: true }`.
|
|
742
|
+
*/
|
|
743
|
+
resolveAllAsync(target, paramTypes, injectTokens, optionalFlags, ctx) {
|
|
744
|
+
const argPromises = paramTypes.map((paramType, index) => {
|
|
745
|
+
const explicit = injectTokens.get(index);
|
|
746
|
+
const isOptional = optionalFlags.has(index);
|
|
747
|
+
const tokenForParam = explicit ?? paramType;
|
|
748
|
+
if (explicit === void 0 && isPrimitiveTypeMarker(paramType)) {
|
|
749
|
+
return Promise.resolve(void 0);
|
|
750
|
+
}
|
|
751
|
+
return ctx.resolveAsync(tokenForParam).catch((err) => {
|
|
752
|
+
if (isOptional && err instanceof TokenNotFoundError) return void 0;
|
|
753
|
+
throw err;
|
|
754
|
+
});
|
|
755
|
+
});
|
|
756
|
+
return Promise.all(argPromises).then((args) => new target(...args));
|
|
757
|
+
}
|
|
758
|
+
resolveOrOptional(token, ctx, isOptional) {
|
|
759
|
+
try {
|
|
760
|
+
return ctx.resolve(token);
|
|
761
|
+
} catch (err) {
|
|
762
|
+
if (isOptional && err instanceof TokenNotFoundError) return void 0;
|
|
763
|
+
throw err;
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
767
|
+
// Internal: sync resolution
|
|
768
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
769
|
+
resolveInContext(token, ctx) {
|
|
770
|
+
if (ctx.path.includes(token)) {
|
|
771
|
+
throw new CyclicDependencyError([
|
|
772
|
+
...ctx.path,
|
|
773
|
+
token
|
|
774
|
+
]);
|
|
775
|
+
}
|
|
776
|
+
const cached = this.lookupCache(token);
|
|
777
|
+
if (cached !== void 0) {
|
|
778
|
+
if (cached instanceof Promise) {
|
|
779
|
+
throw new AsyncProviderInSyncResolveError(token);
|
|
780
|
+
}
|
|
781
|
+
return cached;
|
|
782
|
+
}
|
|
783
|
+
const registration = this.registrations.get(token);
|
|
784
|
+
if (registration === void 0) {
|
|
785
|
+
throw new TokenNotFoundError(token, ctx.path);
|
|
786
|
+
}
|
|
787
|
+
if (registration.scope === Scope.REQUEST) {
|
|
788
|
+
this.assertRequestActive(token);
|
|
789
|
+
}
|
|
790
|
+
const childCtx = this.createContext([
|
|
791
|
+
...ctx.path,
|
|
792
|
+
token
|
|
793
|
+
]);
|
|
794
|
+
const value = registration.factory(childCtx);
|
|
795
|
+
if (value instanceof Promise) {
|
|
796
|
+
this.storeInCache(token, value, registration.scope);
|
|
797
|
+
value.then((resolved) => {
|
|
798
|
+
this.storeInCache(token, resolved, registration.scope);
|
|
799
|
+
this.trackInstance(resolved, registration.scope);
|
|
800
|
+
}, () => {
|
|
801
|
+
this.deleteFromCache(token, registration.scope);
|
|
802
|
+
});
|
|
803
|
+
throw new AsyncProviderInSyncResolveError(token);
|
|
804
|
+
}
|
|
805
|
+
this.storeInCache(token, value, registration.scope);
|
|
806
|
+
this.trackInstance(value, registration.scope);
|
|
807
|
+
return value;
|
|
808
|
+
}
|
|
809
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
810
|
+
// Internal: async resolution (Promise-lock cache)
|
|
811
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
812
|
+
async resolveAsyncInContext(token, ctx) {
|
|
813
|
+
if (ctx.path.includes(token)) {
|
|
814
|
+
throw new CyclicDependencyError([
|
|
815
|
+
...ctx.path,
|
|
816
|
+
token
|
|
817
|
+
]);
|
|
818
|
+
}
|
|
819
|
+
const cached = this.lookupCache(token);
|
|
820
|
+
if (cached !== void 0) {
|
|
821
|
+
return cached;
|
|
822
|
+
}
|
|
823
|
+
const registration = this.registrations.get(token);
|
|
824
|
+
if (registration === void 0) {
|
|
825
|
+
throw new TokenNotFoundError(token, ctx.path);
|
|
826
|
+
}
|
|
827
|
+
if (registration.scope === Scope.REQUEST) {
|
|
828
|
+
this.assertRequestActive(token);
|
|
829
|
+
}
|
|
830
|
+
const childCtx = this.createContextAsync([
|
|
831
|
+
...ctx.path,
|
|
832
|
+
token
|
|
833
|
+
]);
|
|
834
|
+
const result = registration.factory(childCtx);
|
|
835
|
+
if (result instanceof Promise) {
|
|
836
|
+
this.storeInCache(token, result, registration.scope);
|
|
837
|
+
result.then((value) => {
|
|
838
|
+
this.storeInCache(token, value, registration.scope);
|
|
839
|
+
this.trackInstance(value, registration.scope);
|
|
840
|
+
}, () => {
|
|
841
|
+
this.deleteFromCache(token, registration.scope);
|
|
842
|
+
});
|
|
843
|
+
return result;
|
|
844
|
+
}
|
|
845
|
+
this.storeInCache(token, result, registration.scope);
|
|
846
|
+
this.trackInstance(result, registration.scope);
|
|
847
|
+
return result;
|
|
848
|
+
}
|
|
849
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
850
|
+
// Internal: scope-aware cache helpers
|
|
851
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
852
|
+
lookupCache(token) {
|
|
853
|
+
if (this.singletonCache.has(token)) return this.singletonCache.get(token);
|
|
854
|
+
const store = this.requestStorage.getStore();
|
|
855
|
+
if (store?.cache.has(token)) return store.cache.get(token);
|
|
856
|
+
return void 0;
|
|
857
|
+
}
|
|
858
|
+
storeInCache(token, value, scope) {
|
|
859
|
+
if (scope === Scope.SINGLETON) {
|
|
860
|
+
this.singletonCache.set(token, value);
|
|
861
|
+
return;
|
|
862
|
+
}
|
|
863
|
+
if (scope === Scope.REQUEST) {
|
|
864
|
+
const store = this.requestStorage.getStore();
|
|
865
|
+
if (store !== void 0) {
|
|
866
|
+
store.cache.set(token, value);
|
|
867
|
+
}
|
|
868
|
+
return;
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
deleteFromCache(token, scope) {
|
|
872
|
+
if (scope === Scope.SINGLETON) {
|
|
873
|
+
this.singletonCache.delete(token);
|
|
874
|
+
return;
|
|
875
|
+
}
|
|
876
|
+
if (scope === Scope.REQUEST) {
|
|
877
|
+
const store = this.requestStorage.getStore();
|
|
878
|
+
store?.cache.delete(token);
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
trackInstance(value, scope) {
|
|
882
|
+
if (!isDisposable(value)) return;
|
|
883
|
+
if (scope === Scope.SINGLETON) {
|
|
884
|
+
this.singletonInstances.push(value);
|
|
885
|
+
return;
|
|
886
|
+
}
|
|
887
|
+
if (scope === Scope.REQUEST) {
|
|
888
|
+
const store = this.requestStorage.getStore();
|
|
889
|
+
store?.instances.push(value);
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
assertRequestActive(token) {
|
|
893
|
+
if (this.requestStorage.getStore() === void 0) {
|
|
894
|
+
throw new ScopeViolationError(token, "REQUEST scope requires container.runInRequest(...) to be active.");
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
898
|
+
// Internal: ResolutionContext factories
|
|
899
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
900
|
+
createContext(path) {
|
|
901
|
+
return {
|
|
902
|
+
path,
|
|
903
|
+
resolve: /* @__PURE__ */ __name((t) => this.resolveInContext(t, this.createContext(path)), "resolve"),
|
|
904
|
+
resolveAsync: /* @__PURE__ */ __name((t) => this.resolveAsyncInContext(t, this.createContextAsync(path)), "resolveAsync")
|
|
905
|
+
};
|
|
906
|
+
}
|
|
907
|
+
createContextAsync(path) {
|
|
908
|
+
return {
|
|
909
|
+
path,
|
|
910
|
+
resolve: /* @__PURE__ */ __name((t) => this.resolveInContext(t, this.createContext(path)), "resolve"),
|
|
911
|
+
resolveAsync: /* @__PURE__ */ __name((t) => this.resolveAsyncInContext(t, this.createContextAsync(path)), "resolveAsync")
|
|
912
|
+
};
|
|
913
|
+
}
|
|
914
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
915
|
+
// Internal: disposal
|
|
916
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
917
|
+
async disposeInstances(instances) {
|
|
918
|
+
const errors = [];
|
|
919
|
+
for (let i = instances.length - 1; i >= 0; i -= 1) {
|
|
920
|
+
const instance = instances[i];
|
|
921
|
+
if (instance === void 0) continue;
|
|
922
|
+
try {
|
|
923
|
+
const asAsync = instance[Symbol.asyncDispose];
|
|
924
|
+
if (typeof asAsync === "function") {
|
|
925
|
+
await asAsync.call(instance);
|
|
926
|
+
} else {
|
|
927
|
+
await instance.dispose();
|
|
928
|
+
}
|
|
929
|
+
} catch (err) {
|
|
930
|
+
errors.push(err);
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
instances.length = 0;
|
|
934
|
+
if (errors.length > 0) {
|
|
935
|
+
throw new AggregateError(errors, "One or more instances failed to dispose.");
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
};
|
|
939
|
+
function isDisposable(value) {
|
|
940
|
+
if (value === null || typeof value !== "object") return false;
|
|
941
|
+
const candidate = value;
|
|
942
|
+
if (typeof candidate.dispose === "function") return true;
|
|
943
|
+
if (typeof candidate[Symbol.asyncDispose] === "function") return true;
|
|
944
|
+
return false;
|
|
945
|
+
}
|
|
946
|
+
__name(isDisposable, "isDisposable");
|
|
947
|
+
|
|
948
|
+
// src/decorators/inject.ts
|
|
949
|
+
function Inject(token) {
|
|
950
|
+
return (target, _propertyKey, parameterIndex) => {
|
|
951
|
+
const existing = Reflect.getMetadata(METADATA_KEYS.INJECT_TOKENS, target);
|
|
952
|
+
const map = existing instanceof Map ? existing : /* @__PURE__ */ new Map();
|
|
953
|
+
map.set(parameterIndex, token);
|
|
954
|
+
Reflect.defineMetadata(METADATA_KEYS.INJECT_TOKENS, map, target);
|
|
955
|
+
};
|
|
956
|
+
}
|
|
957
|
+
__name(Inject, "Inject");
|
|
958
|
+
|
|
959
|
+
// src/decorators/injectable.ts
|
|
960
|
+
function Injectable(options = {}) {
|
|
961
|
+
return (target) => {
|
|
962
|
+
const metadata = options.scope !== void 0 ? {
|
|
963
|
+
scope: options.scope
|
|
964
|
+
} : {};
|
|
965
|
+
Reflect.defineMetadata(METADATA_KEYS.INJECTABLE, metadata, target);
|
|
966
|
+
};
|
|
967
|
+
}
|
|
968
|
+
__name(Injectable, "Injectable");
|
|
969
|
+
|
|
970
|
+
// src/decorators/optional.ts
|
|
971
|
+
function Optional() {
|
|
972
|
+
return (target, _propertyKey, parameterIndex) => {
|
|
973
|
+
const existing = Reflect.getMetadata(METADATA_KEYS.OPTIONAL_FLAGS, target);
|
|
974
|
+
const set = existing instanceof Set ? existing : /* @__PURE__ */ new Set();
|
|
975
|
+
set.add(parameterIndex);
|
|
976
|
+
Reflect.defineMetadata(METADATA_KEYS.OPTIONAL_FLAGS, set, target);
|
|
977
|
+
};
|
|
978
|
+
}
|
|
979
|
+
__name(Optional, "Optional");
|
|
980
|
+
|
|
981
|
+
exports.AsyncProviderInSyncResolveError = AsyncProviderInSyncResolveError;
|
|
982
|
+
exports.Container = Container;
|
|
983
|
+
exports.ContainerDisposedError = ContainerDisposedError;
|
|
984
|
+
exports.ContainerFrozenError = ContainerFrozenError;
|
|
985
|
+
exports.CyclicDependencyError = CyclicDependencyError;
|
|
986
|
+
exports.CyclicModuleImportError = CyclicModuleImportError;
|
|
987
|
+
exports.Inject = Inject;
|
|
988
|
+
exports.Injectable = Injectable;
|
|
989
|
+
exports.InvalidExportError = InvalidExportError;
|
|
990
|
+
exports.InvalidModuleError = InvalidModuleError;
|
|
991
|
+
exports.MissingInjectableError = MissingInjectableError;
|
|
992
|
+
exports.Module = Module;
|
|
993
|
+
exports.Optional = Optional;
|
|
994
|
+
exports.ReflectMetadataMissingError = ReflectMetadataMissingError;
|
|
995
|
+
exports.Scope = Scope;
|
|
996
|
+
exports.ScopeViolationError = ScopeViolationError;
|
|
997
|
+
exports.TokenNotFoundError = TokenNotFoundError;
|
|
998
|
+
exports.describeToken = describeToken;
|
|
999
|
+
//# sourceMappingURL=index.cjs.map
|
|
1000
|
+
//# sourceMappingURL=index.cjs.map
|