@theokit/di 0.1.1 → 0.2.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 CHANGED
@@ -1,13 +1,5 @@
1
1
  # Changelog
2
2
 
3
- ## 0.1.1
4
-
5
- ### Patch Changes
6
-
7
- - 461c020: Add `METADATA_KEYS.SQUAD` (`"usetheo:di:squad"`) and `METADATA_KEYS.STEP` (`"usetheo:di:step"`) — new metadata keys backing the `@Squad()` and `@Step()` decorators in `@theokit/di-agent`. Shipped as a patch (additive values on the existing exported `METADATA_KEYS`) to keep `@theokit/di-agent` and the in-progress `@theokit/orm` (prerelease `0.1.0-next.1`) inside their `^0.1.0` peer range — a `minor` (`0.2.0`) would fall outside `^0.1.x` and force both dependents to `1.0.0`.
8
-
9
- Also: broke the `container.ts ↔ internal/module-loader.ts` type-only cycle (arch-review ADR 0001) — `loadModule` now depends on a narrow `ModuleRegistrar` interface from the leaf `types.ts` instead of the concrete `Container`. No behavior change; `Container` satisfies it structurally.
10
-
11
3
  All notable changes to `@theokit/di` are documented in this file.
12
4
 
13
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
@@ -15,29 +7,61 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
15
7
 
16
8
  ## [Unreleased]
17
9
 
10
+ ## [0.2.0] - 2026-08-21
11
+
18
12
  ### Added
19
13
 
