@sukujs/di 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +85 -2
- package/dist/index.cjs +847 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +325 -0
- package/dist/index.d.mts +325 -0
- package/dist/index.mjs +811 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +54 -4
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal replacement for the `reflect-metadata` package.
|
|
3
|
+
*
|
|
4
|
+
* TypeScript's `emitDecoratorMetadata` emits calls such as
|
|
5
|
+
* `__metadata("design:paramtypes", [Logger, Database])`, which forward to
|
|
6
|
+
* `Reflect.metadata(key, value)` when that function exists. This module installs
|
|
7
|
+
* just enough of the Reflect metadata API, backed by a WeakMap, so the container can
|
|
8
|
+
* read constructor parameter types without a dependency.
|
|
9
|
+
*
|
|
10
|
+
* It is installed once on `globalThis.Reflect` the first time `@sukujs/di` is imported,
|
|
11
|
+
* and never overrides an existing implementation (for example a user-installed
|
|
12
|
+
* `reflect-metadata`).
|
|
13
|
+
*/
|
|
14
|
+
type MetadataKey = string | symbol;
|
|
15
|
+
type PropertyKey = string | symbol | undefined;
|
|
16
|
+
export declare function defineMetadata(key: MetadataKey, value: unknown, target: object, property?: PropertyKey): void;
|
|
17
|
+
export declare function getOwnMetadata<T = unknown>(key: MetadataKey, target: object, property?: PropertyKey): T | undefined;
|
|
18
|
+
export declare function hasOwnMetadata(key: MetadataKey, target: object, property?: PropertyKey): boolean;
|
|
19
|
+
/** Looks up metadata on the target and then along its prototype chain. */
|
|
20
|
+
export declare function getMetadata<T = unknown>(key: MetadataKey, target: object, property?: PropertyKey): T | undefined;
|
|
21
|
+
export declare function hasMetadata(key: MetadataKey, target: object, property?: PropertyKey): boolean;
|
|
22
|
+
/** Installs the shim on `globalThis.Reflect` unless a metadata API is already present. */
|
|
23
|
+
export declare function installReflectShim(): boolean;
|
|
24
|
+
interface ServiceProviderOptions {
|
|
25
|
+
/**
|
|
26
|
+
* Throw when a scoped service is resolved from the root provider, which is how a
|
|
27
|
+
* singleton capturing a scoped dependency is caught at runtime. Default `true`.
|
|
28
|
+
*/
|
|
29
|
+
validateScopes?: boolean;
|
|
30
|
+
/**
|
|
31
|
+
* Walk every class registration at build time and fail fast on missing
|
|
32
|
+
* dependencies, cycles, and captive dependencies. Default `false` (turn on in tests
|
|
33
|
+
* and development).
|
|
34
|
+
*/
|
|
35
|
+
validateOnBuild?: boolean;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Resolves services. The root provider is returned by `ServiceCollection.build()`;
|
|
39
|
+
* `createScope()` returns a child provider with its own scoped instances.
|
|
40
|
+
*
|
|
41
|
+
* `ServiceProvider` is itself injectable: a class that declares a `ServiceProvider`
|
|
42
|
+
* constructor parameter receives the provider it is being resolved from.
|
|
43
|
+
*/
|
|
44
|
+
export declare abstract class ServiceProvider {
|
|
45
|
+
abstract readonly isRoot: boolean;
|
|
46
|
+
/** The application's root provider. For a root provider, itself. */
|
|
47
|
+
abstract readonly root: ServiceProvider;
|
|
48
|
+
/** Resolves the last registration for `token`; throws `MissingServiceError` if none. */
|
|
49
|
+
abstract get<T>(token: Token<T>): T;
|
|
50
|
+
abstract getOptional<T>(token: Token<T>): T | undefined;
|
|
51
|
+
/** Resolves every registration for `token`, in registration order. */
|
|
52
|
+
abstract getAll<T>(token: Token<T>): T[];
|
|
53
|
+
abstract getKeyed<T>(token: Token<T>, key: unknown): T;
|
|
54
|
+
abstract getKeyedOptional<T>(token: Token<T>, key: unknown): T | undefined;
|
|
55
|
+
abstract has(token: Token, key?: unknown): boolean;
|
|
56
|
+
/**
|
|
57
|
+
* Constructs a class that is not registered, resolving its constructor parameters from
|
|
58
|
+
* this provider (like .NET's `ActivatorUtilities.CreateInstance`). The instance is owned by
|
|
59
|
+
* this provider and disposed with it.
|
|
60
|
+
*/
|
|
61
|
+
abstract create<T>(cls: Constructor<T>): T;
|
|
62
|
+
/** Creates a child provider. Dispose it to release scoped and transient instances it created. */
|
|
63
|
+
abstract createScope(): ServiceProvider;
|
|
64
|
+
/** Disposes instances this provider owns, newest first, then child scopes (root only). */
|
|
65
|
+
abstract dispose(): Promise<void>;
|
|
66
|
+
/** Enables `await using provider = collection.build()`. */
|
|
67
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
68
|
+
}
|
|
69
|
+
export declare function buildServiceProvider(descriptors: readonly ServiceDescriptor[], options?: ServiceProviderOptions): ServiceProvider;
|
|
70
|
+
type Constructor<T = unknown> = new (...args: any[]) => T;
|
|
71
|
+
type AbstractConstructor<T = unknown> = abstract new (...args: any[]) => T;
|
|
72
|
+
/**
|
|
73
|
+
* Opaque token for registering values that have no class to stand in for them
|
|
74
|
+
* (configuration objects, primitives, interfaces). Carries its type parameter so
|
|
75
|
+
* `provider.get(TOKEN)` is typed.
|
|
76
|
+
*/
|
|
77
|
+
export declare class InjectionToken<T = unknown> {
|
|
78
|
+
readonly description: string;
|
|
79
|
+
readonly __type?: T;
|
|
80
|
+
constructor(description: string);
|
|
81
|
+
toString(): string;
|
|
82
|
+
}
|
|
83
|
+
type Token<T = unknown> = Constructor<T> | AbstractConstructor<T> | InjectionToken<T> | string | symbol;
|
|
84
|
+
/** Infers the service type a token resolves to. */
|
|
85
|
+
type Resolved<K> = K extends Token<infer T> ? T : never;
|
|
86
|
+
type Lifetime = 'singleton' | 'scoped' | 'transient';
|
|
87
|
+
type Factory<T = unknown> = (provider: ServiceProvider) => T;
|
|
88
|
+
export declare function isConstructor(value: unknown): value is Constructor;
|
|
89
|
+
export declare function tokenName(token: unknown): string;
|
|
90
|
+
/** Dependencies a classless service asks for: `{ db: Database }` arrives as `{ db }` in `create`. */
|
|
91
|
+
type Dependencies = Record<string, Token>;
|
|
92
|
+
type ResolvedDependencies<D> = { [K in keyof D]: D[K] extends Token<infer T> ? T : never; };
|
|
93
|
+
interface ServiceDefinitionOptions<T, D extends Dependencies> {
|
|
94
|
+
/** `singleton` (default), `scoped` (one per request) or `transient`. */
|
|
95
|
+
lifetime?: Lifetime;
|
|
96
|
+
/** Other services this one needs, resolved by the container and passed to `create` by name. */
|
|
97
|
+
services?: D;
|
|
98
|
+
/** Builds the service. Whatever it returns is the service; its type is inferred. */
|
|
99
|
+
create: (deps: ResolvedDependencies<D>) => T;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* A service declared without a class. It is its own injection token and carries its own
|
|
103
|
+
* registration, so it can be listed in `services`, injected with `@Inject(Def)`, and named in
|
|
104
|
+
* a route's or another service's `services`.
|
|
105
|
+
*/
|
|
106
|
+
export declare class ServiceDefinition<T = unknown> extends InjectionToken<T> {
|
|
107
|
+
readonly descriptor: ServiceDescriptor<T>;
|
|
108
|
+
constructor(name: string, lifetime: Lifetime, dependencies: Dependencies, create: (deps: any) => T);
|
|
109
|
+
}
|
|
110
|
+
/** The type a token, class or `service()` definition resolves to. */
|
|
111
|
+
type ServiceOf<K> = K extends Token<infer T> ? T : never;
|
|
112
|
+
/**
|
|
113
|
+
* Declares a service without a class.
|
|
114
|
+
*
|
|
115
|
+
* ```ts
|
|
116
|
+
* export const Users = service('users', {
|
|
117
|
+
* services: { db: Database },
|
|
118
|
+
* create: ({ db }) => ({
|
|
119
|
+
* find: (id: number) => db.users.get(id),
|
|
120
|
+
* }),
|
|
121
|
+
* });
|
|
122
|
+
*
|
|
123
|
+
* // No dependencies: pass the factory directly.
|
|
124
|
+
* export const Clock = service('clock', () => ({ now: () => new Date() }));
|
|
125
|
+
* ```
|
|
126
|
+
*/
|
|
127
|
+
export declare function service<T>(name: string, create: () => T): ServiceDefinition<T>;
|
|
128
|
+
export declare function service<T, D extends Dependencies = {}>(name: string, options: ServiceDefinitionOptions<T, D>): ServiceDefinition<T>;
|
|
129
|
+
type DescriptorKind = 'class' | 'factory' | 'value' | 'existing';
|
|
130
|
+
/** A single registration. Immutable once added to a collection. */
|
|
131
|
+
interface ServiceDescriptor<T = unknown> {
|
|
132
|
+
readonly kind: DescriptorKind;
|
|
133
|
+
readonly token: Token<T>;
|
|
134
|
+
readonly lifetime: Lifetime;
|
|
135
|
+
/** Present only for keyed registrations. */
|
|
136
|
+
readonly key?: unknown;
|
|
137
|
+
readonly useClass?: Constructor<T>;
|
|
138
|
+
readonly useFactory?: Factory<T>;
|
|
139
|
+
readonly useValue?: T;
|
|
140
|
+
readonly useExisting?: Token<T>;
|
|
141
|
+
/** For factories that declare what they resolve, so startup validation can check them. */
|
|
142
|
+
readonly dependsOn?: readonly Token[];
|
|
143
|
+
}
|
|
144
|
+
/** Second argument of `addSingleton(token, impl)` and friends. */
|
|
145
|
+
type Implementation<T> = Constructor<T> | Factory<T> | {
|
|
146
|
+
useClass: Constructor<T>;
|
|
147
|
+
} | {
|
|
148
|
+
useFactory: Factory<T>;
|
|
149
|
+
} | {
|
|
150
|
+
useValue: T;
|
|
151
|
+
} | {
|
|
152
|
+
useExisting: Token<T>;
|
|
153
|
+
};
|
|
154
|
+
interface ProviderBase<T> {
|
|
155
|
+
provide: Token<T>;
|
|
156
|
+
lifetime?: Lifetime;
|
|
157
|
+
key?: unknown;
|
|
158
|
+
}
|
|
159
|
+
interface ClassProvider<T = unknown> extends ProviderBase<T> {
|
|
160
|
+
useClass: Constructor<T>;
|
|
161
|
+
}
|
|
162
|
+
interface FactoryProvider<T = unknown> extends ProviderBase<T> {
|
|
163
|
+
useFactory: Factory<T>;
|
|
164
|
+
}
|
|
165
|
+
interface ValueProvider<T = unknown> extends ProviderBase<T> {
|
|
166
|
+
useValue: T;
|
|
167
|
+
}
|
|
168
|
+
interface ExistingProvider<T = unknown> extends ProviderBase<T> {
|
|
169
|
+
useExisting: Token<T>;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* NestJS-style provider shorthand accepted by `collection.add()` and module
|
|
173
|
+
* definitions: a bare class, or an object with `provide` and one `use*` field.
|
|
174
|
+
*/
|
|
175
|
+
type Provider<T = unknown> = Constructor<T> | ServiceDefinition<T> | ClassProvider<T> | FactoryProvider<T> | ValueProvider<T> | ExistingProvider<T>;
|
|
176
|
+
/** Builds a descriptor from `(token, implementation, lifetime)` as the add* methods receive it. */
|
|
177
|
+
export declare function describe<T>(token: Token<T>, impl: Implementation<T> | undefined, lifetime: Lifetime, key?: unknown): ServiceDescriptor<T>;
|
|
178
|
+
/** Converts NestJS-style provider shorthand into a descriptor. Bare classes default to singleton. */
|
|
179
|
+
export declare function normalizeProvider<T>(provider: Provider<T>): ServiceDescriptor<T>;
|
|
180
|
+
/**
|
|
181
|
+
* Ordered list of registrations, modelled on .NET's `IServiceCollection`.
|
|
182
|
+
*
|
|
183
|
+
* - `get(token)` resolves the **last** registration for a token.
|
|
184
|
+
* - `getAll(token)` resolves every registration, in order.
|
|
185
|
+
* - `tryAdd*` only registers when the token has no registration yet.
|
|
186
|
+
*/
|
|
187
|
+
export declare class ServiceCollection {
|
|
188
|
+
private readonly items;
|
|
189
|
+
get descriptors(): readonly ServiceDescriptor[];
|
|
190
|
+
get size(): number;
|
|
191
|
+
/** Adds a descriptor, or a NestJS-style provider (`Class` or `{ provide, use* }`). */
|
|
192
|
+
add(entry: ServiceDescriptor | Provider): this;
|
|
193
|
+
addRange(entries: Iterable<ServiceDescriptor | Provider>): this;
|
|
194
|
+
addSingleton<T>(token: Token<T>, impl?: Implementation<T>): this;
|
|
195
|
+
addScoped<T>(token: Token<T>, impl?: Implementation<T>): this;
|
|
196
|
+
addTransient<T>(token: Token<T>, impl?: Implementation<T>): this;
|
|
197
|
+
addKeyedSingleton<T>(token: Token<T>, key: unknown, impl?: Implementation<T>): this;
|
|
198
|
+
addKeyedScoped<T>(token: Token<T>, key: unknown, impl?: Implementation<T>): this;
|
|
199
|
+
addKeyedTransient<T>(token: Token<T>, key: unknown, impl?: Implementation<T>): this;
|
|
200
|
+
/** Adds only if nothing is registered for the token (and key). */
|
|
201
|
+
tryAdd(entry: ServiceDescriptor | Provider): this;
|
|
202
|
+
tryAddSingleton<T>(token: Token<T>, impl?: Implementation<T>): this;
|
|
203
|
+
tryAddScoped<T>(token: Token<T>, impl?: Implementation<T>): this;
|
|
204
|
+
tryAddTransient<T>(token: Token<T>, impl?: Implementation<T>): this;
|
|
205
|
+
/**
|
|
206
|
+
* Adds only if no registration for the token has the same implementation
|
|
207
|
+
* (class, factory, or alias). Useful for plugin collections resolved with `getAll`.
|
|
208
|
+
*/
|
|
209
|
+
tryAddEnumerable(entry: ServiceDescriptor | Provider): this;
|
|
210
|
+
has(token: Token, key?: unknown): boolean;
|
|
211
|
+
/** Removes every registration for the token (and key). */
|
|
212
|
+
remove(token: Token, key?: unknown): this;
|
|
213
|
+
/** Removes all registrations for the entry's token, then adds it. */
|
|
214
|
+
replace(entry: ServiceDescriptor | Provider): this;
|
|
215
|
+
/** Builds the root `ServiceProvider`. The collection may still be modified afterwards. */
|
|
216
|
+
build(options?: ServiceProviderOptions): ServiceProvider;
|
|
217
|
+
}
|
|
218
|
+
interface ServiceOptions {
|
|
219
|
+
/** Default lifetime used when the class is registered bare (`collection.add(MyService)`). */
|
|
220
|
+
lifetime?: Lifetime;
|
|
221
|
+
}
|
|
222
|
+
interface InjectOptions {
|
|
223
|
+
token: Token;
|
|
224
|
+
key?: unknown;
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Marks a class as resolvable by the container. Any decorator makes TypeScript emit
|
|
228
|
+
* `design:paramtypes`, which is what the container reads to perform constructor
|
|
229
|
+
* injection; this one additionally records default registration options.
|
|
230
|
+
*/
|
|
231
|
+
export declare function Service(options?: ServiceOptions): ClassDecorator;
|
|
232
|
+
export declare function getServiceOptions(target: object): ServiceOptions | undefined;
|
|
233
|
+
export declare function isService(target: object): boolean;
|
|
234
|
+
/**
|
|
235
|
+
* Overrides the token used for one constructor parameter. Required when the
|
|
236
|
+
* parameter type is an interface, a primitive, a string/symbol token, or an
|
|
237
|
+
* `InjectionToken`. Pass `key` to resolve a keyed registration.
|
|
238
|
+
*/
|
|
239
|
+
export declare function Inject(token: Token, key?: unknown): ParameterDecorator;
|
|
240
|
+
/** Resolves to `undefined` instead of throwing when the parameter's service is missing. */
|
|
241
|
+
export declare function Optional(): ParameterDecorator;
|
|
242
|
+
export declare class DiError extends Error {
|
|
243
|
+
readonly name: string;
|
|
244
|
+
}
|
|
245
|
+
export declare class MissingServiceError extends DiError {
|
|
246
|
+
readonly token: unknown;
|
|
247
|
+
readonly key: unknown;
|
|
248
|
+
readonly name = "MissingServiceError";
|
|
249
|
+
constructor(token: unknown, key: unknown, chain: readonly ServiceDescriptor[]);
|
|
250
|
+
}
|
|
251
|
+
export declare class CircularDependencyError extends DiError {
|
|
252
|
+
readonly chain: readonly ServiceDescriptor[];
|
|
253
|
+
readonly name = "CircularDependencyError";
|
|
254
|
+
constructor(chain: readonly ServiceDescriptor[]);
|
|
255
|
+
}
|
|
256
|
+
export declare class ScopedFromRootError extends DiError {
|
|
257
|
+
readonly descriptor: ServiceDescriptor;
|
|
258
|
+
readonly name = "ScopedFromRootError";
|
|
259
|
+
constructor(descriptor: ServiceDescriptor, chain: readonly ServiceDescriptor[]);
|
|
260
|
+
}
|
|
261
|
+
export declare class CaptiveDependencyError extends DiError {
|
|
262
|
+
readonly consumer: ServiceDescriptor;
|
|
263
|
+
readonly dependency: ServiceDescriptor;
|
|
264
|
+
readonly name = "CaptiveDependencyError";
|
|
265
|
+
constructor(consumer: ServiceDescriptor, dependency: ServiceDescriptor);
|
|
266
|
+
}
|
|
267
|
+
export declare class UnresolvableParameterError extends DiError {
|
|
268
|
+
readonly name = "UnresolvableParameterError";
|
|
269
|
+
constructor(cls: Function, index: number, reason: string);
|
|
270
|
+
}
|
|
271
|
+
export declare class InvalidDescriptorError extends DiError {
|
|
272
|
+
readonly name = "InvalidDescriptorError";
|
|
273
|
+
}
|
|
274
|
+
export declare class ProviderDisposedError extends DiError {
|
|
275
|
+
readonly name = "ProviderDisposedError";
|
|
276
|
+
constructor();
|
|
277
|
+
}
|
|
278
|
+
interface BindingOptions {
|
|
279
|
+
/** Registers a keyed service, resolved with `getKeyed(token, key)` or `@Inject(token, key)`. */
|
|
280
|
+
key?: unknown;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Typed registration helpers. Unlike `{ provide, useClass }` objects, the implementation is
|
|
284
|
+
* checked against the token: `singleton(Logger, ConsoleLogger)` fails to compile unless
|
|
285
|
+
* `ConsoleLogger` is assignable to `Logger`.
|
|
286
|
+
*
|
|
287
|
+
* ```ts
|
|
288
|
+
* services: [
|
|
289
|
+
* singleton(Logger, ConsoleLogger),
|
|
290
|
+
* scoped(UnitOfWork),
|
|
291
|
+
* value(CONFIG, { port: 3000 }),
|
|
292
|
+
* factory(Mailer, (sp) => new Mailer(sp.get(Logger))),
|
|
293
|
+
* alias(Cache, RedisCache),
|
|
294
|
+
* ]
|
|
295
|
+
* ```
|
|
296
|
+
*/
|
|
297
|
+
export declare function singleton<T>(token: Token<T>, impl?: Constructor<NoInfer<T>>, options?: BindingOptions): ServiceDescriptor<T>;
|
|
298
|
+
export declare function scoped<T>(token: Token<T>, impl?: Constructor<NoInfer<T>>, options?: BindingOptions): ServiceDescriptor<T>;
|
|
299
|
+
export declare function transient<T>(token: Token<T>, impl?: Constructor<NoInfer<T>>, options?: BindingOptions): ServiceDescriptor<T>;
|
|
300
|
+
/** Registers an existing instance or constant. Never disposed by the container. */
|
|
301
|
+
export declare function value<T>(token: Token<T>, instance: T, options?: BindingOptions): ServiceDescriptor<T>;
|
|
302
|
+
/** Registers a factory. Singleton unless a lifetime is given. */
|
|
303
|
+
export declare function factory<T>(token: Token<T>, create: Factory<NoInfer<T>>, lifetime?: Lifetime, options?: BindingOptions): ServiceDescriptor<T>;
|
|
304
|
+
/** Makes `token` resolve to whatever `existing` resolves to. */
|
|
305
|
+
export declare function alias<T, U extends T>(token: Token<T>, existing: Token<U>, options?: BindingOptions): ServiceDescriptor<T>;
|
|
306
|
+
interface InjectEntryObject {
|
|
307
|
+
token: Token;
|
|
308
|
+
key?: unknown;
|
|
309
|
+
optional?: boolean;
|
|
310
|
+
}
|
|
311
|
+
/** One entry of a class's `static inject` array. */
|
|
312
|
+
type InjectEntry = Token | InjectEntryObject;
|
|
313
|
+
interface ParameterInfo {
|
|
314
|
+
readonly index: number;
|
|
315
|
+
readonly token: Token;
|
|
316
|
+
readonly key?: unknown;
|
|
317
|
+
readonly optional: boolean;
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Determines the token for each constructor parameter of `cls`, combining
|
|
321
|
+
* `design:paramtypes` (emitted by TypeScript) with `@Inject` / `@Optional` overrides.
|
|
322
|
+
* Results are cached per class.
|
|
323
|
+
*/
|
|
324
|
+
export declare function getConstructorParameters(cls: Function): readonly ParameterInfo[];
|
|
325
|
+
export type { AbstractConstructor, BindingOptions, ClassProvider, Constructor, Dependencies, DescriptorKind, ExistingProvider, Factory, FactoryProvider, Implementation, InjectEntry, InjectEntryObject, InjectOptions, Lifetime, ParameterInfo, Provider, Resolved, ResolvedDependencies, ServiceDefinitionOptions, ServiceDescriptor, ServiceOf, ServiceOptions, ServiceProviderOptions, Token, ValueProvider };
|