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