@theokit/di 0.1.0 → 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 +60 -13
- package/LICENSE +2 -2
- package/README.md +3 -3
- package/dist/index.cjs +191 -26
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +269 -30
- package/dist/index.d.ts +269 -30
- package/dist/index.js +186 -27
- package/dist/index.js.map +1 -1
- package/package.json +19 -16
package/CHANGELOG.md
CHANGED
|
@@ -5,16 +5,63 @@ All notable changes to `@theokit/di` are documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [Unreleased]
|
|
9
|
+
|
|
10
|
+
## [0.2.0] - 2026-08-21
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
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.
|
|
21
|
+
|
|
22
|
+
### Changed
|
|
23
|
+
|
|
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).
|
|
45
|
+
|
|
46
|
+
|
|
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.
|
|
54
|
+
|
|
8
55
|
## [0.1.0] - 2026-05-31
|
|
9
56
|
|
|
10
|
-
> First GA release. Promotes `0.1.0-next.0` to stable with the
|
|
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`.
|
|
11
58
|
|
|
12
59
|
### Changed
|
|
13
60
|
|
|
14
|
-
- 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.
|
|
15
|
-
- Refactored `Container.fromFactoryProvider` (complexity 11 → ≤10) via Extract Method: introduced `tryResolveSyncDeps` private helper returning a discriminated union for sync/async dispatch.
|
|
16
|
-
- Removed redundant `export` on `MODULE_METADATA_KEY` (internal-only — never part of public surface).
|
|
17
|
-
-
|
|
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.
|
|
18
65
|
|
|
19
66
|
## [0.1.0-next.0] - 2026-05-29
|
|
20
67
|
|
|
@@ -25,15 +72,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
25
72
|
- 5 decorators: `@Injectable()`, `@Inject(token)`, `@Optional()`, `@Module({...})` — NestJS-compatible API.
|
|
26
73
|
- 4 provider types: `useClass`, `useFactory`, `useValue`, `useExisting`.
|
|
27
74
|
- 3 lifecycle scopes: `SINGLETON` (default), `TRANSIENT`, `REQUEST` (via `AsyncLocalStorage`).
|
|
28
|
-
- Cycle detection at resolve-time
|
|
29
|
-
- Cache cleanup on Promise rejection
|
|
30
|
-
- `runInRequest()` try/finally guarantees REQUEST instances are disposed even on callback throw
|
|
31
|
-
- `validateClassProvider()` centralized validation — both declarative `providers: []` and imperative `register()` reject undecorated classes
|
|
32
|
-
- Container freezes after first `resolve()`; `allowDynamicRegistration: true` opt-out for tests
|
|
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.
|
|
33
80
|
- Module loading with cycle detection (DFS), export validation at register-time, BFS-style transitive provider import.
|
|
34
81
|
- Typed errors: `TokenNotFoundError`, `CyclicDependencyError`, `AsyncProviderInSyncResolveError`, `ScopeViolationError`, `MissingInjectableError`, `ContainerDisposedError`, `ContainerFrozenError`, `InvalidModuleError`, `InvalidExportError`, `CyclicModuleImportError`, `ReflectMetadataMissingError`.
|
|
35
82
|
- Disposal lifecycle: `dispose()` calls `Symbol.asyncDispose` (preferred) or `dispose()` on each instance in reverse construction order; aggregates errors via `AggregateError`.
|
|
36
|
-
- Foundation for `@theokit/orm`
|
|
83
|
+
- Foundation for `@theokit/orm` and `@theokit/http`. Agent-first integration ships as the separate `@theokit/di-agent` package, with zero coupling.
|
|
37
84
|
|
|
38
85
|
### Bundle / Coverage
|
|
39
86
|
|
|
@@ -41,6 +88,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
41
88
|
- Bundle: ESM 11.55 KB / CJS 11.32 KB (gzipped est.).
|
|
42
89
|
- Dual ESM + CJS, target Node 22.12+, dts emitted.
|
|
43
90
|
|
|
44
|
-
### Polyglot strategy
|
|
91
|
+
### Polyglot strategy
|
|
45
92
|
|
|
46
|
-
`@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` (
|
|
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
|
|
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
|
|
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:**
|
|
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
|
|
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");
|
|
@@ -190,7 +201,47 @@ var METADATA_KEYS = {
|
|
|
190
201
|
/** Set<number> from `@Optional()` parameter decorators. */
|
|
191
202
|
OPTIONAL_FLAGS: "usetheo:di:optional",
|
|
192
203
|
/** TS-emitted constructor parameter types (requires `emitDecoratorMetadata`). */
|
|
193
|
-
DESIGN_PARAMTYPES: "design:paramtypes"
|
|
204
|
+
DESIGN_PARAMTYPES: "design:paramtypes",
|
|
205
|
+
/** Map<number, string> from `@Qualifier(name)` parameter decorators. */
|
|
206
|
+
QUALIFIER_NAMES: "usetheo:di:qualifier-names",
|
|
207
|
+
/** boolean from `@Primary` class decorator. */
|
|
208
|
+
PRIMARY: "usetheo:di:primary",
|
|
209
|
+
/** string | symbol from `@PostConstruct` method decorator. */
|
|
210
|
+
POST_CONSTRUCT: "usetheo:di:post-construct",
|
|
211
|
+
/** string | symbol from `@PreDestroy` method decorator. */
|
|
212
|
+
PRE_DESTROY: "usetheo:di:pre-destroy",
|
|
213
|
+
/** Map<string|symbol, SandboxOptions> from `@UseSandbox()` property decorator. */
|
|
214
|
+
SANDBOX: "usetheo:di:sandbox",
|
|
215
|
+
/** Map<string|symbol, SubAgentSpec> from `@SubAgent()` property decorator. */
|
|
216
|
+
SUBAGENT: "usetheo:di:subagent",
|
|
217
|
+
/** Map<string|symbol, SquadMetadata> from `@Squad()` property decorator. */
|
|
218
|
+
SQUAD: "usetheo:di:squad",
|
|
219
|
+
/** Map<string|symbol, StepMetadata> from `@Step()` method decorator. */
|
|
220
|
+
STEP: "usetheo:di:step",
|
|
221
|
+
/** Map<string|symbol, HitlMetadata> from `@Hitl()` method decorator. */
|
|
222
|
+
HITL: "usetheo:di:hitl",
|
|
223
|
+
/** AutoSummarizeConfig from `@AutoSummarize()` class decorator. */
|
|
224
|
+
AUTO_SUMMARIZE: "usetheo:di:auto-summarize",
|
|
225
|
+
/** Map<string|symbol, ToolOptions> from `@Tool()` property decorator. */
|
|
226
|
+
TOOL: "usetheo:di:tool",
|
|
227
|
+
/** WorkflowOptions from `@Workflow()` class decorator. */
|
|
228
|
+
WORKFLOW: "usetheo:di:workflow",
|
|
229
|
+
/** EvalOptions from `@Eval()` class decorator. */
|
|
230
|
+
EVAL: "usetheo:di:eval",
|
|
231
|
+
/** Map<string|symbol, CronMetadata> from `@Cron()` method decorator. */
|
|
232
|
+
CRON: "usetheo:di:cron",
|
|
233
|
+
/** Map<string|symbol, SubscriptionOptions> from `@Subscription()` property decorator. */
|
|
234
|
+
SUBSCRIPTION: "usetheo:di:subscription",
|
|
235
|
+
/** AuthOptions from `@Auth()` class decorator. */
|
|
236
|
+
AUTH: "usetheo:di:auth",
|
|
237
|
+
/** Map<string|symbol, RetrieverOptions> from `@Retriever()` property decorator. */
|
|
238
|
+
RETRIEVER: "usetheo:di:retriever",
|
|
239
|
+
/** Map<string|symbol, RerankerOptions> from `@Reranker()` property decorator. */
|
|
240
|
+
RERANKER: "usetheo:di:reranker",
|
|
241
|
+
/** Map<string|symbol, TextSplitterOptions> from `@TextSplitter()` property decorator. */
|
|
242
|
+
TEXT_SPLITTER: "usetheo:di:text-splitter",
|
|
243
|
+
/** Map<string|symbol, MemoryScopeOptions> from `@MemoryScopeDecorator()` property decorator. */
|
|
244
|
+
MEMORY_SCOPE: "usetheo:di:memory-scope"
|
|
194
245
|
};
|
|
195
246
|
function hasReflectMetadata() {
|
|
196
247
|
return typeof Reflect !== "undefined" && typeof Reflect.getMetadata === "function";
|
|
@@ -229,6 +280,21 @@ function isInjectable(target) {
|
|
|
229
280
|
return readInjectableMetadata(target) !== void 0;
|
|
230
281
|
}
|
|
231
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");
|
|
232
298
|
var PRIMITIVE_WRAPPERS = /* @__PURE__ */ new Set([
|
|
233
299
|
Number,
|
|
234
300
|
String,
|
|
@@ -359,6 +425,11 @@ var Scope = {
|
|
|
359
425
|
};
|
|
360
426
|
|
|
361
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");
|
|
362
433
|
var Container = class {
|
|
363
434
|
static {
|
|
364
435
|
__name(this, "Container");
|
|
@@ -384,7 +455,7 @@ var Container = class {
|
|
|
384
455
|
* - A full Provider (useClass / useFactory / useValue / useExisting)
|
|
385
456
|
* - A bare class (shorthand expands to ClassProvider { provide: X, useClass: X })
|
|
386
457
|
*
|
|
387
|
-
*
|
|
458
|
+
* ClassProvider validation runs via `validateClassProvider()`
|
|
388
459
|
* regardless of which API path was used.
|
|
389
460
|
*/
|
|
390
461
|
register(providerOrClass) {
|
|
@@ -404,9 +475,9 @@ var Container = class {
|
|
|
404
475
|
* modules. Walks imports BFS, registers every provider, validates
|
|
405
476
|
* exports.
|
|
406
477
|
*
|
|
407
|
-
*
|
|
408
|
-
*
|
|
409
|
-
*
|
|
478
|
+
* An undecorated class throws `InvalidModuleError`. Respects the
|
|
479
|
+
* freeze-after-first-resolve guarantee — each child `register()` checks
|
|
480
|
+
* `assertNotFrozen`.
|
|
410
481
|
*/
|
|
411
482
|
registerModule(moduleClass) {
|
|
412
483
|
this.assertNotDisposed();
|
|
@@ -443,7 +514,7 @@ var Container = class {
|
|
|
443
514
|
* providers resolved within `callback` (or any async continuation) share
|
|
444
515
|
* a single per-request cache.
|
|
445
516
|
*
|
|
446
|
-
*
|
|
517
|
+
* try/finally guarantees REQUEST-scoped instances are disposed
|
|
447
518
|
* even if the callback throws.
|
|
448
519
|
*/
|
|
449
520
|
async runInRequest(callback) {
|
|
@@ -461,7 +532,7 @@ var Container = class {
|
|
|
461
532
|
/**
|
|
462
533
|
* Debug helper — returns a snapshot of the dependency graph.
|
|
463
534
|
*
|
|
464
|
-
*
|
|
535
|
+
* Detects cycles in unused providers too (resolve-time
|
|
465
536
|
* detection only fires for resolves that actually traverse the cycle).
|
|
466
537
|
* Use this proactively in tests / dev mode to surface latent cycles.
|
|
467
538
|
*/
|
|
@@ -562,7 +633,7 @@ var Container = class {
|
|
|
562
633
|
}
|
|
563
634
|
}
|
|
564
635
|
/**
|
|
565
|
-
*
|
|
636
|
+
* Shared by both declarative providers: [] AND imperative
|
|
566
637
|
* register() — every class provider must have @Injectable().
|
|
567
638
|
*/
|
|
568
639
|
validateClassProvider(provider) {
|
|
@@ -577,7 +648,7 @@ var Container = class {
|
|
|
577
648
|
if (this.disposed) throw new ContainerDisposedError();
|
|
578
649
|
}
|
|
579
650
|
/**
|
|
580
|
-
*
|
|
651
|
+
* The container freezes on first resolve. Late registrations
|
|
581
652
|
* require explicit `allowDynamicRegistration: true` (testing escape hatch).
|
|
582
653
|
*/
|
|
583
654
|
assertNotFrozen(token) {
|
|
@@ -608,7 +679,8 @@ var Container = class {
|
|
|
608
679
|
token: provider.provide,
|
|
609
680
|
scope,
|
|
610
681
|
factory: /* @__PURE__ */ __name((ctx) => this.constructClassWithAsyncFallback(target, ctx), "factory"),
|
|
611
|
-
classTarget: target
|
|
682
|
+
classTarget: target,
|
|
683
|
+
containerOwned: true
|
|
612
684
|
};
|
|
613
685
|
}
|
|
614
686
|
fromFactoryProvider(provider) {
|
|
@@ -623,7 +695,8 @@ var Container = class {
|
|
|
623
695
|
}
|
|
624
696
|
return Promise.all(injectTokens.map((dep) => ctx.resolveAsync(dep))).then((asyncArgs) => provider.useFactory(...asyncArgs));
|
|
625
697
|
}, "factory"),
|
|
626
|
-
injectTokens
|
|
698
|
+
injectTokens,
|
|
699
|
+
containerOwned: true
|
|
627
700
|
};
|
|
628
701
|
}
|
|
629
702
|
/**
|
|
@@ -654,7 +727,8 @@ var Container = class {
|
|
|
654
727
|
return {
|
|
655
728
|
token: provider.provide,
|
|
656
729
|
scope: Scope.SINGLETON,
|
|
657
|
-
factory: /* @__PURE__ */ __name(() => provider.useValue, "factory")
|
|
730
|
+
factory: /* @__PURE__ */ __name(() => provider.useValue, "factory"),
|
|
731
|
+
containerOwned: false
|
|
658
732
|
};
|
|
659
733
|
}
|
|
660
734
|
fromExistingProvider(provider) {
|
|
@@ -662,15 +736,16 @@ var Container = class {
|
|
|
662
736
|
token: provider.provide,
|
|
663
737
|
scope: Scope.SINGLETON,
|
|
664
738
|
factory: /* @__PURE__ */ __name((ctx) => ctx.resolve(provider.useExisting), "factory"),
|
|
665
|
-
aliasTarget: provider.useExisting
|
|
739
|
+
aliasTarget: provider.useExisting,
|
|
740
|
+
containerOwned: false
|
|
666
741
|
};
|
|
667
742
|
}
|
|
668
743
|
/**
|
|
669
744
|
* Resolve constructor params + build instance. Tries sync first; if any
|
|
670
745
|
* dep is async, falls back to awaiting via `resolveAsync`.
|
|
671
746
|
*
|
|
672
|
-
* Refactored via Extract Method
|
|
673
|
-
* - validateMetadata:
|
|
747
|
+
* Refactored via Extract Method: orchestrates 3 helpers:
|
|
748
|
+
* - validateMetadata: detect emitDecoratorMetadata off
|
|
674
749
|
* - tryResolveSync: sync resolution loop with AsyncProvider bailout
|
|
675
750
|
* - resolveAllAsync: Promise.all fallback when any dep is async
|
|
676
751
|
*/
|
|
@@ -684,12 +759,13 @@ var Container = class {
|
|
|
684
759
|
this.validateMetadata(target, paramTypes);
|
|
685
760
|
const syncResult = this.tryResolveSync(target, paramTypes, injectTokens, optionalFlags, ctx);
|
|
686
761
|
if ("args" in syncResult) {
|
|
687
|
-
|
|
762
|
+
const instance = new target(...syncResult.args);
|
|
763
|
+
return isAsyncContext(ctx) ? runPostConstructAsync(target, instance) : runPostConstructSync(target, instance);
|
|
688
764
|
}
|
|
689
|
-
return this.resolveAllAsync(target, paramTypes, injectTokens, optionalFlags, ctx);
|
|
765
|
+
return this.resolveAllAsync(target, paramTypes, injectTokens, optionalFlags, ctx).then((instance) => runPostConstructAsync(target, instance));
|
|
690
766
|
}
|
|
691
767
|
/**
|
|
692
|
-
*
|
|
768
|
+
* Detection: zero paramTypes for a class that declares a non-empty
|
|
693
769
|
* constructor strongly suggests emitDecoratorMetadata is off.
|
|
694
770
|
*/
|
|
695
771
|
validateMetadata(target, paramTypes) {
|
|
@@ -796,14 +872,14 @@ var Container = class {
|
|
|
796
872
|
this.storeInCache(token, value, registration.scope);
|
|
797
873
|
value.then((resolved) => {
|
|
798
874
|
this.storeInCache(token, resolved, registration.scope);
|
|
799
|
-
this.trackInstance(resolved, registration
|
|
875
|
+
this.trackInstance(resolved, registration);
|
|
800
876
|
}, () => {
|
|
801
877
|
this.deleteFromCache(token, registration.scope);
|
|
802
878
|
});
|
|
803
879
|
throw new AsyncProviderInSyncResolveError(token);
|
|
804
880
|
}
|
|
805
881
|
this.storeInCache(token, value, registration.scope);
|
|
806
|
-
this.trackInstance(value, registration
|
|
882
|
+
this.trackInstance(value, registration);
|
|
807
883
|
return value;
|
|
808
884
|
}
|
|
809
885
|
// ─────────────────────────────────────────────────────────────────────
|
|
@@ -836,14 +912,14 @@ var Container = class {
|
|
|
836
912
|
this.storeInCache(token, result, registration.scope);
|
|
837
913
|
result.then((value) => {
|
|
838
914
|
this.storeInCache(token, value, registration.scope);
|
|
839
|
-
this.trackInstance(value, registration
|
|
915
|
+
this.trackInstance(value, registration);
|
|
840
916
|
}, () => {
|
|
841
917
|
this.deleteFromCache(token, registration.scope);
|
|
842
918
|
});
|
|
843
919
|
return result;
|
|
844
920
|
}
|
|
845
921
|
this.storeInCache(token, result, registration.scope);
|
|
846
|
-
this.trackInstance(result, registration
|
|
922
|
+
this.trackInstance(result, registration);
|
|
847
923
|
return result;
|
|
848
924
|
}
|
|
849
925
|
// ─────────────────────────────────────────────────────────────────────
|
|
@@ -878,8 +954,18 @@ var Container = class {
|
|
|
878
954
|
store?.cache.delete(token);
|
|
879
955
|
}
|
|
880
956
|
}
|
|
881
|
-
|
|
882
|
-
|
|
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;
|
|
883
969
|
if (scope === Scope.SINGLETON) {
|
|
884
970
|
this.singletonInstances.push(value);
|
|
885
971
|
return;
|
|
@@ -905,11 +991,14 @@ var Container = class {
|
|
|
905
991
|
};
|
|
906
992
|
}
|
|
907
993
|
createContextAsync(path) {
|
|
908
|
-
|
|
994
|
+
const ctx = {
|
|
909
995
|
path,
|
|
910
996
|
resolve: /* @__PURE__ */ __name((t) => this.resolveInContext(t, this.createContext(path)), "resolve"),
|
|
911
997
|
resolveAsync: /* @__PURE__ */ __name((t) => this.resolveAsyncInContext(t, this.createContextAsync(path)), "resolveAsync")
|
|
912
998
|
};
|
|
999
|
+
return Object.assign(ctx, {
|
|
1000
|
+
[ASYNC_CONTEXT]: true
|
|
1001
|
+
});
|
|
913
1002
|
}
|
|
914
1003
|
// ─────────────────────────────────────────────────────────────────────
|
|
915
1004
|
// Internal: disposal
|
|
@@ -920,10 +1009,11 @@ var Container = class {
|
|
|
920
1009
|
const instance = instances[i];
|
|
921
1010
|
if (instance === void 0) continue;
|
|
922
1011
|
try {
|
|
1012
|
+
await callPreDestroy(instance);
|
|
923
1013
|
const asAsync = instance[Symbol.asyncDispose];
|
|
924
1014
|
if (typeof asAsync === "function") {
|
|
925
1015
|
await asAsync.call(instance);
|
|
926
|
-
} else {
|
|
1016
|
+
} else if (isDisposable(instance)) {
|
|
927
1017
|
await instance.dispose();
|
|
928
1018
|
}
|
|
929
1019
|
} catch (err) {
|
|
@@ -944,6 +1034,49 @@ function isDisposable(value) {
|
|
|
944
1034
|
return false;
|
|
945
1035
|
}
|
|
946
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");
|
|
947
1080
|
|
|
948
1081
|
// src/decorators/inject.ts
|
|
949
1082
|
function Inject(token) {
|
|
@@ -967,6 +1100,16 @@ function Injectable(options = {}) {
|
|
|
967
1100
|
}
|
|
968
1101
|
__name(Injectable, "Injectable");
|
|
969
1102
|
|
|
1103
|
+
// src/decorators/lifecycle.ts
|
|
1104
|
+
function PostConstruct(target, propertyKey) {
|
|
1105
|
+
Reflect.defineMetadata(METADATA_KEYS.POST_CONSTRUCT, propertyKey, target.constructor);
|
|
1106
|
+
}
|
|
1107
|
+
__name(PostConstruct, "PostConstruct");
|
|
1108
|
+
function PreDestroy(target, propertyKey) {
|
|
1109
|
+
Reflect.defineMetadata(METADATA_KEYS.PRE_DESTROY, propertyKey, target.constructor);
|
|
1110
|
+
}
|
|
1111
|
+
__name(PreDestroy, "PreDestroy");
|
|
1112
|
+
|
|
970
1113
|
// src/decorators/optional.ts
|
|
971
1114
|
function Optional() {
|
|
972
1115
|
return (target, _propertyKey, parameterIndex) => {
|
|
@@ -978,6 +1121,23 @@ function Optional() {
|
|
|
978
1121
|
}
|
|
979
1122
|
__name(Optional, "Optional");
|
|
980
1123
|
|
|
1124
|
+
// src/decorators/primary.ts
|
|
1125
|
+
function Primary(target) {
|
|
1126
|
+
Reflect.defineMetadata(METADATA_KEYS.PRIMARY, true, target);
|
|
1127
|
+
}
|
|
1128
|
+
__name(Primary, "Primary");
|
|
1129
|
+
|
|
1130
|
+
// src/decorators/qualifier.ts
|
|
1131
|
+
function Qualifier(name) {
|
|
1132
|
+
return (target, _propertyKey, parameterIndex) => {
|
|
1133
|
+
const existing = Reflect.getMetadata(METADATA_KEYS.QUALIFIER_NAMES, target) ?? /* @__PURE__ */ new Map();
|
|
1134
|
+
existing.set(parameterIndex, name);
|
|
1135
|
+
Reflect.defineMetadata(METADATA_KEYS.QUALIFIER_NAMES, existing, target);
|
|
1136
|
+
};
|
|
1137
|
+
}
|
|
1138
|
+
__name(Qualifier, "Qualifier");
|
|
1139
|
+
|
|
1140
|
+
exports.AsyncPostConstructInSyncResolveError = AsyncPostConstructInSyncResolveError;
|
|
981
1141
|
exports.AsyncProviderInSyncResolveError = AsyncProviderInSyncResolveError;
|
|
982
1142
|
exports.Container = Container;
|
|
983
1143
|
exports.ContainerDisposedError = ContainerDisposedError;
|
|
@@ -988,9 +1148,14 @@ exports.Inject = Inject;
|
|
|
988
1148
|
exports.Injectable = Injectable;
|
|
989
1149
|
exports.InvalidExportError = InvalidExportError;
|
|
990
1150
|
exports.InvalidModuleError = InvalidModuleError;
|
|
1151
|
+
exports.METADATA_KEYS = METADATA_KEYS;
|
|
991
1152
|
exports.MissingInjectableError = MissingInjectableError;
|
|
992
1153
|
exports.Module = Module;
|
|
993
1154
|
exports.Optional = Optional;
|
|
1155
|
+
exports.PostConstruct = PostConstruct;
|
|
1156
|
+
exports.PreDestroy = PreDestroy;
|
|
1157
|
+
exports.Primary = Primary;
|
|
1158
|
+
exports.Qualifier = Qualifier;
|
|
994
1159
|
exports.ReflectMetadataMissingError = ReflectMetadataMissingError;
|
|
995
1160
|
exports.Scope = Scope;
|
|
996
1161
|
exports.ScopeViolationError = ScopeViolationError;
|