@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.
@@ -0,0 +1,506 @@
1
+ /**
2
+ * Public type contract for `@theokit/di`. All consumer-facing types live
3
+ * here; internal types live in `src/internal/`.
4
+ */
5
+ /**
6
+ * Constructor of a class — what TypeScript emits for `class X { ... }`.
7
+ * Used as a Class-token (per ADR D2).
8
+ */
9
+ type ClassConstructor<T = unknown> = new (...args: any[]) => T;
10
+ /**
11
+ * Token: anything that identifies a dependency in the container.
12
+ *
13
+ * Per ADR D2: Class primary (auto-resolution via `reflect-metadata`),
14
+ * String fallback (for primitives / interfaces). Symbol explicitly NOT
15
+ * supported in v1 (deferred to v2 if real demand surfaces).
16
+ */
17
+ type Token<T = unknown> = ClassConstructor<T> | string;
18
+ /**
19
+ * Lifecycle scope (per ADR D5). The container honors three modes:
20
+ *
21
+ * - `SINGLETON` — single instance shared across the entire container
22
+ * - `TRANSIENT` — fresh instance per resolve
23
+ * - `REQUEST` — single instance per `container.runInRequest(...)` boundary
24
+ * (uses Node's `AsyncLocalStorage`)
25
+ */
26
+ declare const Scope: {
27
+ readonly SINGLETON: "singleton";
28
+ readonly TRANSIENT: "transient";
29
+ readonly REQUEST: "request";
30
+ };
31
+ type Scope = (typeof Scope)[keyof typeof Scope];
32
+ /**
33
+ * Tells the container HOW to materialize a value for a token.
34
+ * Exactly one of `useClass | useFactory | useValue | useExisting` MUST be set.
35
+ */
36
+ type Provider<T = unknown> = ClassProvider<T> | FactoryProvider<T> | ValueProvider<T> | ExistingProvider<T>;
37
+ interface ClassProvider<T = unknown> {
38
+ provide: Token<T>;
39
+ useClass: ClassConstructor<T>;
40
+ scope?: Scope;
41
+ }
42
+ interface FactoryProvider<T = unknown> {
43
+ provide: Token<T>;
44
+ useFactory: (...deps: any[]) => T | Promise<T>;
45
+ inject?: ReadonlyArray<Token>;
46
+ scope?: Scope;
47
+ }
48
+ interface ValueProvider<T = unknown> {
49
+ provide: Token<T>;
50
+ useValue: T;
51
+ }
52
+ interface ExistingProvider<T = unknown> {
53
+ provide: Token<T>;
54
+ useExisting: Token<T>;
55
+ }
56
+ /**
57
+ * Resolution context passed to factories. Mostly internal but exposed so
58
+ * factories can `inject` siblings without hard-coding container references.
59
+ */
60
+ interface ResolutionContext {
61
+ /** The current resolution path (used for cycle detection). */
62
+ readonly path: ReadonlyArray<Token>;
63
+ /** Synchronously resolve a token within the same context. */
64
+ resolve<U>(token: Token<U>): U;
65
+ /** Asynchronously resolve a token within the same context. */
66
+ resolveAsync<U>(token: Token<U>): Promise<U>;
67
+ }
68
+ /**
69
+ * Options passed to `new Container({...})`.
70
+ */
71
+ interface ContainerOptions {
72
+ /**
73
+ * Declarative providers seed (NestJS-style). Same effect as calling
74
+ * `container.register(provider)` for each entry.
75
+ */
76
+ providers?: ReadonlyArray<Provider | ClassConstructor>;
77
+ /**
78
+ * When `true`, allows `register()` / `registerModule()` calls AFTER
79
+ * the first `resolve()`. Default `false` — fail-fast on misuse.
80
+ *
81
+ * v1.2 EC-R2-5: containers freeze after first resolve to prevent
82
+ * subtle bugs where a singleton is constructed with one set of
83
+ * registrations and a different set is added later.
84
+ */
85
+ allowDynamicRegistration?: boolean;
86
+ }
87
+ /**
88
+ * Anything that implements a `dispose()` method participates in lifecycle
89
+ * cleanup when the container or REQUEST scope ends.
90
+ */
91
+ interface Disposable {
92
+ dispose(): void | Promise<void>;
93
+ }
94
+ /**
95
+ * `analyze()` debug return shape (per ADR D7).
96
+ */
97
+ interface DependencyGraph {
98
+ nodes: ReadonlyArray<{
99
+ token: Token;
100
+ scope: Scope;
101
+ isAsync: boolean;
102
+ }>;
103
+ edges: ReadonlyArray<{
104
+ from: Token;
105
+ to: Token;
106
+ }>;
107
+ cycles: ReadonlyArray<ReadonlyArray<Token>>;
108
+ }
109
+
110
+ /**
111
+ * Dependency-graph helpers — used by `container.analyze()` for debug + by
112
+ * the registration phase (future) for proactive cycle detection.
113
+ *
114
+ * Per v1.2 EC-11: iterative DFS, NOT recursive, so large graphs (100+ nodes)
115
+ * with multiple cycles don't blow the call stack.
116
+ */
117
+
118
+ interface GraphNode {
119
+ readonly token: Token;
120
+ readonly scope: Scope;
121
+ readonly isAsync: boolean;
122
+ }
123
+ interface GraphEdge {
124
+ readonly from: Token;
125
+ readonly to: Token;
126
+ }
127
+
128
+ /**
129
+ * Container — the DI runtime. Implements:
130
+ * - 3 scopes (SINGLETON / TRANSIENT / REQUEST via AsyncLocalStorage)
131
+ * - 4 provider types (useClass / useFactory / useValue / useExisting)
132
+ * - Cycle detection at resolve-time (path tracking)
133
+ * - Promise-lock REQUEST cache (v1.1 EC-2) with cycle-first ordering
134
+ * (v1.2 EC-R2-1) and reject cleanup (v1.2 EC-R2-2)
135
+ * - Disposal lifecycle (T3.3) + freeze on first resolve (v1.2 EC-R2-5)
136
+ */
137
+
138
+ /**
139
+ * Lightweight DI container. See `README.md` for usage examples.
140
+ */
141
+ declare class Container {
142
+ private readonly registrations;
143
+ private readonly singletonCache;
144
+ private readonly singletonInstances;
145
+ private readonly requestStorage;
146
+ private readonly options;
147
+ private hasResolved;
148
+ private disposed;
149
+ constructor(options?: ContainerOptions);
150
+ /**
151
+ * Register a provider. Accepts:
152
+ * - A full Provider (useClass / useFactory / useValue / useExisting)
153
+ * - A bare class (shorthand expands to ClassProvider { provide: X, useClass: X })
154
+ *
155
+ * Per v1.1 EC-1, ClassProvider validation runs via `validateClassProvider()`
156
+ * regardless of which API path was used.
157
+ */
158
+ register<T>(providerOrClass: Provider<T> | ClassConstructor<T>): void;
159
+ /**
160
+ * Load a `@Module()`-decorated class plus all transitively imported
161
+ * modules. Walks imports BFS, registers every provider, validates
162
+ * exports.
163
+ *
164
+ * Per v1.1 EC-4: undecorated class throws `InvalidModuleError`.
165
+ * Per v1.2 EC-R2-5: respects the freeze-after-first-resolve guarantee
166
+ * (each child `register()` checks `assertNotFrozen`).
167
+ */
168
+ registerModule(moduleClass: ClassConstructor): void;
169
+ /**
170
+ * True if the container has a registration for `token`.
171
+ */
172
+ has(token: Token): boolean;
173
+ /**
174
+ * Synchronously resolve a token. Throws `AsyncProviderInSyncResolveError`
175
+ * if the resolution chain contains an async provider.
176
+ */
177
+ resolve<T>(token: Token<T>): T;
178
+ /**
179
+ * Asynchronously resolve a token. Always returns a Promise even for sync
180
+ * providers (for API uniformity).
181
+ */
182
+ resolveAsync<T>(token: Token<T>): Promise<T>;
183
+ /**
184
+ * Run `callback` inside a fresh REQUEST scope. All REQUEST-scoped
185
+ * providers resolved within `callback` (or any async continuation) share
186
+ * a single per-request cache.
187
+ *
188
+ * v1.1 EC-3: try/finally guarantees REQUEST-scoped instances are disposed
189
+ * even if the callback throws.
190
+ */
191
+ runInRequest<R>(callback: () => R | Promise<R>): Promise<R>;
192
+ /**
193
+ * Debug helper — returns a snapshot of the dependency graph.
194
+ *
195
+ * Per ADR D7: detects cycles in unused providers too (resolve-time
196
+ * detection only fires for resolves that actually traverse the cycle).
197
+ * Use this proactively in tests / dev mode to surface latent cycles.
198
+ */
199
+ analyze(): {
200
+ nodes: GraphNode[];
201
+ edges: GraphEdge[];
202
+ cycles: ReadonlyArray<ReadonlyArray<Token>>;
203
+ };
204
+ private getDirectDependencies;
205
+ /**
206
+ * Dispose the container — runs `dispose()` (or `Symbol.asyncDispose`) on
207
+ * every singleton instance in reverse construction order. Idempotent.
208
+ * Subsequent `resolve()` throws `ContainerDisposedError`.
209
+ */
210
+ dispose(): Promise<void>;
211
+ /**
212
+ * Symbol.asyncDispose alias — enables `await using container = new Container(...)`.
213
+ */
214
+ [Symbol.asyncDispose](): Promise<void>;
215
+ private normalizeShorthand;
216
+ private tokenOf;
217
+ private validateProvider;
218
+ /**
219
+ * v1.1 EC-1: shared by both declarative providers: [] AND imperative
220
+ * register() — every class provider must have @Injectable().
221
+ */
222
+ private validateClassProvider;
223
+ private assertNotDisposed;
224
+ /**
225
+ * v1.2 EC-R2-5: container freezes on first resolve. Late registrations
226
+ * require explicit `allowDynamicRegistration: true` (testing escape hatch).
227
+ */
228
+ private assertNotFrozen;
229
+ private normalizeProvider;
230
+ private fromClassProvider;
231
+ private fromFactoryProvider;
232
+ /**
233
+ * Attempt sync resolution of a flat dep list (factory provider shape).
234
+ * Returns `{ args }` on success or `{ needsAsync: true }` if any dep
235
+ * raised AsyncProviderInSyncResolveError. Throws for any other error.
236
+ * Extracted via D422 to keep fromFactoryProvider.factory below complexity 10.
237
+ */
238
+ private tryResolveSyncDeps;
239
+ private fromValueProvider;
240
+ private fromExistingProvider;
241
+ /**
242
+ * Resolve constructor params + build instance. Tries sync first; if any
243
+ * dep is async, falls back to awaiting via `resolveAsync`.
244
+ *
245
+ * Refactored via Extract Method (ADR D422): orchestrates 3 helpers:
246
+ * - validateMetadata: EC-12 detect emitDecoratorMetadata off
247
+ * - tryResolveSync: sync resolution loop with AsyncProvider bailout
248
+ * - resolveAllAsync: Promise.all fallback when any dep is async
249
+ */
250
+ private constructClassWithAsyncFallback;
251
+ /**
252
+ * EC-12 detection: zero paramTypes for a class that declares a non-empty
253
+ * constructor strongly suggests emitDecoratorMetadata is off.
254
+ */
255
+ private validateMetadata;
256
+ /**
257
+ * Handle a single primitive-marker param (e.g. `param: string` without
258
+ * explicit @Inject). Returns `undefined` for optional, throws for required.
259
+ * Extracted to keep tryResolveSync below the complexity-10 cap (D422).
260
+ */
261
+ private handlePrimitiveParam;
262
+ /**
263
+ * Attempt sync resolution. Returns `{ args }` on success, `{ needsAsync: true }`
264
+ * if any dep raised AsyncProviderInSyncResolveError. Throws for any other error.
265
+ */
266
+ private tryResolveSync;
267
+ /**
268
+ * Async fallback: resolve every dep via resolveAsync, then construct.
269
+ * Called when tryResolveSync returned `{ needsAsync: true }`.
270
+ */
271
+ private resolveAllAsync;
272
+ private resolveOrOptional;
273
+ private resolveInContext;
274
+ private resolveAsyncInContext;
275
+ private lookupCache;
276
+ private storeInCache;
277
+ private deleteFromCache;
278
+ private trackInstance;
279
+ private assertRequestActive;
280
+ private createContext;
281
+ private createContextAsync;
282
+ private disposeInstances;
283
+ }
284
+
285
+ /**
286
+ * Overrides the default class-token resolution for a constructor parameter.
287
+ * Required when the parameter type is an interface (TS emits `Object`) or
288
+ * a string token (e.g., `'DATABASE_URL'`).
289
+ *
290
+ * @example
291
+ * class GreeterService {
292
+ * constructor(
293
+ * @Inject('DATABASE_URL') readonly dbUrl: string,
294
+ * @Inject(LoggerInterface) readonly logger: LoggerInterface,
295
+ * ) {}
296
+ * }
297
+ */
298
+ declare function Inject(token: Token): ParameterDecorator;
299
+
300
+ /**
301
+ * Options accepted by `@Injectable({...})`.
302
+ */
303
+ interface InjectableOptions {
304
+ scope?: Scope;
305
+ }
306
+ /**
307
+ * Marks a class as DI-managed. Without this decorator, the container
308
+ * rejects the class at registration time (per v1.1 EC-1).
309
+ *
310
+ * @example
311
+ * @Injectable()
312
+ * class UserService { constructor(private db: DbConnection) {} }
313
+ *
314
+ * @Injectable({ scope: Scope.REQUEST })
315
+ * class RequestLogger { ... }
316
+ */
317
+ declare function Injectable(options?: InjectableOptions): ClassDecorator;
318
+
319
+ /**
320
+ * Module declaration shape accepted by `@Module({...})`.
321
+ *
322
+ * - `providers` — providers registered into the container when this module
323
+ * is loaded. Bare classes are expanded to ClassProvider shorthand.
324
+ * - `imports` — other `@Module()` classes whose exported providers are
325
+ * visible to this module.
326
+ * - `exports` — tokens from this module's `providers` that should be
327
+ * visible to outer modules that `import` this one.
328
+ */
329
+ interface ModuleMetadata {
330
+ providers?: ReadonlyArray<Provider | ClassConstructor>;
331
+ imports?: ReadonlyArray<ClassConstructor>;
332
+ exports?: ReadonlyArray<Token>;
333
+ }
334
+ /**
335
+ * Mark a class as a DI module. The class itself never gets instantiated —
336
+ * the decorator just attaches metadata that `Container.registerModule()`
337
+ * reads.
338
+ *
339
+ * @example
340
+ * @Module({
341
+ * providers: [UserService, { provide: 'DB_URL', useValue: process.env.DB }],
342
+ * imports: [LoggingModule],
343
+ * exports: [UserService],
344
+ * })
345
+ * class UserModule {}
346
+ */
347
+ declare function Module(metadata: ModuleMetadata): ClassDecorator;
348
+
349
+ /**
350
+ * Marks a constructor parameter as optional. If the corresponding
351
+ * dependency is not registered, the parameter receives `undefined`
352
+ * instead of throwing `TokenNotFoundError`.
353
+ *
354
+ * `@Optional()` ONLY swallows `TokenNotFoundError` — other errors
355
+ * (e.g., factory throws, cyclic dependency) propagate.
356
+ *
357
+ * @example
358
+ * class GreeterService {
359
+ * constructor(@Optional() private logger?: Logger) {}
360
+ * }
361
+ */
362
+ declare function Optional(): ParameterDecorator;
363
+
364
+ /**
365
+ * Typed error classes. All container failure modes use these — never
366
+ * `throw new Error(...)` from production code (per system type-safety rule).
367
+ */
368
+
369
+ /**
370
+ * Renders a token to a human-readable string for error messages.
371
+ * - Class tokens: `MyService`
372
+ * - String tokens: `"DATABASE_URL"`
373
+ * - Anything else: `<unknown token>` (defensive — should never happen)
374
+ */
375
+ declare function describeToken(token: Token): string;
376
+ /**
377
+ * Thrown when `resolve()` / `resolveAsync()` is asked for a token that
378
+ * was never registered.
379
+ */
380
+ declare class TokenNotFoundError extends Error {
381
+ readonly token: Token;
382
+ readonly resolutionPath: ReadonlyArray<Token>;
383
+ readonly name: "TokenNotFoundError";
384
+ constructor(token: Token, resolutionPath: ReadonlyArray<Token>);
385
+ }
386
+ /**
387
+ * Thrown when a resolution chain contains a cycle (A → B → A).
388
+ * Per ADR D7: detected at resolve-time (not register-time).
389
+ *
390
+ * v1.2 EC-R2-1: cycle check happens BEFORE cache lookup in resolveAsync
391
+ * to prevent infinite Promise await deadlocks on async REQUEST-scoped
392
+ * cycles.
393
+ */
394
+ declare class CyclicDependencyError extends Error {
395
+ readonly cycle: ReadonlyArray<Token>;
396
+ readonly name: "CyclicDependencyError";
397
+ constructor(cycle: ReadonlyArray<Token>);
398
+ }
399
+ /**
400
+ * Thrown when sync `resolve()` is called on a chain that contains an
401
+ * async provider. The user must switch to `resolveAsync()`.
402
+ */
403
+ declare class AsyncProviderInSyncResolveError extends Error {
404
+ readonly token: Token;
405
+ readonly name: "AsyncProviderInSyncResolveError";
406
+ constructor(token: Token);
407
+ }
408
+ /**
409
+ * Thrown when a REQUEST-scoped provider is resolved outside of
410
+ * `container.runInRequest()`.
411
+ */
412
+ declare class ScopeViolationError extends Error {
413
+ readonly token: Token;
414
+ readonly name: "ScopeViolationError";
415
+ constructor(token: Token, message: string);
416
+ }
417
+ /**
418
+ * Thrown when a class is registered as a provider (via `useClass` or shorthand)
419
+ * but lacks the `@Injectable()` decorator. The decorator emits
420
+ * `design:paramtypes` metadata that the container needs to auto-resolve
421
+ * constructor parameters.
422
+ *
423
+ * v1.1 EC-1: validateClassProvider() is called by BOTH the declarative
424
+ * `providers: []` path AND the imperative `container.register()` path.
425
+ */
426
+ declare class MissingInjectableError extends Error {
427
+ readonly target: {
428
+ name?: string;
429
+ };
430
+ readonly name: "MissingInjectableError";
431
+ constructor(target: {
432
+ name?: string;
433
+ });
434
+ }
435
+ /**
436
+ * Thrown when `container.dispose()` is called and then a subsequent
437
+ * `resolve()` / `resolveAsync()` is attempted.
438
+ */
439
+ declare class ContainerDisposedError extends Error {
440
+ readonly name: "ContainerDisposedError";
441
+ constructor();
442
+ }
443
+ /**
444
+ * Thrown when `register()` or `registerModule()` is called AFTER the first
445
+ * `resolve()` has materialized a singleton. Per ADR D7 + EC-R2-5, the
446
+ * container freezes after first resolve unless
447
+ * `allowDynamicRegistration: true` was passed to the constructor.
448
+ */
449
+ declare class ContainerFrozenError extends Error {
450
+ readonly token: Token;
451
+ readonly name: "ContainerFrozenError";
452
+ constructor(token: Token);
453
+ }
454
+ /**
455
+ * Thrown when `reflect-metadata` is not loaded. The polyfill mutates the
456
+ * global `Reflect` object; without it, the container cannot read decorator
457
+ * metadata. Surfaces at first `resolve()` of a class provider — but the
458
+ * Container constructor also probes proactively.
459
+ */
460
+ declare class ReflectMetadataMissingError extends Error {
461
+ readonly name: "ReflectMetadataMissingError";
462
+ constructor();
463
+ }
464
+
465
+ /**
466
+ * Module-loader — walks @Module() classes in BFS order, registers their
467
+ * providers, validates imports + exports visibility, detects cyclic imports.
468
+ *
469
+ * Per ADR D4: modules are OPT-IN. Default usage is flat container.
470
+ * Per v1.1 EC-4: registerModule() rejects undecorated classes with
471
+ * InvalidModuleError pointing to the missing decorator.
472
+ */
473
+
474
+ /**
475
+ * Thrown when a class is passed to `Container.registerModule()` without
476
+ * the `@Module()` decorator (v1.1 EC-4 MUST FIX).
477
+ */
478
+ declare class InvalidModuleError extends Error {
479
+ readonly target: {
480
+ name?: string;
481
+ };
482
+ readonly name: "InvalidModuleError";
483
+ constructor(target: {
484
+ name?: string;
485
+ });
486
+ }
487
+ /**
488
+ * Thrown when a module declares an export for a token that isn't in its
489
+ * own `providers` (v1.1 EC-8 SHOULD TEST — pin register-time validation).
490
+ */
491
+ declare class InvalidExportError extends Error {
492
+ readonly moduleName: string;
493
+ readonly token: Token;
494
+ readonly name: "InvalidExportError";
495
+ constructor(moduleName: string, token: Token);
496
+ }
497
+ /**
498
+ * Thrown when module imports form a cycle (Module A imports B, B imports A).
499
+ */
500
+ declare class CyclicModuleImportError extends Error {
501
+ readonly cycle: ReadonlyArray<string>;
502
+ readonly name: "CyclicModuleImportError";
503
+ constructor(cycle: ReadonlyArray<string>);
504
+ }
505
+
506
+ export { AsyncProviderInSyncResolveError, type ClassConstructor, type ClassProvider, Container, ContainerDisposedError, ContainerFrozenError, type ContainerOptions, CyclicDependencyError, CyclicModuleImportError, type DependencyGraph, type Disposable, type ExistingProvider, type FactoryProvider, Inject, Injectable, type InjectableOptions, InvalidExportError, InvalidModuleError, MissingInjectableError, Module, type ModuleMetadata, Optional, type Provider, ReflectMetadataMissingError, type ResolutionContext, Scope, ScopeViolationError, type Token, TokenNotFoundError, type ValueProvider, describeToken };