20
- - `METADATA_KEYS.SQUAD` (`"usetheo:di:squad"`) — metadata key backing the `@Squad()` decorator in `@theokit/di-agent`.
21
- - `METADATA_KEYS.STEP` (`"usetheo:di:step"`) — metadata key backing the `@Step()` decorator in `@theokit/di-agent`.
14
+ - Every published export now carries documentation an editor can show. Measured on the emitted
15
+ declarations, 33/37 to 37/37. (#24)
16
+
17
+ - npm provenance is enabled again. It was switched off because npm refuses attestation for packages built from a private source repository; this one is public now, so published tarballs carry a sigstore attestation linking them to the commit and workflow that produced them.
18
+ - `@PostConstruct` is now called. The container invokes the marked method once the instance is built and every constructor dependency is injected — once per instance, so a SINGLETON initialises once however often it is resolved. An async hook is awaited by `resolveAsync`; `resolve()` cannot await one and throws `AsyncPostConstructInSyncResolveError` rather than return an object whose initialiser is still running (#5).
19
+ - `@PreDestroy` is now called, before `dispose()` when a class has both, and awaited if it returns a Promise. A class no longer needs a `dispose()` method to be torn down — declaring the hook is enough for the container to track it. A failing hook no longer stops the others; the failures arrive together as an `AggregateError` (#5).
20
+ - `AsyncPostConstructInSyncResolveError`, exported so consumers can catch it by type.
22
21
 
23
22
  ### Changed
24
23
 
25
- - Broke the `container.ts ↔ internal/module-loader.ts` type-only dependency cycle (arch-review ADR 0001). `loadModule` now takes a narrow `ModuleRegistrar` interface (just `register(...)`) from the leaf `types.ts` instead of importing the concrete `Container`. No behavior change — `Container` satisfies it structurally; all 69 tests GREEN, `madge --circular` clean.
24
+ - `repository`, `homepage` and `bugs` now point at `usetheokit/theokit-di`. They pointed at `usetheo/theokit-sdk`, so every "Repository" and "Report issues" link on npm led to a project that does not host this package.
25
+ - The package description no longer names `@theokit/http-decorators`, which does not exist. The package is `@theokit/http`.
26
+ - The README no longer carries a Portuguese clause, and says plainly where `@theokit/http` ships from.
27
+ - JSDoc on the public surface no longer cites ADRs, audit findings, plan tasks or edge-case identifiers that exist in no repository a reader can reach. The rationale each citation stood for is now written inline, so it survives into the published type declarations.
28
+ - `Primary` now declares its parameter as a constructor type rather than `Function`. `Function` is the widest callable type there is, so it documented nothing and admitted values that are not classes. Any class you could already decorate still type-checks.
29
+
30
+ ### Fixed
31
+
32
+ - **Breaking:** `container.dispose()` no longer tears down a value it was handed rather than built.
33
+ A `useValue` with a `dispose()` method was being closed by the container even though the caller
34
+ constructed it and still holds the reference — so a caller who closed their own pool, as every
35
+ convention says they should, closed it twice. The rule is now ownership: the container tears down
36
+ what it constructed (`useClass`, `useFactory`) and leaves alone what it was given. (#23)
37
+ - **Breaking:** an instance reached through `useExisting` is disposed once, not once per token that
38
+ names it. An alias resolves to the same object by definition, and the container was tracking it
39
+ again under the alias, so a resource behind two tokens was closed twice.
40
+ Both were found while documenting the disposal contract: the docblock stated the ownership rule
41
+ and the code did not implement it. Neither shape appeared in any of the eight disposal tests;
42
+ five now cover them. (#23)
43
+ - `@Primary` and `@Qualifier` documented a resolution priority the container has never had. They record metadata and nothing else, and their JSDoc now says exactly that, with the working alternative alongside. Implementing them means holding several registrations per token — which is the cache key, the cycle-detection node identity and the disposal order — so it is a design decision rather than a missing branch, and it has not been made (#5).
44
+ - The English-only lint gate could not fail on an accented word. It split identifiers with an ASCII-only pattern before testing them for diacritics, so `não` became `n` and `o` and the diacritic tier was unreachable. Both tiers now work, verified by planting an accented identifier and watching the sweep turn red (#7).
26
45
 
27
- ### Changed
28
46
 
29
- - **Documentation only:** expanded JSDoc header on `Container` class (`src/container.ts:87`) acknowledging auditor finding PV#10 from the 2026-06-06 architecture audit. The 812 LOC class size is above the 500 LOC heuristic file budget but justified as the Single-Point-of-Truth for DI resolution (registry lookup, lifecycle SINGLETON/TRANSIENT/REQUEST, `@Injectable` metadata read, alias resolution, request-scope ALS propagation, dispose chain). Splitting would fragment cohesion per `rules/architecture.md § 3` + KISS / YAGNI. ADR D422 tracks ongoing Extract-Method refactor at the method level. No code change. Plan `arch-review-fixes-2026-06-06` T11.2 records the trade-off.
47
+ ## 0.1.1
48
+
49
+ ### Patch Changes
50
+
51
+ - Add `METADATA_KEYS.SQUAD` (`"usetheo:di:squad"`) and `METADATA_KEYS.STEP` (`"usetheo:di:step"`) — new metadata keys backing the `@Squad()` and `@Step()` decorators in `@theokit/di-agent`. Shipped as a patch (additive values on the existing exported `METADATA_KEYS`) to keep `@theokit/di-agent` and the in-progress `@theokit/orm` (prerelease `0.1.0-next.1`) inside their `^0.1.0` peer range — a `minor` (`0.2.0`) would fall outside `^0.1.x` and force both dependents to `1.0.0`.
52
+
53
+ Also: broke the `container.ts ↔ internal/module-loader.ts` type-only cycle — `loadModule` now depends on a narrow `ModuleRegistrar` interface from the leaf `types.ts` instead of the concrete `Container`. No behavior change; `Container` satisfies it structurally.
30
54
 
31
55
  ## [0.1.0] - 2026-05-31
32
56
 
33
- > First GA release. Promotes `0.1.0-next.0` to stable with the EC-R3-1 single-flight Promise cache fix (shipped in `0.1.0-next.0` commit `520fe7d`) plus the biome-cleanup refactors below. API contract preserved — no breaking changes from `0.1.0-next.0`.
57
+ > First GA release. Promotes `0.1.0-next.0` to stable with the single-flight Promise cache fix (shipped in `0.1.0-next.0`) plus the complexity refactors below. API contract preserved — no breaking changes from `0.1.0-next.0`.
34
58
 
35
59
  ### Changed
36
60
 
37
- - Refactored `Container.constructClassWithAsyncFallback<T>` (complexity 18 → ≤10) via Extract Method: introduced 4 private helpers (`validateMetadata`, `handlePrimitiveParam`, `tryResolveSync`, `resolveAllAsync`). Behavior preserved; reflect-metadata error ordering + async-fallback semantics unchanged. (theokit-sdk-biome-cleanup)
38
- - Refactored `Container.fromFactoryProvider` (complexity 11 → ≤10) via Extract Method: introduced `tryResolveSyncDeps` private helper returning a discriminated union for sync/async dispatch. (theokit-sdk-biome-cleanup)
39
- - Removed redundant `export` on `MODULE_METADATA_KEY` (internal-only — never part of public surface). (theokit-sdk-biome-cleanup)
40
- - See ADR D422 for the consolidated rationale (parameter decorators enabled in biome + container Extract Method refactor).
61
+ - Refactored `Container.constructClassWithAsyncFallback<T>` (complexity 18 → ≤10) via Extract Method: introduced 4 private helpers (`validateMetadata`, `handlePrimitiveParam`, `tryResolveSync`, `resolveAllAsync`). Behavior preserved; reflect-metadata error ordering + async-fallback semantics unchanged.
62
+ - Refactored `Container.fromFactoryProvider` (complexity 11 → ≤10) via Extract Method: introduced `tryResolveSyncDeps` private helper returning a discriminated union for sync/async dispatch.
63
+ - Removed redundant `export` on `MODULE_METADATA_KEY` (internal-only — never part of public surface).
64
+ - Parameter decorators were enabled in biome in the same pass, which is what let the container tests keep their `@Inject` annotations.
41
65
 
42
66
  ## [0.1.0-next.0] - 2026-05-29
43
67
 
@@ -48,15 +72,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
48
72
  - 5 decorators: `@Injectable()`, `@Inject(token)`, `@Optional()`, `@Module({...})` — NestJS-compatible API.
49
73
  - 4 provider types: `useClass`, `useFactory`, `useValue`, `useExisting`.
50
74
  - 3 lifecycle scopes: `SINGLETON` (default), `TRANSIENT`, `REQUEST` (via `AsyncLocalStorage`).
51
- - Cycle detection at resolve-time (Promise-lock cache with cycle-first ordering per v1.2 EC-R2-1 prevents async deadlocks).
52
- - Cache cleanup on Promise rejection (v1.2 EC-R2-2) — transient factory failures do NOT poison the REQUEST cache.
53
- - `runInRequest()` try/finally guarantees REQUEST instances are disposed even on callback throw (v1.1 EC-3).
54
- - `validateClassProvider()` centralized validation — both declarative `providers: []` and imperative `register()` reject undecorated classes (v1.1 EC-1).
55
- - Container freezes after first `resolve()`; `allowDynamicRegistration: true` opt-out for tests (v1.2 EC-R2-5).
75
+ - Cycle detection at resolve-time the Promise-lock cache checks for a cycle before consulting the cache, which is what prevents an async deadlock.
76
+ - Cache cleanup on Promise rejection — transient factory failures do NOT poison the REQUEST cache.
77
+ - `runInRequest()` try/finally guarantees REQUEST instances are disposed even on callback throw.
78
+ - `validateClassProvider()` centralized validation — both declarative `providers: []` and imperative `register()` reject undecorated classes.
79
+ - Container freezes after first `resolve()`; `allowDynamicRegistration: true` opt-out for tests.
56
80
  - Module loading with cycle detection (DFS), export validation at register-time, BFS-style transitive provider import.
57
81
  - Typed errors: `TokenNotFoundError`, `CyclicDependencyError`, `AsyncProviderInSyncResolveError`, `ScopeViolationError`, `MissingInjectableError`, `ContainerDisposedError`, `ContainerFrozenError`, `InvalidModuleError`, `InvalidExportError`, `CyclicModuleImportError`, `ReflectMetadataMissingError`.
58
82
  - Disposal lifecycle: `dispose()` calls `Symbol.asyncDispose` (preferred) or `dispose()` on each instance in reverse construction order; aggregates errors via `AggregateError`.
59
- - Foundation for `@theokit/orm` (P2) and `@theokit/http-decorators` (P3). Agent-first integration ships as separate `@theokit/di-agent` package (zero coupling per ADR D8).
83
+ - Foundation for `@theokit/orm` and `@theokit/http`. Agent-first integration ships as the separate `@theokit/di-agent` package, with zero coupling.
60
84
 
61
85
  ### Bundle / Coverage
62
86
 
@@ -64,6 +88,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
64
88
  - Bundle: ESM 11.55 KB / CJS 11.32 KB (gzipped est.).
65
89
  - Dual ESM + CJS, target Node 22.12+, dts emitted.
66
90
 
67
- ### Polyglot strategy (read ADR D11)
91
+ ### Polyglot strategy
68
92
 
69
- `@theokit/di` is **intentionally TS-only**. DI containers are intrinsically language-specific runtime constructs. The polyglot story for the theokit ecosystem lives in the contract layer — `@theokit/orm` (P2, schema export to JSON Schema + SQL migrations) and `@theokit/http-decorators` (P3, OpenAPI 3.x emit from `@Controller` decorators). Python/Go SDKs will be generated from those specs (Supabase/Appwrite pattern), NOT by porting the DI container.
93
+ `@theokit/di` is **intentionally TS-only**. DI containers are intrinsically language-specific runtime constructs. The polyglot story for the theokit ecosystem lives in the contract layer — `@theokit/orm` (schema export to JSON Schema and SQL migrations) and `@theokit/http` (OpenAPI 3.x emitted from `@Controller` decorators). Python/Go SDKs will be generated from those specs (Supabase/Appwrite pattern), NOT by porting the DI container.
package/LICENSE CHANGED
@@ -137,8 +137,8 @@
137
137
 
138
138
  6. Trademarks. This License does not grant permission to use the trade
139
139
  names, trademarks, service marks, or product names of the Licensor,
140
- except as required for describing the origin of the Work and
141
- reproducing the content of the NOTICE file.
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
142
 
143
143
  7. Disclaimer of Warranty. Unless required by applicable law or
144
144
  agreed to in writing, Licensor provides the Work (and each
package/README.md CHANGED
@@ -2,9 +2,9 @@
2
2
 
3
3
  > Lightweight TypeScript dependency injection container for the theokit ecosystem.
4
4
 
5
- NestJS-compatible API (`@Injectable`, `@Inject`, `@Module`, `providers: []`) with three lifecycle scopes (SINGLETON, TRANSIENT, REQUEST via AsyncLocalStorage). Foundation for [`@theokit/orm`](../orm) and [`@theokit/http-decorators`](../http-decorators). Agent-aware integration via the companion [`@theokit/di-agent`](../di-agent) package.
5
+ NestJS-compatible API (`@Injectable`, `@Inject`, `@Module`, `providers: []`) with three lifecycle scopes (SINGLETON, TRANSIENT, REQUEST via AsyncLocalStorage). Foundation for [`@theokit/orm`](../orm) and `@theokit/http`, which ships from the sibling `theokit` repository under `packages/http`. An earlier name, `@theokit/http-decorators`, no longer exists. Agent-aware integration via the companion [`@theokit/di-agent`](../di-agent) package.
6
6
 
7
- **Status:** initial release (`0.1.0-next.0` on npm `next` tag — promote to `latest` after 1-2 weeks dogfood).
7
+ **Status:** `0.1.1` on npm `latest`.
8
8
 
9
9
  ## Install
10
10
 
@@ -58,7 +58,7 @@ console.log(greeter.greet("world")); // Hello, world!
58
58
 
59
59
  ## Polyglot strategy
60
60
 
61
- `@theokit/di` is **intentionally TS-only**. DI containers are language-specific runtime constructs — Python uses `inspect`/`typing.get_type_hints`, Go uses `reflect`, etc. The cross-language story for the theokit ecosystem lives in the **contract layer** (OpenAPI from `@theokit/http-decorators`, SQL migrations + JSON schemas from `@theokit/orm`), not in the container. See ADR D11 of the implementation plan.
61
+ `@theokit/di` is **intentionally TS-only**. DI containers are language-specific runtime constructs — Python uses `inspect`/`typing.get_type_hints`, Go uses `reflect`, etc. The cross-language story for the theokit ecosystem lives in the **contract layer** (OpenAPI from `@theokit/http`, SQL migrations + JSON schemas from `@theokit/orm`), not in the container.
62
62
 
63
63
  ## License
64
64
 
package/dist/index.cjs CHANGED
@@ -49,6 +49,17 @@ var AsyncProviderInSyncResolveError = class extends Error {
49
49
  super(`Provider for token ${describeToken(token)} is async (factory returned a Promise). Use container.resolveAsync() instead of container.resolve().`), this.token = token;
50
50
  }
51
51
  };
52
+ var AsyncPostConstructInSyncResolveError = class extends Error {
53
+ static {
54
+ __name(this, "AsyncPostConstructInSyncResolveError");
55
+ }
56
+ className;
57
+ methodName;
58
+ name = "AsyncPostConstructInSyncResolveError";
59
+ constructor(className, methodName) {
60
+ super(`@PostConstruct ${className}.${methodName}() returned a Promise, and container.resolve() cannot await it. Use container.resolveAsync() instead, or make ${methodName}() synchronous.`), this.className = className, this.methodName = methodName;
61
+ }
62
+ };
52
63
  var ScopeViolationError = class extends Error {
53
64
  static {
54
65
  __name(this, "ScopeViolationError");
@@ -207,7 +218,7 @@ var METADATA_KEYS = {
207
218
  SQUAD: "usetheo:di:squad",
208
219
  /** Map<string|symbol, StepMetadata> from `@Step()` method decorator. */
209
220
  STEP: "usetheo:di:step",
210
- /** HitlOptions from `@Hitl()` method decorator. */
221
+ /** Map<string|symbol, HitlMetadata> from `@Hitl()` method decorator. */
211
222
  HITL: "usetheo:di:hitl",
212
223
  /** AutoSummarizeConfig from `@AutoSummarize()` class decorator. */
213
224
  AUTO_SUMMARIZE: "usetheo:di:auto-summarize",
@@ -217,7 +228,7 @@ var METADATA_KEYS = {
217
228
  WORKFLOW: "usetheo:di:workflow",
218
229
  /** EvalOptions from `@Eval()` class decorator. */
219
230
  EVAL: "usetheo:di:eval",
220
- /** CronMetadata from `@Cron()` method decorator. */
231
+ /** Map<string|symbol, CronMetadata> from `@Cron()` method decorator. */
221
232
  CRON: "usetheo:di:cron",
222
233
  /** Map<string|symbol, SubscriptionOptions> from `@Subscription()` property decorator. */
223
234
  SUBSCRIPTION: "usetheo:di:subscription",
@@ -269,6 +280,21 @@ function isInjectable(target) {
269
280
  return readInjectableMetadata(target) !== void 0;
270
281
  }
271
282
  __name(isInjectable, "isInjectable");
283
+ function readPostConstruct(target) {
284
+ return readLifecycleHook(target, METADATA_KEYS.POST_CONSTRUCT);
285
+ }
286
+ __name(readPostConstruct, "readPostConstruct");
287
+ function readPreDestroy(target) {
288
+ return readLifecycleHook(target, METADATA_KEYS.PRE_DESTROY);
289
+ }
290
+ __name(readPreDestroy, "readPreDestroy");
291
+ function readLifecycleHook(target, key) {
292
+ if (!hasReflectMetadata()) return void 0;
293
+ const out = Reflect.getMetadata(key, target);
294
+ if (typeof out === "string" || typeof out === "symbol") return out;
295
+ return void 0;
296
+ }
297
+ __name(readLifecycleHook, "readLifecycleHook");
272
298
  var PRIMITIVE_WRAPPERS = /* @__PURE__ */ new Set([
273
299
  Number,
274
300
  String,
@@ -399,6 +425,11 @@ var Scope = {
399
425
  };
400
426
 
401
427
  // src/container.ts
428
+ var ASYNC_CONTEXT = /* @__PURE__ */ Symbol("theokit.di.asyncContext");
429
+ function isAsyncContext(ctx) {
430
+ return ctx[ASYNC_CONTEXT] === true;
431
+ }
432
+ __name(isAsyncContext, "isAsyncContext");
402
433
  var Container = class {
403
434
  static {
404
435
  __name(this, "Container");
@@ -424,7 +455,7 @@ var Container = class {
424
455
  * - A full Provider (useClass / useFactory / useValue / useExisting)
425
456
  * - A bare class (shorthand expands to ClassProvider { provide: X, useClass: X })
426
457
  *
427
- * Per v1.1 EC-1, ClassProvider validation runs via `validateClassProvider()`
458
+ * ClassProvider validation runs via `validateClassProvider()`
428
459
  * regardless of which API path was used.
429
460
  */
430
461
  register(providerOrClass) {
@@ -444,9 +475,9 @@ var Container = class {
444
475
  * modules. Walks imports BFS, registers every provider, validates
445
476
  * exports.
446
477
  *
447
- * Per v1.1 EC-4: undecorated class throws `InvalidModuleError`.
448
- * Per v1.2 EC-R2-5: respects the freeze-after-first-resolve guarantee
449
- * (each child `register()` checks `assertNotFrozen`).
478
+ * An undecorated class throws `InvalidModuleError`. Respects the
479
+ * freeze-after-first-resolve guarantee — each child `register()` checks
480
+ * `assertNotFrozen`.
450
481
  */
451
482
  registerModule(moduleClass) {
452
483
  this.assertNotDisposed();
@@ -483,7 +514,7 @@ var Container = class {
483
514
  * providers resolved within `callback` (or any async continuation) share
484
515
  * a single per-request cache.
485
516
  *
486
- * v1.1 EC-3: try/finally guarantees REQUEST-scoped instances are disposed
517
+ * try/finally guarantees REQUEST-scoped instances are disposed
487
518
  * even if the callback throws.
488
519
  */
489
520
  async runInRequest(callback) {
@@ -501,7 +532,7 @@ var Container = class {
501
532
  /**
502
533
  * Debug helper — returns a snapshot of the dependency graph.
503
534
  *
504
- * Per ADR D7: detects cycles in unused providers too (resolve-time
535
+ * Detects cycles in unused providers too (resolve-time
505
536
  * detection only fires for resolves that actually traverse the cycle).
506
537
  * Use this proactively in tests / dev mode to surface latent cycles.
507
538
  */
@@ -602,7 +633,7 @@ var Container = class {
602
633
  }
603
634
  }
604
635
  /**
605
- * v1.1 EC-1: shared by both declarative providers: [] AND imperative
636
+ * Shared by both declarative providers: [] AND imperative
606
637
  * register() — every class provider must have @Injectable().
607
638
  */
608
639
  validateClassProvider(provider) {
@@ -617,7 +648,7 @@ var Container = class {
617
648
  if (this.disposed) throw new ContainerDisposedError();
618
649
  }
619
650
  /**
620
- * v1.2 EC-R2-5: container freezes on first resolve. Late registrations
651
+ * The container freezes on first resolve. Late registrations
621
652
  * require explicit `allowDynamicRegistration: true` (testing escape hatch).
622
653
  */
623
654
  assertNotFrozen(token) {
@@ -648,7 +679,8 @@ var Container = class {
648
679
  token: provider.provide,
649
680
  scope,
650
681
  factory: /* @__PURE__ */ __name((ctx) => this.constructClassWithAsyncFallback(target, ctx), "factory"),
651
- classTarget: target
682
+ classTarget: target,
683
+ containerOwned: true
652
684
  };
653
685
  }
654
686
  fromFactoryProvider(provider) {
@@ -663,7 +695,8 @@ var Container = class {
663
695
  }
664
696
  return Promise.all(injectTokens.map((dep) => ctx.resolveAsync(dep))).then((asyncArgs) => provider.useFactory(...asyncArgs));
665
697
  }, "factory"),
666
- injectTokens
698
+ injectTokens,
699
+ containerOwned: true
667
700
  };
668
701
  }
669
702
  /**
@@ -694,7 +727,8 @@ var Container = class {
694
727
  return {
695
728
  token: provider.provide,
696
729
  scope: Scope.SINGLETON,
697
- factory: /* @__PURE__ */ __name(() => provider.useValue, "factory")
730
+ factory: /* @__PURE__ */ __name(() => provider.useValue, "factory"),
731
+ containerOwned: false
698
732
  };
699
733
  }
700
734
  fromExistingProvider(provider) {
@@ -702,15 +736,16 @@ var Container = class {
702
736
  token: provider.provide,
703
737
  scope: Scope.SINGLETON,
704
738
  factory: /* @__PURE__ */ __name((ctx) => ctx.resolve(provider.useExisting), "factory"),
705
- aliasTarget: provider.useExisting
739
+ aliasTarget: provider.useExisting,
740
+ containerOwned: false
706
741
  };
707
742
  }
708
743
  /**
709
744
  * Resolve constructor params + build instance. Tries sync first; if any
710
745
  * dep is async, falls back to awaiting via `resolveAsync`.
711
746
  *
712
- * Refactored via Extract Method (ADR D422): orchestrates 3 helpers:
713
- * - validateMetadata: EC-12 detect emitDecoratorMetadata off
747
+ * Refactored via Extract Method: orchestrates 3 helpers:
748
+ * - validateMetadata: detect emitDecoratorMetadata off
714
749
  * - tryResolveSync: sync resolution loop with AsyncProvider bailout
715
750
  * - resolveAllAsync: Promise.all fallback when any dep is async
716
751
  */
@@ -724,12 +759,13 @@ var Container = class {
724
759
  this.validateMetadata(target, paramTypes);
725
760
  const syncResult = this.tryResolveSync(target, paramTypes, injectTokens, optionalFlags, ctx);
726
761
  if ("args" in syncResult) {
727
- return new target(...syncResult.args);
762
+ const instance = new target(...syncResult.args);
763
+ return isAsyncContext(ctx) ? runPostConstructAsync(target, instance) : runPostConstructSync(target, instance);
728
764
  }
729
- return this.resolveAllAsync(target, paramTypes, injectTokens, optionalFlags, ctx);
765
+ return this.resolveAllAsync(target, paramTypes, injectTokens, optionalFlags, ctx).then((instance) => runPostConstructAsync(target, instance));
730
766
  }
731
767
  /**
732
- * EC-12 detection: zero paramTypes for a class that declares a non-empty
768
+ * Detection: zero paramTypes for a class that declares a non-empty
733
769
  * constructor strongly suggests emitDecoratorMetadata is off.
734
770
  */
735
771
  validateMetadata(target, paramTypes) {
@@ -836,14 +872,14 @@ var Container = class {
836
872
  this.storeInCache(token, value, registration.scope);
837
873
  value.then((resolved) => {
838
874
  this.storeInCache(token, resolved, registration.scope);
839
- this.trackInstance(resolved, registration.scope);
875
+ this.trackInstance(resolved, registration);
840
876
  }, () => {
841
877
  this.deleteFromCache(token, registration.scope);
842
878
  });
843
879
  throw new AsyncProviderInSyncResolveError(token);
844
880
  }
845
881
  this.storeInCache(token, value, registration.scope);
846
- this.trackInstance(value, registration.scope);
882
+ this.trackInstance(value, registration);
847
883
  return value;
848
884
  }
849
885
  // ─────────────────────────────────────────────────────────────────────
@@ -876,14 +912,14 @@ var Container = class {
876
912
  this.storeInCache(token, result, registration.scope);
877
913
  result.then((value) => {
878
914
  this.storeInCache(token, value, registration.scope);
879
- this.trackInstance(value, registration.scope);
915
+ this.trackInstance(value, registration);
880
916
  }, () => {
881
917
  this.deleteFromCache(token, registration.scope);
882
918
  });
883
919
  return result;
884
920
  }
885
921
  this.storeInCache(token, result, registration.scope);
886
- this.trackInstance(result, registration.scope);
922
+ this.trackInstance(result, registration);
887
923
  return result;
888
924
  }
889
925
  // ─────────────────────────────────────────────────────────────────────
@@ -918,8 +954,18 @@ var Container = class {
918
954
  store?.cache.delete(token);
919
955
  }
920
956
  }
921
- trackInstance(value, scope) {
922
- if (!isDisposable(value)) return;
957
+ /**
958
+ * Record an instance for teardown, when this container is the one that should tear it down.
959
+ *
960
+ * Two questions, in this order. Does the container OWN it — see `containerOwned`; a value the
961
+ * caller handed in and an instance reached through an alias are both refused here. And does it
962
+ * have any teardown at all: a class whose only teardown is `@PreDestroy` has no `dispose()`, so
963
+ * testing `isDisposable` alone would silently skip it.
964
+ */
965
+ trackInstance(value, registration) {
966
+ if (!registration.containerOwned) return;
967
+ const { scope } = registration;
968
+ if (!isDisposable(value) && !hasPreDestroy(value)) return;
923
969
  if (scope === Scope.SINGLETON) {
924
970
  this.singletonInstances.push(value);
925
971
  return;
@@ -945,11 +991,14 @@ var Container = class {
945
991
  };
946
992
  }
947
993
  createContextAsync(path) {
948
- return {
994
+ const ctx = {
949
995
  path,
950
996
  resolve: /* @__PURE__ */ __name((t) => this.resolveInContext(t, this.createContext(path)), "resolve"),
951
997
  resolveAsync: /* @__PURE__ */ __name((t) => this.resolveAsyncInContext(t, this.createContextAsync(path)), "resolveAsync")
952
998
  };
999
+ return Object.assign(ctx, {
1000
+ [ASYNC_CONTEXT]: true
1001
+ });
953
1002
  }
954
1003
  // ─────────────────────────────────────────────────────────────────────
955
1004
  // Internal: disposal
@@ -960,10 +1009,11 @@ var Container = class {
960
1009
  const instance = instances[i];
961
1010
  if (instance === void 0) continue;
962
1011
  try {
1012
+ await callPreDestroy(instance);
963
1013
  const asAsync = instance[Symbol.asyncDispose];
964
1014
  if (typeof asAsync === "function") {
965
1015
  await asAsync.call(instance);
966
- } else {
1016
+ } else if (isDisposable(instance)) {
967
1017
  await instance.dispose();
968
1018
  }
969
1019
  } catch (err) {
@@ -984,6 +1034,49 @@ function isDisposable(value) {
984
1034
  return false;
985
1035
  }
986
1036
  __name(isDisposable, "isDisposable");
1037
+ function callPostConstruct(target, instance) {
1038
+ const hook = readPostConstruct(target);
1039
+ if (hook === void 0) return void 0;
1040
+ const method = instance[hook];
1041
+ if (typeof method !== "function") return void 0;
1042
+ return method.call(instance);
1043
+ }
1044
+ __name(callPostConstruct, "callPostConstruct");
1045
+ function runPostConstructSync(target, instance) {
1046
+ const returned = callPostConstruct(target, instance);
1047
+ if (isThenable(returned)) {
1048
+ throw new AsyncPostConstructInSyncResolveError(target.name, String(readPostConstruct(target)));
1049
+ }
1050
+ return instance;
1051
+ }
1052
+ __name(runPostConstructSync, "runPostConstructSync");
1053
+ async function runPostConstructAsync(target, instance) {
1054
+ const returned = callPostConstruct(target, instance);
1055
+ if (isThenable(returned)) await returned;
1056
+ return instance;
1057
+ }
1058
+ __name(runPostConstructAsync, "runPostConstructAsync");
1059
+ async function callPreDestroy(instance) {
1060
+ const ctor = instance.constructor;
1061
+ if (typeof ctor !== "function") return;
1062
+ const hook = readPreDestroy(ctor);
1063
+ if (hook === void 0) return;
1064
+ const method = instance[hook];
1065
+ if (typeof method !== "function") return;
1066
+ await method.call(instance);
1067
+ }
1068
+ __name(callPreDestroy, "callPreDestroy");
1069
+ function hasPreDestroy(value) {
1070
+ if (value === null || typeof value !== "object") return false;
1071
+ const ctor = value.constructor;
1072
+ if (typeof ctor !== "function") return false;
1073
+ return readPreDestroy(ctor) !== void 0;
1074
+ }
1075
+ __name(hasPreDestroy, "hasPreDestroy");
1076
+ function isThenable(value) {
1077
+ return value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
1078
+ }
1079
+ __name(isThenable, "isThenable");
987
1080
 
988
1081
  // src/decorators/inject.ts
989
1082
  function Inject(token) {
@@ -1044,6 +1137,7 @@ function Qualifier(name) {
1044
1137
  }
1045
1138
  __name(Qualifier, "Qualifier");
1046
1139
 
1140
+ exports.AsyncPostConstructInSyncResolveError = AsyncPostConstructInSyncResolveError;
1047
1141
  exports.AsyncProviderInSyncResolveError = AsyncProviderInSyncResolveError;
1048
1142
  exports.Container = Container;
1049
1143
  exports.ContainerDisposedError = ContainerDisposedError;