truxie 0.1.0-test.2 → 0.1.0-test.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-F5KXBDV2.js +1 -0
- package/dist/chunk-RMR6UXWO.js +1 -0
- package/dist/chunk-XVPJFMLQ.js +1 -0
- package/dist/index.d.ts +273 -140
- package/dist/index.js +3 -3
- package/dist/saga.d.ts +82 -0
- package/dist/saga.js +1 -0
- package/dist/schedule.d.ts +132 -0
- package/dist/schedule.js +1 -0
- package/dist/types-D-An5cXP.d.ts +88 -0
- package/package.json +17 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a,d as d$1}from'./chunk-RMR6UXWO.js';import'reflect-metadata';var s=Symbol("module"),d=Symbol("module:global");function b(t){return e=>{Reflect.defineMetadata(s,t,e);}}a(b,"Module");function m(){return t=>{Reflect.defineMetadata(d,true,t);}}a(m,"Global");function A(t){return Reflect.getOwnMetadata(s,t)}a(A,"getModuleMetadata");function O(t){return Reflect.getOwnMetadata(d,t)===true}a(O,"isGlobalModule");function p(t,e,o,l){var u=arguments.length,n=u<3?e:l===null?l=Object.getOwnPropertyDescriptor(e,o):l,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(t,e,o,l);else for(var i=t.length-1;i>=0;i--)(a=t[i])&&(n=(u<3?a(n):u>3?a(e,o,n):a(e,o))||n);return u>3&&n&&Object.defineProperty(e,o,n),n}a(p,"_ts_decorate");var f=class{static{a(this,"DiscoveryService");}container;providers=[];_init(e,o){this.container=e,this.providers=o;}getProviders(){return this.providers}async resolve(e){return this.container.resolve(e)}getProviderClass(e){return typeof e=="function"?e:"useClass"in e?e.useClass:null}};f=p([d$1()],f);export{b as a,m as b,A as c,O as d,f as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import'reflect-metadata';var u=Object.defineProperty;var n=(t,e)=>u(t,"name",{value:e,configurable:true});var p=(function(t){return t.SINGLETON="singleton",t.REQUEST="request",t.TRANSIENT="transient",t})({}),s=class{static{n(this,"InjectionToken");}description;constructor(e){this.description=e;}toString(){return `InjectionToken(${this.description})`}};var f=Symbol("injectable"),a=Symbol("inject:param"),l=Symbol("inject:deps"),r=Symbol("optional");function R(t){return e=>{Reflect.defineMetadata(f,{scope:t?.scope??p.SINGLETON},e);}}n(R,"Injectable");function O(...t){return (e,c,o)=>{if(typeof o=="number"){let i=Reflect.getOwnMetadata(a,e)??new Map;i.set(o,t[0]),Reflect.defineMetadata(a,i,e);}else Reflect.defineMetadata(l,t,e);}}n(O,"Inject");function g(){return (t,e,c)=>{let o=Reflect.getOwnMetadata(r,t)??new Set;o.add(c),Reflect.defineMetadata(r,o,t);}}n(g,"Optional");function S(t){return Reflect.getOwnMetadata(f,t)}n(S,"getInjectableMetadata");function w(t){return Reflect.getOwnMetadata(l,t)??[]}n(w,"getClassDeps");function x(t){return Reflect.getOwnMetadata(a,t)??new Map}n(x,"getInjectTokens");function I(t){return Reflect.getOwnMetadata(r,t)??new Set}n(I,"getOptionalParams");export{n as a,p as b,s as c,R as d,O as e,g as f,S as g,w as h,x as i,I as j};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-RMR6UXWO.js';var e=class extends Error{static{a$1(this,"AppError");}statusCode;status;isOperational;constructor(s,c){super(s),this.statusCode=c,this.status=c>=400&&c<500?"fail":"error",this.isOperational=true,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace(this,this.constructor);}},o=class extends e{static{a$1(this,"NotFoundError");}constructor(s="Resource not found"){super(s,404);}},u=class extends e{static{a$1(this,"ValidationError");}errors;constructor(s="Validation failed",c){super(s,400),this.errors=c;}},a=class extends e{static{a$1(this,"UnauthorizedError");}constructor(s="Not authorized"){super(s,401);}},n=class extends e{static{a$1(this,"ForbiddenError");}constructor(s="Access forbidden"){super(s,403);}},p=class extends e{static{a$1(this,"ConflictError");}constructor(s="Resource conflict"){super(s,409);}},i=class extends e{static{a$1(this,"RequestAbortedError");}constructor(s="Request aborted by client"){super(s,499);}};export{e as a,o as b,u as c,a as d,n as e,p as f,i as g};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,45 +1,7 @@
|
|
|
1
|
+
import { P as Provider, T as Token, I as InjectableOptions, a as Type, F as ForwardRef, M as ModuleMetadata, D as DynamicModule, b as ModuleAsyncOptions, c as InjectionToken } from './types-D-An5cXP.js';
|
|
2
|
+
export { C as ClassProvider, E as ExistingProvider, d as FactoryProvider, e as ModuleOptionsFactory, S as Scope, V as ValueProvider } from './types-D-An5cXP.js';
|
|
1
3
|
import { ZodSchema } from 'zod';
|
|
2
4
|
|
|
3
|
-
declare enum Scope {
|
|
4
|
-
SINGLETON = "singleton",
|
|
5
|
-
REQUEST = "request",
|
|
6
|
-
TRANSIENT = "transient"
|
|
7
|
-
}
|
|
8
|
-
interface Type<T = unknown> extends Function {
|
|
9
|
-
new (...args: any[]): T;
|
|
10
|
-
}
|
|
11
|
-
interface InjectableOptions {
|
|
12
|
-
scope?: Scope;
|
|
13
|
-
}
|
|
14
|
-
interface ClassProvider<T = unknown> {
|
|
15
|
-
provide: Token<T>;
|
|
16
|
-
useClass: Type<T>;
|
|
17
|
-
scope?: Scope;
|
|
18
|
-
}
|
|
19
|
-
interface ValueProvider<T = unknown> {
|
|
20
|
-
provide: Token<T>;
|
|
21
|
-
useValue: T;
|
|
22
|
-
}
|
|
23
|
-
interface FactoryProvider<T = unknown> {
|
|
24
|
-
provide: Token<T>;
|
|
25
|
-
useFactory: (...args: any[]) => T | Promise<T>;
|
|
26
|
-
inject?: Token[];
|
|
27
|
-
}
|
|
28
|
-
interface ExistingProvider<T = unknown> {
|
|
29
|
-
provide: Token<T>;
|
|
30
|
-
useExisting: Token<T>;
|
|
31
|
-
}
|
|
32
|
-
type Provider<T = unknown> = Type<T> | ClassProvider<T> | ValueProvider<T> | FactoryProvider<T> | ExistingProvider<T>;
|
|
33
|
-
type Token<T = unknown> = Type<T> | string | symbol | InjectionToken<T>;
|
|
34
|
-
declare class InjectionToken<T = unknown> {
|
|
35
|
-
readonly description: string;
|
|
36
|
-
constructor(description: string);
|
|
37
|
-
toString(): string;
|
|
38
|
-
}
|
|
39
|
-
interface ForwardRef<T = unknown> {
|
|
40
|
-
forwardRef: () => Type<T>;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
5
|
declare class Container {
|
|
44
6
|
private registrations;
|
|
45
7
|
private resolving;
|
|
@@ -77,24 +39,28 @@ declare function Optional(): ParameterDecorator;
|
|
|
77
39
|
declare function forwardRef<T>(fn: () => Type<T>): ForwardRef<T>;
|
|
78
40
|
declare function resolveForwardRef<T>(ref: Type<T> | ForwardRef<T>): Type<T>;
|
|
79
41
|
|
|
80
|
-
interface ModuleMetadata {
|
|
81
|
-
imports?: Array<Type | DynamicModule>;
|
|
82
|
-
controllers?: Type[];
|
|
83
|
-
providers?: Provider[];
|
|
84
|
-
exports?: Token[];
|
|
85
|
-
}
|
|
86
|
-
interface DynamicModule {
|
|
87
|
-
module: Type;
|
|
88
|
-
imports?: Array<Type | DynamicModule>;
|
|
89
|
-
controllers?: Type[];
|
|
90
|
-
providers?: Provider[];
|
|
91
|
-
exports?: Token[];
|
|
92
|
-
global?: boolean;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
42
|
declare function Module(metadata: ModuleMetadata): ClassDecorator;
|
|
43
|
+
/**
|
|
44
|
+
* Marks a module as global so its exported providers are visible to all
|
|
45
|
+
* modules without needing to import it explicitly.
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* @Global()
|
|
49
|
+
* @Module({ providers: [ConfigService], exports: [ConfigService] })
|
|
50
|
+
* export class CoreModule {}
|
|
51
|
+
*/
|
|
52
|
+
declare function Global(): ClassDecorator;
|
|
96
53
|
declare function getModuleMetadata(target: Function): ModuleMetadata | undefined;
|
|
54
|
+
declare function isGlobalModule(target: Function): boolean;
|
|
97
55
|
|
|
56
|
+
interface ResolvedModule {
|
|
57
|
+
type: Type;
|
|
58
|
+
metadata: ModuleMetadata;
|
|
59
|
+
controllers: Type[];
|
|
60
|
+
providers: Provider[];
|
|
61
|
+
exports: Set<Token>;
|
|
62
|
+
global: boolean;
|
|
63
|
+
}
|
|
98
64
|
declare class ModuleRegistry {
|
|
99
65
|
private resolved;
|
|
100
66
|
private sortedModules;
|
|
@@ -113,10 +79,146 @@ declare class ModuleRegistry {
|
|
|
113
79
|
getAllControllers(): Type[];
|
|
114
80
|
callLifecycleHooks(container: Container, hook: string, signal?: string): Promise<void>;
|
|
115
81
|
private resolveModule;
|
|
82
|
+
/**
|
|
83
|
+
* Build the set of tokens visible to a module:
|
|
84
|
+
* own providers + exported tokens from imported modules + global module providers.
|
|
85
|
+
*/
|
|
86
|
+
getVisibleTokens(mod: ResolvedModule): Set<Token>;
|
|
87
|
+
/**
|
|
88
|
+
* Validate that every module's exports are resolvable:
|
|
89
|
+
* each exported token must be in the module's own providers
|
|
90
|
+
* or in an imported module's exports (re-export).
|
|
91
|
+
*/
|
|
92
|
+
private validateExports;
|
|
93
|
+
/**
|
|
94
|
+
* Validate that all @Inject dependencies of a module's providers
|
|
95
|
+
* are visible (own providers + imported exports + globals).
|
|
96
|
+
* Call after scan() for strict visibility enforcement.
|
|
97
|
+
*/
|
|
98
|
+
validateVisibility(): void;
|
|
99
|
+
private getProviderToken;
|
|
100
|
+
private collectImportedExports;
|
|
101
|
+
/**
|
|
102
|
+
* Find a provider by token in a module's own providers.
|
|
103
|
+
*/
|
|
104
|
+
private findProvider;
|
|
105
|
+
/**
|
|
106
|
+
* Find a provider from an imported module's exports (for re-export support).
|
|
107
|
+
* Walks the import chain to find the original provider definition.
|
|
108
|
+
*/
|
|
109
|
+
private findReExportedProvider;
|
|
116
110
|
private getModuleType;
|
|
117
111
|
private topologicalSort;
|
|
118
112
|
}
|
|
119
113
|
|
|
114
|
+
/**
|
|
115
|
+
* The class generated by `ConfigurableModuleBuilder.build()`.
|
|
116
|
+
*
|
|
117
|
+
* Extend it in your module class to inherit `forRoot`, `forRootAsync`,
|
|
118
|
+
* and `forFeature` as static methods.
|
|
119
|
+
*/
|
|
120
|
+
interface ConfigurableModuleClass<TOptions extends object> {
|
|
121
|
+
new (...args: any[]): {};
|
|
122
|
+
/**
|
|
123
|
+
* Synchronous configuration — use when options are known at module load time.
|
|
124
|
+
*
|
|
125
|
+
* @example
|
|
126
|
+
* @Module({ imports: [NotionModule.forRoot({ apiKey: '...' })] })
|
|
127
|
+
* class AppModule {}
|
|
128
|
+
*/
|
|
129
|
+
forRoot(options: TOptions, extras?: ExtraOptions): DynamicModule;
|
|
130
|
+
/**
|
|
131
|
+
* Asynchronous configuration — use when options come from config service,
|
|
132
|
+
* environment, or another provider.
|
|
133
|
+
*
|
|
134
|
+
* @example
|
|
135
|
+
* @Module({
|
|
136
|
+
* imports: [NotionModule.forRootAsync({
|
|
137
|
+
* imports: [ConfigModule],
|
|
138
|
+
* useFactory: (cfg: ConfigService) => ({ apiKey: cfg.get('NOTION_KEY') }),
|
|
139
|
+
* inject: [ConfigService],
|
|
140
|
+
* })]
|
|
141
|
+
* })
|
|
142
|
+
* class AppModule {}
|
|
143
|
+
*/
|
|
144
|
+
forRootAsync(asyncOptions: ModuleAsyncOptions<TOptions>): DynamicModule;
|
|
145
|
+
/**
|
|
146
|
+
* Feature-level configuration — use inside feature modules to configure
|
|
147
|
+
* a subset of the module's behaviour (e.g. register specific entities/schemas).
|
|
148
|
+
*
|
|
149
|
+
* @example
|
|
150
|
+
* @Module({ imports: [TypeOrmModule.forFeature([User, Post])] })
|
|
151
|
+
* class UserModule {}
|
|
152
|
+
*/
|
|
153
|
+
forFeature(config: FeatureConfig, extras?: ExtraOptions): DynamicModule;
|
|
154
|
+
}
|
|
155
|
+
/** Extra options available on every `forRoot` / `forFeature` call. */
|
|
156
|
+
interface ExtraOptions {
|
|
157
|
+
/** When true, providers exported by this module are available everywhere. */
|
|
158
|
+
global?: boolean;
|
|
159
|
+
}
|
|
160
|
+
/** Configuration accepted by `forFeature`. */
|
|
161
|
+
type FeatureConfig = object;
|
|
162
|
+
interface ConfigurableModuleBuilderResult<TOptions extends object, TFeature extends FeatureConfig> {
|
|
163
|
+
/**
|
|
164
|
+
* Base class to extend in your `@Module` class.
|
|
165
|
+
* Provides `forRoot`, `forRootAsync`, and `forFeature` as static methods.
|
|
166
|
+
*/
|
|
167
|
+
ConfigurableModuleClass: ConfigurableModuleClass<TOptions>;
|
|
168
|
+
/**
|
|
169
|
+
* Injection token for the module options.
|
|
170
|
+
* Use with `@Inject(MODULE_OPTIONS_TOKEN)` in your service.
|
|
171
|
+
*/
|
|
172
|
+
MODULE_OPTIONS_TOKEN: InjectionToken<TOptions>;
|
|
173
|
+
/**
|
|
174
|
+
* Injection token for the feature config (only if `forFeature` is used).
|
|
175
|
+
* Use with `@Inject(MODULE_FEATURE_TOKEN)` in your service.
|
|
176
|
+
*/
|
|
177
|
+
MODULE_FEATURE_TOKEN: InjectionToken<TFeature[]>;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Builds a reusable configurable module base class with `forRoot`,
|
|
181
|
+
* `forRootAsync`, and `forFeature` static methods — identical to the
|
|
182
|
+
* NestJS `ConfigurableModuleBuilder` pattern.
|
|
183
|
+
*
|
|
184
|
+
* @example
|
|
185
|
+
* const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } =
|
|
186
|
+
* new ConfigurableModuleBuilder<NotionOptions>().build()
|
|
187
|
+
*
|
|
188
|
+
* @Global()
|
|
189
|
+
* @Module({ providers: [NotionService], exports: [NotionService] })
|
|
190
|
+
* export class NotionModule extends ConfigurableModuleClass {}
|
|
191
|
+
*/
|
|
192
|
+
declare class ConfigurableModuleBuilder<TOptions extends object, TFeature extends FeatureConfig = FeatureConfig> {
|
|
193
|
+
private description;
|
|
194
|
+
private featureDescription;
|
|
195
|
+
private onForRoot?;
|
|
196
|
+
private onForFeature?;
|
|
197
|
+
constructor(description?: string);
|
|
198
|
+
/**
|
|
199
|
+
* Custom token description (used in error messages).
|
|
200
|
+
* Default: `'MODULE_OPTIONS'`.
|
|
201
|
+
*/
|
|
202
|
+
setTokenDescription(description: string): this;
|
|
203
|
+
/**
|
|
204
|
+
* Hook called after every `forRoot` / `forRootAsync` to let you augment
|
|
205
|
+
* the returned `DynamicModule` (e.g. add extra providers, change exports).
|
|
206
|
+
*
|
|
207
|
+
* @example
|
|
208
|
+
* builder.transformDynamicModule((mod, opts) => ({
|
|
209
|
+
* ...mod,
|
|
210
|
+
* providers: [...(mod.providers ?? []), createCacheProvider(opts)],
|
|
211
|
+
* }))
|
|
212
|
+
*/
|
|
213
|
+
transformDynamicModule(fn: (module: DynamicModule, options: TOptions) => DynamicModule): this;
|
|
214
|
+
/**
|
|
215
|
+
* Hook called after every `forFeature` to let you augment the
|
|
216
|
+
* returned `DynamicModule`.
|
|
217
|
+
*/
|
|
218
|
+
transformFeatureModule(fn: (module: DynamicModule, config: TFeature) => DynamicModule): this;
|
|
219
|
+
build(): ConfigurableModuleBuilderResult<TOptions, TFeature>;
|
|
220
|
+
}
|
|
221
|
+
|
|
120
222
|
/** Framework-agnostic representation of a multipart form field or file. */
|
|
121
223
|
interface FormDataPart {
|
|
122
224
|
name: string;
|
|
@@ -188,6 +290,24 @@ interface Interceptor {
|
|
|
188
290
|
intercept(ctx: ExecutionContext, next: () => Promise<unknown>): Promise<unknown>;
|
|
189
291
|
}
|
|
190
292
|
|
|
293
|
+
/**
|
|
294
|
+
* Middleware runs before guards, pipes, and interceptors.
|
|
295
|
+
* Suitable for: logging, CORS, rate limiting, request transformation.
|
|
296
|
+
*
|
|
297
|
+
* @example
|
|
298
|
+
* class LogMiddleware implements Middleware {
|
|
299
|
+
* async use(ctx: ExecutionContext, next: () => Promise<unknown>) {
|
|
300
|
+
* console.log('→', ctx.getNativeRequest())
|
|
301
|
+
* const result = await next()
|
|
302
|
+
* console.log('←', result)
|
|
303
|
+
* return result
|
|
304
|
+
* }
|
|
305
|
+
* }
|
|
306
|
+
*/
|
|
307
|
+
interface Middleware {
|
|
308
|
+
use(ctx: ExecutionContext, next: () => Promise<unknown>): Promise<unknown>;
|
|
309
|
+
}
|
|
310
|
+
|
|
191
311
|
interface PipeTransform {
|
|
192
312
|
transform(ctx: ExecutionContext): void | Promise<void>;
|
|
193
313
|
}
|
|
@@ -204,9 +324,11 @@ interface ExceptionFilter {
|
|
|
204
324
|
|
|
205
325
|
type GuardRef = Type<ICanActivateGuard> | ICanActivateGuard;
|
|
206
326
|
type InterceptorRef = Type<Interceptor> | Interceptor;
|
|
327
|
+
type MiddlewareRef$1 = Type<Middleware> | Middleware;
|
|
207
328
|
type PipeRef = Type<PipeTransform> | PipeTransform;
|
|
208
329
|
type FilterRef = Type<ExceptionFilter> | ExceptionFilter;
|
|
209
330
|
interface PipelineOptions {
|
|
331
|
+
middlewares?: MiddlewareRef$1[];
|
|
210
332
|
guards?: GuardRef[];
|
|
211
333
|
interceptors?: InterceptorRef[];
|
|
212
334
|
pipes?: PipeRef[];
|
|
@@ -219,7 +341,16 @@ interface CreatePipelineOptions extends PipelineOptions {
|
|
|
219
341
|
}
|
|
220
342
|
declare function createPipeline(container: Container, globalOptions: PipelineOptions, localOptions: CreatePipelineOptions): (ctx: ExecutionContext) => Promise<unknown>;
|
|
221
343
|
|
|
222
|
-
declare function UseInterceptors(...interceptors: InterceptorRef[]):
|
|
344
|
+
declare function UseInterceptors(...interceptors: InterceptorRef[]): any;
|
|
345
|
+
/** Class-level interceptors set via @UseInterceptors on the class. */
|
|
346
|
+
declare function getInterceptorsMetadata(target: Function): InterceptorRef[];
|
|
347
|
+
/** Method-level interceptors set via @UseInterceptors on a specific method. */
|
|
348
|
+
declare function getMethodInterceptors(target: Function, methodName: string): InterceptorRef[];
|
|
349
|
+
/**
|
|
350
|
+
* Effective interceptors for a route = class-level + method-level, in that order.
|
|
351
|
+
* Class interceptors run first (outermost), method interceptors run last (innermost).
|
|
352
|
+
*/
|
|
353
|
+
declare function getEffectiveInterceptors(target: Function, methodName: string): InterceptorRef[];
|
|
223
354
|
|
|
224
355
|
/**
|
|
225
356
|
* Framework-agnostic transaction context.
|
|
@@ -306,6 +437,33 @@ declare class UnitOfWorkInterceptor implements Interceptor {
|
|
|
306
437
|
intercept(ctx: ExecutionContext, next: () => Promise<unknown>): Promise<unknown>;
|
|
307
438
|
}
|
|
308
439
|
|
|
440
|
+
type MiddlewareRef = Type<Middleware> | Middleware;
|
|
441
|
+
/**
|
|
442
|
+
* Attach middleware to a controller class or a specific route method.
|
|
443
|
+
*
|
|
444
|
+
* Class-level: runs for every route in the controller.
|
|
445
|
+
* Method-level: runs only for that route, after class-level middleware.
|
|
446
|
+
*
|
|
447
|
+
* @example
|
|
448
|
+
* @UseMiddleware(LogMiddleware)
|
|
449
|
+
* @Controller('users')
|
|
450
|
+
* class UserController {
|
|
451
|
+
* @UseMiddleware(RateLimitMiddleware)
|
|
452
|
+
* @Post('/')
|
|
453
|
+
* create() { ... }
|
|
454
|
+
* }
|
|
455
|
+
*/
|
|
456
|
+
declare function UseMiddleware(...middlewares: MiddlewareRef[]): any;
|
|
457
|
+
/** Class-level middlewares set via @UseMiddleware on the class. */
|
|
458
|
+
declare function getMiddlewaresMetadata(target: Function): MiddlewareRef[];
|
|
459
|
+
/** Method-level middlewares set via @UseMiddleware on a specific method. */
|
|
460
|
+
declare function getMethodMiddlewares(target: Function, methodName: string): MiddlewareRef[];
|
|
461
|
+
/**
|
|
462
|
+
* Effective middlewares for a route = class-level + method-level, in that order.
|
|
463
|
+
* Class middlewares run first (outermost), method middlewares run next.
|
|
464
|
+
*/
|
|
465
|
+
declare function getEffectiveMiddlewares(target: Function, methodName: string): MiddlewareRef[];
|
|
466
|
+
|
|
309
467
|
declare function UsePipes(...pipes: PipeRef[]): ClassDecorator & MethodDecorator;
|
|
310
468
|
|
|
311
469
|
interface ZodLikeSchema {
|
|
@@ -516,88 +674,6 @@ declare class EventBus {
|
|
|
516
674
|
*/
|
|
517
675
|
declare function OnEvent(eventType: string): MethodDecorator;
|
|
518
676
|
|
|
519
|
-
/**
|
|
520
|
-
* A single step in a saga.
|
|
521
|
-
*
|
|
522
|
-
* @template T - The return type of the execute function
|
|
523
|
-
*/
|
|
524
|
-
interface SagaStep<T = unknown> {
|
|
525
|
-
/** Human-readable name for logging/debugging. */
|
|
526
|
-
name: string;
|
|
527
|
-
/** The forward action. Returns a result that is passed to compensate on failure. */
|
|
528
|
-
execute: (signal?: AbortSignal) => T | Promise<T>;
|
|
529
|
-
/**
|
|
530
|
-
* The compensating action. Called with the result of execute() if a LATER step fails.
|
|
531
|
-
* Should undo the effect of execute().
|
|
532
|
-
* If not provided, the step is considered non-compensatable (e.g., the last step).
|
|
533
|
-
*/
|
|
534
|
-
compensate?: (result: T) => void | Promise<void>;
|
|
535
|
-
}
|
|
536
|
-
interface SagaResult<T = unknown> {
|
|
537
|
-
/** Whether all steps completed successfully. */
|
|
538
|
-
success: boolean;
|
|
539
|
-
/** Results of each completed step, keyed by step name. */
|
|
540
|
-
results: Record<string, unknown>;
|
|
541
|
-
/** The result of the last step (convenience). */
|
|
542
|
-
value?: T;
|
|
543
|
-
/** If failed, the error that caused the failure. */
|
|
544
|
-
error?: unknown;
|
|
545
|
-
/** Name of the step that failed. */
|
|
546
|
-
failedStep?: string;
|
|
547
|
-
/** Names of steps that were successfully compensated. */
|
|
548
|
-
compensated: string[];
|
|
549
|
-
/** Compensation errors, if any. Keyed by step name. */
|
|
550
|
-
compensationErrors: Record<string, unknown>;
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
interface SagaOrchestratorOptions {
|
|
554
|
-
/** Called when a compensation step fails. Defaults to console.error. */
|
|
555
|
-
onCompensationError?: (stepName: string, error: unknown) => void;
|
|
556
|
-
}
|
|
557
|
-
/**
|
|
558
|
-
* Executes a sequence of steps with automatic compensation on failure.
|
|
559
|
-
*
|
|
560
|
-
* If step N fails, steps N-1..0 are compensated in reverse order.
|
|
561
|
-
* Compensation errors are captured but do NOT prevent other compensations.
|
|
562
|
-
*
|
|
563
|
-
* @example
|
|
564
|
-
* ```typescript
|
|
565
|
-
* @UseCase()
|
|
566
|
-
* class CreateOrderUseCase {
|
|
567
|
-
* constructor(private saga: SagaOrchestrator) {}
|
|
568
|
-
*
|
|
569
|
-
* async execute(input: CreateOrderInput) {
|
|
570
|
-
* const result = await this.saga.execute([
|
|
571
|
-
* {
|
|
572
|
-
* name: 'reserve-inventory',
|
|
573
|
-
* execute: () => inventoryService.reserve(input.items),
|
|
574
|
-
* compensate: (res) => inventoryService.release(res.reservationId),
|
|
575
|
-
* },
|
|
576
|
-
* {
|
|
577
|
-
* name: 'charge-payment',
|
|
578
|
-
* execute: () => paymentService.charge(input.amount),
|
|
579
|
-
* compensate: (res) => paymentService.refund(res.chargeId),
|
|
580
|
-
* },
|
|
581
|
-
* {
|
|
582
|
-
* name: 'create-order',
|
|
583
|
-
* execute: () => orderService.create(input),
|
|
584
|
-
* },
|
|
585
|
-
* ])
|
|
586
|
-
*
|
|
587
|
-
* if (!result.success) throw result.error
|
|
588
|
-
* return result.value
|
|
589
|
-
* }
|
|
590
|
-
* }
|
|
591
|
-
* ```
|
|
592
|
-
*/
|
|
593
|
-
declare class SagaOrchestrator {
|
|
594
|
-
private onCompensationError;
|
|
595
|
-
constructor();
|
|
596
|
-
setOptions(options: SagaOrchestratorOptions): void;
|
|
597
|
-
execute<T = unknown>(steps: SagaStep[], signal?: AbortSignal): Promise<SagaResult<T>>;
|
|
598
|
-
private buildFailure;
|
|
599
|
-
}
|
|
600
|
-
|
|
601
677
|
declare class AppError extends Error {
|
|
602
678
|
readonly statusCode: number;
|
|
603
679
|
readonly status: 'fail' | 'error';
|
|
@@ -667,6 +743,8 @@ interface CompiledRoute {
|
|
|
667
743
|
controllerClass: any;
|
|
668
744
|
methodName: string;
|
|
669
745
|
guardClasses: GuardClass[];
|
|
746
|
+
interceptorRefs: InterceptorRef[];
|
|
747
|
+
middlewareRefs: MiddlewareRef$1[];
|
|
670
748
|
rawPath: string;
|
|
671
749
|
}
|
|
672
750
|
interface RouteMatch {
|
|
@@ -695,7 +773,7 @@ declare class ControllerRouter {
|
|
|
695
773
|
|
|
696
774
|
/** Async-capable function that extracts the auth payload from the execution context. */
|
|
697
775
|
type AuthExtractorFn<T = unknown> = (ctx: ExecutionContext) => T | Promise<T>;
|
|
698
|
-
type RouteParamType = 'query' | 'param' | 'body' | 'rawBody' | 'formData' | 'headers' | 'cookie' | 'ip' | 'userAgent' | 'auth';
|
|
776
|
+
type RouteParamType = 'query' | 'param' | 'body' | 'rawBody' | 'formData' | 'headers' | 'cookie' | 'ip' | 'userAgent' | 'auth' | 'custom';
|
|
699
777
|
interface RouteParamMetadata {
|
|
700
778
|
index: number;
|
|
701
779
|
type: RouteParamType;
|
|
@@ -808,9 +886,59 @@ declare function defineAuth<_T = unknown>(extractor?: AuthExtractorFn<_T>): () =
|
|
|
808
886
|
* Use `defineAuth<YourPayload>()` in your project to get a typed version.
|
|
809
887
|
*/
|
|
810
888
|
declare const Auth: () => ParameterDecorator;
|
|
889
|
+
/**
|
|
890
|
+
* Factory for custom parameter decorators with a user-supplied async extractor.
|
|
891
|
+
*
|
|
892
|
+
* The returned function is a zero-argument decorator factory — call it with `()` at the use site.
|
|
893
|
+
*
|
|
894
|
+
* @example
|
|
895
|
+
* // Define once:
|
|
896
|
+
* const CurrentUser = createParamDecorator<IUser>(async (ctx) => {
|
|
897
|
+
* const payload = ctx.getAuth<{ id: string }>()
|
|
898
|
+
* if (!payload) throw new UnauthorizedError()
|
|
899
|
+
* return userService.findById(payload.id)
|
|
900
|
+
* })
|
|
901
|
+
*
|
|
902
|
+
* // Use in a controller:
|
|
903
|
+
* @Get('/profile')
|
|
904
|
+
* getProfile(@CurrentUser() user: IUser) {}
|
|
905
|
+
*/
|
|
906
|
+
declare function createParamDecorator<T = unknown>(extractor: (ctx: ExecutionContext) => T | Promise<T>): () => ParameterDecorator;
|
|
811
907
|
declare function getRouteParams(controllerClass: Function, methodName: string): RouteParamMetadata[] | null;
|
|
812
908
|
declare function resolveParamArgs(meta: RouteParamMetadata[], ctx: ExecutionContext): Promise<unknown[]>;
|
|
813
909
|
|
|
910
|
+
/**
|
|
911
|
+
* Provides runtime access to registered providers and the DI container.
|
|
912
|
+
*
|
|
913
|
+
* Automatically registered by BackendApplication during init().
|
|
914
|
+
* Used by extension modules (e.g. ScheduleModule) that need to scan
|
|
915
|
+
* all providers for metadata.
|
|
916
|
+
*
|
|
917
|
+
* @example
|
|
918
|
+
* ```typescript
|
|
919
|
+
* @Injectable()
|
|
920
|
+
* @Inject(DiscoveryService)
|
|
921
|
+
* class MyExplorer {
|
|
922
|
+
* constructor(private readonly discovery: DiscoveryService) {}
|
|
923
|
+
*
|
|
924
|
+
* async onApplicationBootstrap() {
|
|
925
|
+
* for (const provider of this.discovery.getProviders()) {
|
|
926
|
+
* // scan for custom metadata
|
|
927
|
+
* }
|
|
928
|
+
* }
|
|
929
|
+
* }
|
|
930
|
+
* ```
|
|
931
|
+
*/
|
|
932
|
+
declare class DiscoveryService {
|
|
933
|
+
private container;
|
|
934
|
+
private providers;
|
|
935
|
+
/** @internal Called by BackendApplication during init. */
|
|
936
|
+
_init(container: Container, providers: Provider[]): void;
|
|
937
|
+
getProviders(): Provider[];
|
|
938
|
+
resolve<T>(token: Token<T>): Promise<T>;
|
|
939
|
+
getProviderClass(provider: Provider): Type | null;
|
|
940
|
+
}
|
|
941
|
+
|
|
814
942
|
interface ApplicationOptions {
|
|
815
943
|
rootModule: Type | DynamicModule;
|
|
816
944
|
globalGuards?: PipelineOptions['guards'];
|
|
@@ -844,6 +972,11 @@ declare class BackendApplication {
|
|
|
844
972
|
* classes placed in `providers: []` (backward compatibility).
|
|
845
973
|
*/
|
|
846
974
|
getControllers(): Type[];
|
|
975
|
+
/**
|
|
976
|
+
* Return all providers registered across all modules.
|
|
977
|
+
* Used by extension packages (e.g. @truxie/schedule) to scan for metadata.
|
|
978
|
+
*/
|
|
979
|
+
getProviders(): Provider[];
|
|
847
980
|
getEventBus(): EventBus;
|
|
848
981
|
createHandler(options: Omit<CreatePipelineOptions, 'handler'> & {
|
|
849
982
|
handler: HandlerFn;
|
|
@@ -853,4 +986,4 @@ declare class BackendApplication {
|
|
|
853
986
|
private ensureInitialized;
|
|
854
987
|
}
|
|
855
988
|
|
|
856
|
-
export { AppError, type ApplicationOptions, Auth, type AuthExtractorFn, BackendApplication, BaseExecutionContext, Body, Catch, type
|
|
989
|
+
export { AppError, type ApplicationOptions, Auth, type AuthExtractorFn, BackendApplication, BaseExecutionContext, Body, Catch, type CompiledRoute, ConfigurableModuleBuilder, type ConfigurableModuleBuilderResult, type ConfigurableModuleClass, ConflictError, Container, Controller, ControllerRouter, Cookie, type CreatePipelineOptions, DefaultValuePipe, Delete, DiscoveryService, DomainEvent, DynamicModule, EventBus, type EventBusOptions, type EventHandler, type ExceptionFilter, type ExecutionContext, type ExtraOptions, type FeatureConfig, type FilterRef, ForbiddenError, FormData, type FormDataPart, ForwardRef, Get, Global, type GuardClass, type GuardInstance, type GuardRef, type HandlerFn, Headers, type HttpMethod, type ICanActivateGuard, type IUseCase, Inject, Injectable, InjectableOptions, type Interceptor, type InterceptorRef, Ip, type Middleware, type MiddlewareRef, Module, ModuleAsyncOptions, ModuleMetadata, ModuleRegistry, NoGuard, NotFoundError, type OnApplicationBootstrap, type OnApplicationShutdown, OnEvent, type OnModuleDestroy, type OnModuleInit, Optional, Param, type ParamPipe, type ParamPipeRef, ParseIdPipe, ParseIntPipe, Patch, type PipeRef, type PipeTransform, type PipelineOptions, Post, Provider, Put, Query, RawBody, RequestAbortedError, RouteGuards, type RouteMatch, type RouteMetadata, type RouteParamMetadata, type RouteParamType, Token, Type, UOW_INSTANCE_KEY, UOW_SESSION_KEY, UnauthorizedError, type UnitOfWork, type UnitOfWorkFactory, UnitOfWorkInterceptor, UseFilters, UseInterceptors, UseMiddleware, UsePipes, UserAgent, ValidationError, ZodParamPipe, ZodValidationPipe, createParamDecorator, createPipeline, defineAuth, forwardRef, getControllerGuards, getControllerPath, getEffectiveInterceptors, getEffectiveMiddlewares, getInterceptorsMetadata, getMethodGuards, getMethodInterceptors, getMethodMiddlewares, getMiddlewaresMetadata, getModuleMetadata, getRouteMetadata, getRouteParams, isGlobalModule, resolveForwardRef, resolveParamArgs };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import'reflect-metadata';var ne=Object.defineProperty;var s=(e,t)=>ne(e,"name",{value:t,configurable:true});var d=(function(e){return e.SINGLETON="singleton",e.REQUEST="request",e.TRANSIENT="transient",e})({}),_=class{static{s(this,"InjectionToken");}description;constructor(t){this.description=t;}toString(){return `InjectionToken(${this.description})`}};var pt=Symbol("injectable"),X=Symbol("inject:param"),ht=Symbol("inject:deps"),tt=Symbol("optional");function M(e){return t=>{Reflect.defineMetadata(pt,{scope:e?.scope??d.SINGLETON},t);}}s(M,"Injectable");function mt(...e){return (t,r,o)=>{if(typeof o=="number"){let n=Reflect.getOwnMetadata(X,t)??new Map;n.set(o,e[0]),Reflect.defineMetadata(X,n,t);}else Reflect.defineMetadata(ht,e,t);}}s(mt,"Inject");function gt(){return (e,t,r)=>{let o=Reflect.getOwnMetadata(tt,e)??new Set;o.add(r),Reflect.defineMetadata(tt,o,e);}}s(gt,"Optional");function N(e){return Reflect.getOwnMetadata(pt,e)}s(N,"getInjectableMetadata");function yt(e){return Reflect.getOwnMetadata(ht,e)??[]}s(yt,"getClassDeps");function wt(e){return Reflect.getOwnMetadata(X,e)??new Map}s(wt,"getInjectTokens");function xt(e){return Reflect.getOwnMetadata(tt,e)??new Set}s(xt,"getOptionalParams");function Et(e){return {forwardRef:e}}s(Et,"forwardRef");function D(e){return typeof e=="object"&&"forwardRef"in e?e.forwardRef():e}s(D,"resolveForwardRef");var b=class e{static{s(this,"Container");}registrations=new Map;resolving=new Set;parent=null;children=[];register(...t){for(let r of t)this.registerOne(r);}registerOne(t){if(typeof t=="function"){let a=N(t)?.scope??d.SINGLETON;this.registrations.set(t,{provider:t,scope:a});return}let r=t.provide,o=d.SINGLETON;if("useClass"in t){let n=N(t.useClass);o=t.scope??n?.scope??d.SINGLETON;}else "useFactory"in t&&(o=d.SINGLETON);this.registrations.set(r,{provider:t,scope:o});}async resolve(t){let r=D(t),o=r!==t?r:t,n=this.registrations.get(o)??this.parent?.findRegistration(o);if(!n)throw new Error(`No provider found for ${et(o)}`);if(n.scope===d.SINGLETON&&n.instance!==void 0||n.scope===d.REQUEST&&this.parent&&n.instance!==void 0)return n.instance;if(this.resolving.has(o))throw new Error(`Circular dependency detected for ${et(o)}`);this.resolving.add(o);try{let a=await this.createInstance(n);return (n.scope===d.SINGLETON||n.scope===d.REQUEST)&&(n.instance=a),a}finally{this.resolving.delete(o);}}has(t){return this.registrations.has(t)||(this.parent?.has(t)??false)}findRegistration(t){return this.registrations.get(t)??this.parent?.findRegistration(t)}createChild(){let t=new e;t.parent=this;for(let[r,o]of this.registrations)o.scope===d.REQUEST&&t.registrations.set(r,{provider:o.provider,scope:d.REQUEST,instance:void 0});return this.children.push(t),t}async dispose(){for(let t of this.children)await t.dispose();this.children=[];for(let[,t]of this.registrations)if(t.instance&&typeof t.instance=="object"&&t.instance!==null){let r=t.instance;typeof r.onModuleDestroy=="function"&&await r.onModuleDestroy();}this.registrations.clear(),this.resolving.clear();}async createInstance(t){let{provider:r}=t;if(typeof r=="function")return this.instantiateClass(r);if("useValue"in r)return r.useValue;if("useClass"in r)return this.instantiateClass(r.useClass);if("useFactory"in r){let o=r,n=[];if(o.inject)for(let a of o.inject)n.push(await this.resolve(a));return o.useFactory(...n)}if("useExisting"in r)return this.resolve(r.useExisting);throw new Error("Unknown provider type")}async instantiateClass(t){let r=Reflect.getMetadata("design:paramtypes",t)??[],o=yt(t),n=wt(t),a=xt(t),i=n.size>0?Math.max(...n.keys())+1:0,c=Math.max(r.length,i,o.length),u=[];for(let f=0;f<c;f++){let l=n.get(f)??o[f]??r[f],p=a.has(f);try{u.push(await this.resolve(l));}catch{if(p)u.push(void 0);else throw new Error(`Cannot resolve parameter at index ${f} (${et(l)}) of ${t.name}`)}}return new t(...u)}};function et(e){return typeof e=="string"?e:typeof e=="symbol"||e instanceof _?e.toString():typeof e=="function"?e.name:String(e)}s(et,"tokenToString");var Rt=Symbol("module");function Mt(e){return t=>{Reflect.defineMetadata(Rt,e,t);}}s(Mt,"Module");function j(e){return Reflect.getOwnMetadata(Rt,e)}s(j,"getModuleMetadata");var bt=Symbol("controller:path"),rt=Symbol("controller:guards"),ot=Symbol("route:metadata"),nt=Symbol("method:route"),T=Symbol("method:guards"),st=Symbol("method:noguard");function vt(e){return t=>{Reflect.defineMetadata(bt,e,t);}}s(vt,"Controller");function O(e){return (t="")=>(r,o,n)=>{let a=n!==void 0,i=String(a?o:o?.name??o),c=a?n?.value:r;if(typeof c=="function"&&(c[nt]={method:e,path:t,methodName:i}),a){let u=Reflect.getOwnMetadata(ot,r.constructor)??[];return u.push({method:e,path:t,methodName:i}),Reflect.defineMetadata(ot,u,r.constructor),n}return r}}s(O,"createMethodDecorator");var At=O("GET"),Pt=O("POST"),St=O("PUT"),Ct=O("DELETE"),Nt=O("PATCH");function Tt(...e){return (t,r,o)=>{if(r==null){Reflect.defineMetadata(rt,e,t);return}if(o!==void 0){if(o?.value){let n=o.value[T]??[];o.value[T]=[...n,...e];}return o}if(typeof t=="function"){let n=t[T]??[];t[T]=[...n,...e];}return typeof t=="function"&&r?.kind==="class"&&Reflect.defineMetadata(rt,e,t),t}}s(Tt,"RouteGuards");function Ot(){return (e,t,r)=>r!==void 0?(r?.value&&(r.value[st]=true),r):(typeof e=="function"&&(e[st]=true),e)}s(Ot,"NoGuard");function v(e){return Reflect.getOwnMetadata(bt,e)}s(v,"getControllerPath");function at(e){return Reflect.getOwnMetadata(rt,e)??[]}s(at,"getControllerGuards");function $(e){let t=[],r=e.prototype;if(r){let o=Object.getOwnPropertyNames(r);for(let n of o){if(n==="constructor")continue;let a=r[n];typeof a=="function"&&a[nt]&&t.push(a[nt]);}}return t.length>0?t:Reflect.getOwnMetadata(ot,e)??[]}s($,"getRouteMetadata");function G(e,t){let o=e.prototype?.[t],n=typeof o=="function"&&o[st]===true,a=typeof o=="function"&&o[T]||[];return n?a:[...at(e),...a]}s(G,"getMethodGuards");var A=class{static{s(this,"ModuleRegistry");}resolved=new Map;sortedModules=[];scan(t){this.resolveModule(t),this.sortedModules=this.topologicalSort();}registerAll(t){let r=new Set;for(let o of this.sortedModules)if(o.global)for(let n of o.providers)r.add(n);r.size>0&&t.register(...r);for(let o of this.sortedModules)if(t.register(...o.providers),o.metadata.imports)for(let n of o.metadata.imports){let a=this.getModuleType(n),i=this.resolved.get(a);if(i)for(let c of i.exports){let u=i.providers.find(f=>typeof f=="function"?f===c:f.provide===c);u&&t.register(u);}}}getAllProviders(){let t=[];for(let r of this.sortedModules)t.push(...r.providers);return t}getAllControllers(){let t=new Set,r=[];for(let o of this.sortedModules){for(let n of o.controllers)t.has(n)||(t.add(n),r.push(n));for(let n of o.metadata.providers??[])typeof n=="function"&&v(n)!==void 0&&!t.has(n)&&(t.add(n),r.push(n));}return r}async callLifecycleHooks(t,r,o){for(let n of this.sortedModules)for(let a of n.providers){let i=typeof a=="function"?a:a.provide;if(t.has(i))try{let c=await t.resolve(i);c&&typeof c=="object"&&typeof c[r]=="function"&&await c[r](o);}catch{}}}resolveModule(t){let r=typeof t=="object"&&"module"in t,o=r?t.module:t;if(this.resolved.has(o))return this.resolved.get(o);let n=j(o)??{},a=r?t:{},i=[...n.controllers??[],...a.controllers??[]],c={imports:[...n.imports??[],...a.imports??[]],controllers:i,providers:[...n.providers??[],...a.providers??[]],exports:[...n.exports??[],...a.exports??[]]},u={type:o,metadata:c,controllers:i,providers:[...i,...c.providers??[]],exports:new Set(c.exports??[]),global:r?t.global??false:false};this.resolved.set(o,u);for(let f of c.imports??[])this.resolveModule(f);return u}getModuleType(t){return typeof t=="object"&&"module"in t?t.module:t}topologicalSort(){let t=new Set,r=new Set,o=[],n=s(a=>{if(t.has(a))return;if(r.has(a))throw new Error(`Circular module dependency detected: ${a.name}`);r.add(a);let i=this.resolved.get(a);if(i){for(let c of i.metadata.imports??[])n(this.getModuleType(c));r.delete(a),t.add(a),o.push(i);}},"visit");for(let[a]of this.resolved)n(a);return o}};var B=class{static{s(this,"BaseExecutionContext");}nativeRequest;handler;container;query;params;body;rawBody;formData;auth;data=new Map;metadata=new Map;abortController;constructor(t,r,o,n={},a={},i){this.nativeRequest=t,this.handler=r,this.container=o,this.query=n,this.params=a,this.abortController=i??new AbortController;}getNativeRequest(){return this.nativeRequest}getHandler(){return this.handler}getBody(){return this.body}setBody(t){this.body=t;}getRawBody(){return this.rawBody}setRawBody(t){this.rawBody=t;}getFormData(){return this.formData}setFormData(t){this.formData=t;}getQuery(){return this.query}getParams(){return this.params}getAuth(){return this.auth}setAuth(t){this.auth=t;}getMetadata(t){return this.metadata.get(t)}setMetadata(t,r){this.metadata.set(t,r);}getData(t){return this.data.get(t)}setData(t,r){this.data.set(t,r);}getContainer(){return this.container}getSignal(){return this.abortController.signal}abort(t){this.abortController.abort(t);}};var It=Symbol("filters"),_t=Symbol("catch");function Dt(...e){return (t,r,o)=>{let n=r?t.constructor:t,a=Reflect.getOwnMetadata(It,n)??[];Reflect.defineMetadata(It,[...a,...e],n);}}s(Dt,"UseFilters");function jt(...e){return t=>{Reflect.defineMetadata(_t,e,t);}}s(jt,"Catch");function it(e){return Reflect.getOwnMetadata(_t,e)??[]}s(it,"getCatchMetadata");var g=class extends Error{static{s(this,"AppError");}statusCode;status;isOperational;constructor(t,r){super(t),this.statusCode=r,this.status=r>=400&&r<500?"fail":"error",this.isOperational=true,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace(this,this.constructor);}},U=class extends g{static{s(this,"NotFoundError");}constructor(t="Resource not found"){super(t,404);}},h=class extends g{static{s(this,"ValidationError");}errors;constructor(t="Validation failed",r){super(t,400),this.errors=r;}},k=class extends g{static{s(this,"UnauthorizedError");}constructor(t="Not authorized"){super(t,401);}},P=class extends g{static{s(this,"ForbiddenError");}constructor(t="Access forbidden"){super(t,403);}},F=class extends g{static{s(this,"ConflictError");}constructor(t="Resource conflict"){super(t,409);}},x=class extends g{static{s(this,"RequestAbortedError");}constructor(t="Request aborted by client"){super(t,499);}};function q(e,t,r){return async o=>{let n=[...t.guards??[],...r.guards??[]],a=[...t.interceptors??[],...r.interceptors??[]],i=[...t.pipes??[],...r.pipes??[]],c=[...t.filters??[],...r.filters??[]],u=await H(e,c);try{R(o);let f=await H(e,n);for(let C of f)if(R(o),!await C.canActivate(o))throw new P("Access denied by guard");R(o);let l=await H(e,i);for(let C of l)R(o),await C.transform(o);R(o);let p=await H(e,a),w=s(async()=>(R(o),r.handler(o)),"handlerCall");return p.length===0?await w():await p.reduceRight((C,dt)=>async()=>(R(o),dt.intercept(o,C)),w)()}catch(f){return se(f,o,u)}}}s(q,"createPipeline");function R(e){if(e.getSignal().aborted)throw new x}s(R,"checkAborted");async function se(e,t,r){for(let o of r){let n=it(o.constructor);if(n.length===0||e instanceof Error&&n.some(i=>e instanceof i))return o.catch(e,t)}throw e}s(se,"handleError");async function H(e,t){let r=[];for(let o of t)typeof o=="function"?r.push(await e.resolve(o)):r.push(o);return r}s(H,"resolveRefs");var $t=Symbol("interceptors");function Gt(...e){return (t,r,o)=>{let n=r?t.constructor:t,a=Reflect.getOwnMetadata($t,n)??[];Reflect.defineMetadata($t,[...a,...e],n);}}s(Gt,"UseInterceptors");var ct="uow:session",ft="uow:instance",L=class{static{s(this,"UnitOfWorkInterceptor");}factory;constructor(t){this.factory=t;}async intercept(t,r){let o=this.factory();await o.start(),t.setData(ct,o.getContext()),t.setData(ft,o);try{let n=await r();return await o.commit(),n}catch(n){throw await o.rollback(),n}}};var Bt=Symbol("pipes");function Ut(...e){return (t,r,o)=>{let n=r?t.constructor:t,a=Reflect.getOwnMetadata(Bt,n)??[];Reflect.defineMetadata(Bt,[...a,...e],n);}}s(Ut,"UsePipes");var z=class{static{s(this,"ZodValidationPipe");}schema;constructor(t){this.schema=t;}transform(t){let r=t.getBody(),o=this.schema.safeParse(r);if(!o.success){let n={};for(let a of o.error.issues){let i=a.path.join(".")||"_root";n[i]||(n[i]=[]),n[i].push(a.message);}throw new h("Validation failed",n)}t.setBody(o.data);}};var ae=/^[0-9a-fA-F]{24}$/,V=class{static{s(this,"ParseIdPipe");}paramName;constructor(t="id"){this.paramName=t;}transform(t){let o=t.getParams()[this.paramName];if(!o||!ae.test(o))throw new h(`Invalid ${this.paramName}: must be a valid ObjectId`)}};var W=class{static{s(this,"ParseIntPipe");}transform(t){let r=Number(t);if(!Number.isInteger(r)||t===""||t===null||t===void 0)throw new h(`Expected an integer, received: ${JSON.stringify(t)}`);return r}};var Q=class{static{s(this,"ZodParamPipe");}schema;constructor(t){this.schema=t;}transform(t){let r=this.schema.safeParse(t);if(!r.success){let o=r.error.errors.map(n=>`${n.path.join(".")}: ${n.message}`).join(", ");throw new h(o)}return r.data}};function kt(e){return {transform(t){return t??e}}}s(kt,"DefaultValuePipe");var Y=class{static{s(this,"DomainEvent");}payload;timestamp;constructor(t){this.payload=t,this.timestamp=Date.now();}};function ie(e,t,r,o){var n=arguments.length,a=n<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,r):o,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(e,t,r,o);else for(var c=e.length-1;c>=0;c--)(i=e[c])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a}s(ie,"_ts_decorate");function Ft(e,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(e,t)}s(Ft,"_ts_metadata");var m=class{static{s(this,"EventBus");}handlers=new Map;onError;constructor(){this.onError=ce;}setOptions(t){t.onError&&(this.onError=t.onError);}subscribe(t,r,o){let n=this.handlers.get(t)??[];n.push({instance:o?.instance??{},methodName:o?.methodName??"anonymous",handler:r}),this.handlers.set(t,n);}registerHandler(t,r,o){let n=r[o].bind(r);this.subscribe(t,n,{instance:r,methodName:o});}async emit(t){let r=this.handlers.get(t.type);if(!r||r.length===0)return;let o=await Promise.allSettled(r.map(n=>n.handler(t)));for(let n=0;n<o.length;n++){let a=o[n];if(a.status==="rejected"){let i=r[n],c=`${i.instance.constructor?.name??"Unknown"}.${i.methodName}`;this.onError(a.reason,t.type,c);}}}emitAsync(t){this.emit(t).catch(()=>{});}hasHandlers(t){let r=this.handlers.get(t);return r!==void 0&&r.length>0}handlerCount(t){return this.handlers.get(t)?.length??0}clear(){this.handlers.clear();}};m=ie([M(),Ft("design:type",Function),Ft("design:paramtypes",[])],m);function ce(e,t,r){console.error(`[EventBus] Handler "${r}" failed for event "${t}":`,e);}s(ce,"defaultErrorHandler");var ut=Symbol("on-event");function Ht(e){return (t,r,o)=>{let n=Reflect.getOwnMetadata(ut,t.constructor)??[];n.push({eventType:e,methodName:String(r)}),Reflect.defineMetadata(ut,n,t.constructor);}}s(Ht,"OnEvent");function qt(e){return Reflect.getOwnMetadata(ut,e)??[]}s(qt,"getOnEventMetadata");function fe(e,t,r,o){var n=arguments.length,a=n<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,r):o,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(e,t,r,o);else for(var c=e.length-1;c>=0;c--)(i=e[c])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a}s(fe,"_ts_decorate");function Lt(e,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(e,t)}s(Lt,"_ts_metadata");var S=class{static{s(this,"SagaOrchestrator");}onCompensationError;constructor(){this.onCompensationError=ue;}setOptions(t){t.onCompensationError&&(this.onCompensationError=t.onCompensationError);}async execute(t,r){let o=[],n={};for(let i of t){if(r?.aborted)return this.buildFailure(new x,i.name,o,n);try{let c=await i.execute(r);o.push({step:i,result:c}),n[i.name]=c;}catch(c){return this.buildFailure(c,i.name,o,n)}}let a=o.length>0?o[o.length-1].result:void 0;return {success:true,results:n,value:a,compensated:[],compensationErrors:{}}}async buildFailure(t,r,o,n){let a=[],i={};for(let c=o.length-1;c>=0;c--){let{step:u,result:f}=o[c];if(u.compensate)try{await u.compensate(f),a.push(u.name);}catch(l){i[u.name]=l,this.onCompensationError(u.name,l);}}return {success:false,results:n,error:t,failedStep:r,compensated:a,compensationErrors:i}}};S=fe([M(),Lt("design:type",Function),Lt("design:paramtypes",[])],S);function ue(e,t){console.error(`[Saga] Compensation failed for step "${e}":`,t);}s(ue,"defaultCompensationErrorHandler");var J=class{static{s(this,"ControllerRouter");}routes=[];globalPrefix;constructor(t=""){this.globalPrefix=t;}register(...t){for(let r of t){let o=v(r)??"",n=$(r);for(let a of n){let i=le(`${this.globalPrefix}/${o}/${a.path}`);he(i,r.name,a.methodName),this.checkDuplicate(i,a.method,r.name,a.methodName);let{pattern:c,paramNames:u}=de(i),f=G(r,a.methodName);this.routes.push({method:a.method,pattern:c,paramNames:u,controllerClass:r,methodName:a.methodName,guardClasses:f,rawPath:i});}}}checkDuplicate(t,r,o,n){let a=this.routes.find(i=>i.method===r&&i.rawPath===t);if(a)throw new Error(`Duplicate route: ${r} ${t}
|
|
2
|
-
Already registered by: ${
|
|
3
|
-
Conflicting with: ${
|
|
1
|
+
import {c as c$2,e as e$1,g as g$1}from'./chunk-XVPJFMLQ.js';export{a as AppError,f as ConflictError,e as ForbiddenError,b as NotFoundError,g as RequestAbortedError,d as UnauthorizedError,c as ValidationError}from'./chunk-XVPJFMLQ.js';import {c as c$1,d,e}from'./chunk-F5KXBDV2.js';export{e as DiscoveryService,b as Global,a as Module,c as getModuleMetadata,d as isGlobalModule}from'./chunk-F5KXBDV2.js';import {a,g,b as b$1,h as h$1,i,j as j$1,c,d as d$1}from'./chunk-RMR6UXWO.js';export{e as Inject,d as Injectable,f as Optional,b as Scope}from'./chunk-RMR6UXWO.js';import'reflect-metadata';function Ne(o){return {forwardRef:o}}a(Ne,"forwardRef");function U(o){return typeof o=="object"&&"forwardRef"in o?o.forwardRef():o}a(U,"resolveForwardRef");var E=class o{static{a(this,"Container");}registrations=new Map;resolving=new Set;parent=null;children=[];register(...e){for(let t of e)this.registerOne(t);}registerOne(e){if(typeof e=="function"){let s=g(e)?.scope??b$1.SINGLETON;this.registrations.set(e,{provider:e,scope:s});return}let t=e.provide,r=b$1.SINGLETON;if("useClass"in e){let n=g(e.useClass);r=e.scope??n?.scope??b$1.SINGLETON;}else "useFactory"in e&&(r=e.scope??b$1.SINGLETON);this.registrations.set(t,{provider:e,scope:r});}async resolve(e){let t=U(e),r=t!==e?t:e,n=this.registrations.get(r)??this.parent?.findRegistration(r);if(!n)throw new Error(`No provider found for ${ee(r)}`);if(n.scope===b$1.SINGLETON&&n.instance!==void 0||n.scope===b$1.REQUEST&&this.parent!==null&&n.instance!==void 0)return n.instance;if(this.resolving.has(r))throw new Error(`Circular dependency detected for ${ee(r)}`);this.resolving.add(r);try{let s=await this.createInstance(n);return (n.scope===b$1.SINGLETON||n.scope===b$1.REQUEST&&this.parent!==null)&&(n.instance=s),s}finally{this.resolving.delete(r);}}has(e){return this.registrations.has(e)||(this.parent?.has(e)??false)}findRegistration(e){return this.registrations.get(e)??this.parent?.findRegistration(e)}createChild(){let e=new o;e.parent=this;for(let[t,r]of this.registrations)r.scope===b$1.REQUEST&&e.registrations.set(t,{provider:r.provider,scope:b$1.REQUEST,instance:void 0});return this.children.push(e),e}async dispose(){for(let e of this.children)await e.dispose();this.children=[];for(let[,e]of this.registrations)if(e.instance&&typeof e.instance=="object"&&e.instance!==null){let t=e.instance;typeof t.onModuleDestroy=="function"&&await t.onModuleDestroy();}this.registrations.clear(),this.resolving.clear();}async createInstance(e){let{provider:t}=e;if(typeof t=="function")return this.instantiateClass(t);if("useValue"in t)return t.useValue;if("useClass"in t)return this.instantiateClass(t.useClass);if("useFactory"in t){let r=t,n=[];if(r.inject)for(let s of r.inject)n.push(await this.resolve(s));return r.useFactory(...n)}if("useExisting"in t)return this.resolve(t.useExisting);throw new Error("Unknown provider type")}async instantiateClass(e){let t=Reflect.getMetadata("design:paramtypes",e)??[],r=h$1(e),n=i(e),s=j$1(e),a=n.size>0?Math.max(...n.keys())+1:0,c=Math.max(t.length,a,r.length),f=[];for(let d=0;d<c;d++){let u=n.get(d)??r[d]??t[d],l=s.has(d);try{f.push(await this.resolve(u));}catch{if(l)f.push(void 0);else throw new Error(`Cannot resolve parameter at index ${d} (${ee(u)}) of ${e.name}`)}}return new e(...f)}};function ee(o){return typeof o=="string"?o:typeof o=="symbol"||o instanceof c?o.toString():typeof o=="function"?o.name:String(o)}a(ee,"tokenToString");var De=Symbol("controller:path"),te=Symbol("controller:guards"),re=Symbol("route:metadata"),oe=Symbol("method:route"),S=Symbol("method:guards"),ne=Symbol("method:noguard");function Fe(o){return e=>{Reflect.defineMetadata(De,o,e);}}a(Fe,"Controller");function I(o){return (e="")=>(t,r,n)=>{let s=n!==void 0,a=String(s?r:r?.name??r),c=s?n?.value:t;if(typeof c=="function"&&(c[oe]={method:o,path:e,methodName:a}),s){let f=Reflect.getOwnMetadata(re,t.constructor)??[];return f.push({method:o,path:e,methodName:a}),Reflect.defineMetadata(re,f,t.constructor),n}return t}}a(I,"createMethodDecorator");var Oe=I("GET"),_e=I("POST"),ke=I("PUT"),Ue=I("DELETE"),$e=I("PATCH");function Ge(...o){return (e,t,r)=>{if(t==null){Reflect.defineMetadata(te,o,e);return}if(r!==void 0){if(r?.value){let n=r.value[S]??[];r.value[S]=[...n,...o];}return r}if(typeof e=="function"){let n=e[S]??[];e[S]=[...n,...o];}return typeof e=="function"&&t?.kind==="class"&&Reflect.defineMetadata(te,o,e),e}}a(Ge,"RouteGuards");function Be(){return (o,e,t)=>t!==void 0?(t?.value&&(t.value[ne]=true),t):(typeof o=="function"&&(o[ne]=true),o)}a(Be,"NoGuard");function M(o){return Reflect.getOwnMetadata(De,o)}a(M,"getControllerPath");function se(o){return Reflect.getOwnMetadata(te,o)??[]}a(se,"getControllerGuards");function $(o){let e=[],t=o.prototype;if(t){let r=Object.getOwnPropertyNames(t);for(let n of r){if(n==="constructor")continue;let s=t[n];typeof s=="function"&&s[oe]&&e.push(s[oe]);}}return e.length>0?e:Reflect.getOwnMetadata(re,o)??[]}a($,"getRouteMetadata");function G(o,e){let r=o.prototype?.[e],n=typeof r=="function"&&r[ne]===true,s=typeof r=="function"&&r[S]||[];return n?s:[...se(o),...s]}a(G,"getMethodGuards");var b=class{static{a(this,"ModuleRegistry");}resolved=new Map;sortedModules=[];scan(e){this.resolveModule(e),this.sortedModules=this.topologicalSort(),this.validateExports();}registerAll(e){let t=new Set;for(let r of this.sortedModules)if(r.global)for(let n of r.providers)t.add(n);t.size>0&&e.register(...t);for(let r of this.sortedModules){e.register(...r.providers);for(let n of r.metadata.imports??[]){let s=this.getModuleType(n),a=this.resolved.get(s);if(a)for(let c of a.exports){let f=this.findProvider(a,c)??this.findReExportedProvider(a,c);f&&e.register(f);}}}}getAllProviders(){let e=[];for(let t of this.sortedModules)e.push(...t.providers);return e}getAllControllers(){let e=new Set,t=[];for(let r of this.sortedModules){for(let n of r.controllers)e.has(n)||(e.add(n),t.push(n));for(let n of r.metadata.providers??[])typeof n=="function"&&M(n)!==void 0&&!e.has(n)&&(e.add(n),t.push(n));}return t}async callLifecycleHooks(e,t,r){for(let n of this.sortedModules)for(let s of n.providers){let a=typeof s=="function"?s:s.provide;if(e.has(a))try{let c=await e.resolve(a);c&&typeof c=="object"&&typeof c[t]=="function"&&await c[t](r);}catch{}}}resolveModule(e){let t=typeof e=="object"&&"module"in e,r=t?e.module:e;if(this.resolved.has(r))return this.resolved.get(r);let n=c$1(r)??{},s=t?e:{},a=[...n.controllers??[],...s.controllers??[]],c={imports:[...n.imports??[],...s.imports??[]],controllers:a,providers:[...n.providers??[],...s.providers??[]],exports:[...n.exports??[],...s.exports??[]]},f={type:r,metadata:c,controllers:a,providers:[...a,...c.providers??[]],exports:new Set(c.exports??[]),global:t?e.global??d(r):d(r)};this.resolved.set(r,f);for(let d of c.imports??[])this.resolveModule(d);return f}getVisibleTokens(e){let t=new Set;for(let r of e.providers)t.add(this.getProviderToken(r));for(let r of e.metadata.imports??[]){let n=this.getModuleType(r),s=this.resolved.get(n);if(s)for(let a of s.exports)t.add(a);}for(let r of this.sortedModules)if(r.global)for(let n of r.providers)t.add(this.getProviderToken(n));return t}validateExports(){for(let e of this.sortedModules){let t=new Set(e.providers.map(n=>this.getProviderToken(n))),r=this.collectImportedExports(e);for(let n of e.exports)if(!t.has(n)&&!r.has(n)){let s=typeof n=="function"?n.name:String(n);throw new Error(`${e.type.name} exports ${s} but it is not in its providers and is not re-exported from an imported module`)}}}validateVisibility(){for(let e of this.sortedModules){let t=this.getVisibleTokens(e);for(let r of e.providers){if(typeof r!="function")continue;let n=h$1(r);for(let s of n)if(!t.has(s)){let a=typeof s=="function"?s.name:String(s);throw new Error(`${e.type.name}: ${r.name} depends on ${a}, but it is not provided in this module and not exported by any imported module`)}}}}getProviderToken(e){return typeof e=="function"?e:e.provide}collectImportedExports(e){let t=new Set;for(let r of e.metadata.imports??[]){let n=this.getModuleType(r),s=this.resolved.get(n);if(s)for(let a of s.exports)t.add(a);}return t}findProvider(e,t){return e.providers.find(r=>typeof r=="function"?r===t:r.provide===t)}findReExportedProvider(e,t){for(let r of e.metadata.imports??[]){let n=this.getModuleType(r),s=this.resolved.get(n);if(!s||!s.exports.has(t))continue;let a=this.findProvider(s,t);if(a)return a;let c=this.findReExportedProvider(s,t);if(c)return c}}getModuleType(e){return typeof e=="object"&&"module"in e?e.module:e}topologicalSort(){let e=new Set,t=new Set,r=[],n=a(s=>{if(e.has(s))return;if(t.has(s))throw new Error(`Circular module dependency detected: ${s.name}`);t.add(s);let a=this.resolved.get(s);if(a){for(let c of a.metadata.imports??[])n(this.getModuleType(c));t.delete(s),e.add(s),r.push(a);}},"visit");for(let[s]of this.resolved)n(s);return r}};function ht(o,e){if("useFactory"in e&&e.useFactory){let t=e.useFactory;return [{provide:o,useFactory:t,inject:e.inject??[]}]}if("useClass"in e&&e.useClass){let t=e.useClass;return [{provide:o,useFactory:a(async r=>r.createModuleOptions(),"useFactory"),inject:[t]},t]}if("useExisting"in e&&e.useExisting){let t=e.useExisting;return [{provide:o,useFactory:a(async r=>r.createModuleOptions(),"useFactory"),inject:[t]}]}throw new Error("ModuleAsyncOptions must specify one of: useFactory, useClass, or useExisting")}a(ht,"createAsyncProviders");var B=class{static{a(this,"ConfigurableModuleBuilder");}description;featureDescription;onForRoot;onForFeature;constructor(e="MODULE_OPTIONS"){this.description=e,this.featureDescription=e+"_FEATURE";}setTokenDescription(e){return this.description=e,this}transformDynamicModule(e){return this.onForRoot=e,this}transformFeatureModule(e){return this.onForFeature=e,this}build(){let e=new c(this.description),t=new c(this.featureDescription),r=this.onForRoot,n=this.onForFeature;return {ConfigurableModuleClass:class{static{a(this,"ConfigurableModuleClassImpl");}static forRoot(c,f={}){let d={module:this,global:f.global??false,providers:[{provide:e,useValue:c}],exports:[e]};return r&&(d=r(d,c)),d}static forRootAsync(c){let f=ht(e,c);return {module:this,imports:c.imports??[],providers:f,exports:[e]}}static forFeature(c,f={}){let d={module:this,global:f.global??false,providers:[{provide:t,useValue:c}],exports:[t]};return n&&(d=n(d,c)),d}},MODULE_OPTIONS_TOKEN:e,MODULE_FEATURE_TOKEN:t}}};var j=class{static{a(this,"BaseExecutionContext");}nativeRequest;handler;container;query;params;body;rawBody;formData;auth;data=new Map;metadata=new Map;abortController;constructor(e,t,r,n={},s={},a){this.nativeRequest=e,this.handler=t,this.container=r,this.query=n,this.params=s,this.abortController=a??new AbortController;}getNativeRequest(){return this.nativeRequest}getHandler(){return this.handler}getBody(){return this.body}setBody(e){this.body=e;}getRawBody(){return this.rawBody}setRawBody(e){this.rawBody=e;}getFormData(){return this.formData}setFormData(e){this.formData=e;}getQuery(){return this.query}getParams(){return this.params}getAuth(){return this.auth}setAuth(e){this.auth=e;}getMetadata(e){return this.metadata.get(e)}setMetadata(e,t){this.metadata.set(e,t);}getData(e){return this.data.get(e)}setData(e,t){this.data.set(e,t);}getContainer(){return this.container}getSignal(){return this.abortController.signal}abort(e){this.abortController.abort(e);}};var je=Symbol("filters"),He=Symbol("catch");function Le(...o){return (e,t,r)=>{let n=t?e.constructor:e,s=Reflect.getOwnMetadata(je,n)??[];Reflect.defineMetadata(je,[...s,...o],n);}}a(Le,"UseFilters");function qe(...o){return e=>{Reflect.defineMetadata(He,o,e);}}a(qe,"Catch");function ie(o){return Reflect.getOwnMetadata(He,o)??[]}a(ie,"getCatchMetadata");function H(o,e,t){return async r=>{let n=[...e.middlewares??[],...t.middlewares??[]],s=[...e.guards??[],...t.guards??[]],a$1=[...e.interceptors??[],...t.interceptors??[]],c=[...e.pipes??[],...t.pipes??[]],f=[...e.filters??[],...t.filters??[]],d=await N(o,f);try{w(r);let u=await N(o,n);return await mt(r,u,async()=>{w(r);let l=await N(o,s);for(let R of l)if(w(r),!await R.canActivate(r))throw new e$1("Access denied by guard");w(r);let v=await N(o,c);for(let R of v)w(r),await R.transform(r);w(r);let g=await N(o,a$1),ve=a(async()=>(w(r),t.handler(r)),"handlerCall");return g.length===0?ve():g.reduceRight((R,xe)=>async()=>(w(r),xe.intercept(r,R)),ve)()})}catch(u){return gt(u,r,d)}}}a(H,"createPipeline");async function mt(o,e,t){return e.length===0?t():e.reduceRight((n,s)=>()=>s.use(o,n),t)()}a(mt,"runMiddlewareChain");function w(o){if(o.getSignal().aborted)throw new g$1}a(w,"checkAborted");async function gt(o,e,t){for(let r of t){let n=ie(r.constructor);if(n.length===0||o instanceof Error&&n.some(a=>o instanceof a))return r.catch(o,e)}throw o}a(gt,"handleError");async function N(o,e){let t=[];for(let r of e)typeof r=="function"?t.push(await o.resolve(r)):t.push(r);return t}a(N,"resolveRefs");var ae=Symbol("interceptors"),ce=Symbol("method:interceptors");function Ve(...o){return (e,t,r)=>{if(t!==void 0){let s=r?.value??e,a=s[ce]??[];return s[ce]=[...a,...o],r}let n=Reflect.getOwnMetadata(ae,e)??[];Reflect.defineMetadata(ae,[...n,...o],e);}}a(Ve,"UseInterceptors");function de(o){return Reflect.getOwnMetadata(ae,o)??[]}a(de,"getInterceptorsMetadata");function fe(o,e){let r=o.prototype?.[e];return typeof r=="function"&&r[ce]||[]}a(fe,"getMethodInterceptors");function L(o,e){return [...de(o),...fe(o,e)]}a(L,"getEffectiveInterceptors");var ue="uow:session",le="uow:instance",q=class{static{a(this,"UnitOfWorkInterceptor");}factory;constructor(e){this.factory=e;}async intercept(e,t){let r=this.factory();await r.start(),e.setData(ue,r.getContext()),e.setData(le,r);try{let n=await t();return await r.commit(),n}catch(n){throw await r.rollback(),n}}};var pe=Symbol("middlewares"),he=Symbol("method:middlewares");function ze(...o){return (e,t,r)=>{if(t!==void 0){let s=r?.value??e,a=s[he]??[];return s[he]=[...a,...o],r}let n=Reflect.getOwnMetadata(pe,e)??[];Reflect.defineMetadata(pe,[...n,...o],e);}}a(ze,"UseMiddleware");function me(o){return Reflect.getOwnMetadata(pe,o)??[]}a(me,"getMiddlewaresMetadata");function ge(o,e){let r=o.prototype?.[e];return typeof r=="function"&&r[he]||[]}a(ge,"getMethodMiddlewares");function V(o,e){return [...me(o),...ge(o,e)]}a(V,"getEffectiveMiddlewares");var We=Symbol("pipes");function Qe(...o){return (e,t,r)=>{let n=t?e.constructor:e,s=Reflect.getOwnMetadata(We,n)??[];Reflect.defineMetadata(We,[...s,...o],n);}}a(Qe,"UsePipes");var z=class{static{a(this,"ZodValidationPipe");}schema;constructor(e){this.schema=e;}transform(e){let t=e.getBody(),r=this.schema.safeParse(t);if(!r.success){let n={};for(let s of r.error.issues){let a=s.path.join(".")||"_root";n[a]||(n[a]=[]),n[a].push(s.message);}throw new c$2("Validation failed",n)}e.setBody(r.data);}};var yt=/^[0-9a-fA-F]{24}$/,W=class{static{a(this,"ParseIdPipe");}paramName;constructor(e="id"){this.paramName=e;}transform(e){let r=e.getParams()[this.paramName];if(!r||!yt.test(r))throw new c$2(`Invalid ${this.paramName}: must be a valid ObjectId`)}};var Q=class{static{a(this,"ParseIntPipe");}transform(e){let t=Number(e);if(!Number.isInteger(t)||e===""||e===null||e===void 0)throw new c$2(`Expected an integer, received: ${JSON.stringify(e)}`);return t}};var Y=class{static{a(this,"ZodParamPipe");}schema;constructor(e){this.schema=e;}transform(e){let t=this.schema.safeParse(e);if(!t.success){let r=t.error.errors.map(n=>`${n.path.join(".")}: ${n.message}`).join(", ");throw new c$2(r)}return t.data}};function Ye(o){return {transform(e){return e??o}}}a(Ye,"DefaultValuePipe");var Z=class{static{a(this,"DomainEvent");}payload;timestamp;constructor(e){this.payload=e,this.timestamp=Date.now();}};function wt(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var c=o.length-1;c>=0;c--)(a=o[c])&&(s=(n<3?a(s):n>3?a(e,t,s):a(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}a(wt,"_ts_decorate");function Ze(o,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,e)}a(Ze,"_ts_metadata");var h=class{static{a(this,"EventBus");}handlers=new Map;onError;constructor(){this.onError=vt;}setOptions(e){e.onError&&(this.onError=e.onError);}subscribe(e,t,r){let n=this.handlers.get(e)??[];n.push({instance:r?.instance??{},methodName:r?.methodName??"anonymous",handler:t}),this.handlers.set(e,n);}registerHandler(e,t,r){let n=t[r].bind(t);this.subscribe(e,n,{instance:t,methodName:r});}async emit(e){let t=this.handlers.get(e.type);if(!t||t.length===0)return;let r=await Promise.allSettled(t.map(n=>n.handler(e)));for(let n=0;n<r.length;n++){let s=r[n];if(s.status==="rejected"){let a=t[n],c=`${a.instance.constructor?.name??"Unknown"}.${a.methodName}`;this.onError(s.reason,e.type,c);}}}emitAsync(e){this.emit(e).catch(()=>{});}hasHandlers(e){let t=this.handlers.get(e);return t!==void 0&&t.length>0}handlerCount(e){return this.handlers.get(e)?.length??0}clear(){this.handlers.clear();}};h=wt([d$1(),Ze("design:type",Function),Ze("design:paramtypes",[])],h);function vt(o,e,t){console.error(`[EventBus] Handler "${t}" failed for event "${e}":`,o);}a(vt,"defaultErrorHandler");var ye=Symbol("on-event");function Je(o){return (e,t,r)=>{let n=Reflect.getOwnMetadata(ye,e.constructor)??[];n.push({eventType:o,methodName:String(t)}),Reflect.defineMetadata(ye,n,e.constructor);}}a(Je,"OnEvent");function Ke(o){return Reflect.getOwnMetadata(ye,o)??[]}a(Ke,"getOnEventMetadata");var J=class{static{a(this,"ControllerRouter");}routes=[];globalPrefix;constructor(e=""){this.globalPrefix=e;}register(...e){for(let t of e){let r=M(t)??"",n=$(t);for(let s of n){let a=xt(`${this.globalPrefix}/${r}/${s.path}`);bt(a,t.name,s.methodName),this.checkDuplicate(a,s.method,t.name,s.methodName);let{pattern:c,paramNames:f}=Et(a),d=G(t,s.methodName),u=L(t,s.methodName),l=V(t,s.methodName);this.routes.push({method:s.method,pattern:c,paramNames:f,controllerClass:t,methodName:s.methodName,guardClasses:d,interceptorRefs:u,middlewareRefs:l,rawPath:a});}}this.routes.sort((t,r)=>Xe(t.rawPath)-Xe(r.rawPath));}checkDuplicate(e,t,r,n){let s=this.routes.find(a=>a.method===t&&a.rawPath===e);if(s)throw new Error(`Duplicate route: ${t} ${e}
|
|
2
|
+
Already registered by: ${s.controllerClass.name}.${s.methodName}
|
|
3
|
+
Conflicting with: ${r}.${n}`)}match(e,t){let r=e.toUpperCase();for(let n of this.routes){if(n.method!==r)continue;let s=n.pattern.exec(t);if(!s)continue;let a={};for(let c=0;c<n.paramNames.length;c++)a[n.paramNames[c]]=s[c+1]??"";return {route:n,params:a}}return null}getRoutes(){return this.routes}};function xt(o){return "/"+o.replace(/\/+/g,"/").replace(/^\/|\/$/g,"")}a(xt,"normalizePath");function Et(o){let e=[],t=o.split("/").map(r=>r.startsWith(":")?(e.push(r.slice(1)),"([^/]+)"):Mt(r)).join("/");return {pattern:new RegExp(`^${t}$`),paramNames:e}}a(Et,"compilePath");function Mt(o){return o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(Mt,"escapeRegex");function Xe(o){return o.split("/").filter(Boolean).reduce((e,t)=>e+(t.startsWith(":")?1:0),0)}a(Xe,"routePriority");function bt(o,e,t){let r=`Invalid path "${o}" on ${e}.${t}:`;if(!o.startsWith("/"))throw new Error(`${r} must start with /`);let n=o.split("/").filter((a,c)=>c>0),s=new Set;for(let a of n){if(a==="")throw new Error(`${r} contains empty segment (double slash)`);if(a.startsWith(":")){let c=a.slice(1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(c))throw new Error(`${r} invalid param name ":${c}" \u2014 must be a valid identifier`);if(s.has(c))throw new Error(`${r} duplicate param name ":${c}"`);s.add(c);}}}a(bt,"validatePath");var x=Symbol("route:params");function Rt(o){return o==null?false:typeof o=="function"||typeof o=="object"&&typeof o.transform=="function"}a(Rt,"isParamPipeRef");function K(o,e){return Rt(o)?{key:void 0,pipes:[o,...e??[]]}:{key:o,pipes:e??[]}}a(K,"resolveArgs");function y(o,e,t=[]){return (r,n,s)=>{if(n===void 0)return;let a=r[n];if(typeof a!="function")return;let c=a[x]??[];a[x]=[...c,{index:s,type:o,key:e,pipes:t.length>0?t:void 0}];}}a(y,"buildBuiltinDecorator");function Pt(o){return typeof o=="function"?new o:o}a(Pt,"resolveParamPipe");function et(o,...e){let{key:t,pipes:r}=K(o,e);return y("query",t,r)}a(et,"Query");function tt(o,...e){let{key:t,pipes:r}=K(o,e);return y("param",t,r)}a(tt,"Param");function rt(o,...e){let{key:t,pipes:r}=K(o,e);return y("body",t,r)}a(rt,"Body");var ot=a(()=>y("rawBody"),"RawBody"),nt=a(()=>y("formData"),"FormData"),st=a(()=>y("ip"),"Ip"),it=a(()=>y("userAgent"),"UserAgent"),at=a(o=>y("cookie",o),"Cookie");function ct(o,...e){let{key:t,pipes:r}=K(o,e);return y("headers",t,r)}a(ct,"Headers");function we(o){return ()=>(e,t,r)=>{if(t===void 0)return;let n=e[t];if(typeof n!="function")return;let s=n[x]??[];n[x]=[...s,{index:r,type:"auth",extractor:o}];}}a(we,"defineAuth");var dt=we();function ft(o){return ()=>(e,t,r)=>{if(t===void 0)return;let n=e[t];if(typeof n!="function")return;let s=n[x]??[];n[x]=[...s,{index:r,type:"custom",extractor:o}];}}a(ft,"createParamDecorator");function ut(o,e){let t=o.prototype[e];if(typeof t!="function")return null;let r=t[x];return r&&r.length>0?r:null}a(ut,"getRouteParams");async function lt(o,e){let t=Math.max(...o.map(n=>n.index)),r=new Array(t+1).fill(void 0);for(let{index:n,type:s,key:a,pipes:c,extractor:f}of o){let d;switch(s){case "query":{let u=e.getQuery();d=a!==void 0?u[a]:u;break}case "param":{let u=e.getParams();d=a!==void 0?u[a]:u;break}case "body":{let u=e.getBody()??{};d=a!==void 0?u[a]:u;break}case "rawBody":{d=e.getRawBody();break}case "formData":{d=e.getFormData();break}case "headers":{let u=e.getNativeRequest(),l=u?.node?.req?.headers??u?.headers??{};d=a!==void 0?l[a.toLowerCase()]:l;break}case "cookie":{let u=e.getNativeRequest(),l=u?.node?.req?.headers?.cookie??u?.headers?.cookie??"";if(a&&l){let v=l.split(";").map(g=>g.trim()).find(g=>g.startsWith(a+"="));d=v?decodeURIComponent(v.slice(a.length+1)):void 0;}else d=void 0;break}case "ip":{let u=e.getNativeRequest(),l=u?.node?.req?.headers??{},v=l["cf-connecting-ip"];if(v){d=v.trim();break}let g=l["x-forwarded-for"];if(g){d=(String(g).split(",")[0]??"").trim();break}d=u?.node?.req?.socket?.remoteAddress??"";break}case "userAgent":{d=(e.getNativeRequest()?.node?.req?.headers??{})["user-agent"]??"";break}case "auth":{d=f?await f(e):e.getAuth();break}case "custom":{d=f?await f(e):void 0;break}}if(c&&c.length>0)for(let u of c)d=Pt(u).transform(d);r[n]=d;}return r}a(lt,"resolveParamArgs");async function pt(o,e){let t=await o.resolve(h);for(let r of e){let n=Ct(r);if(!n)continue;let s=Ke(n);if(s.length===0)continue;let a=typeof r=="function"?r:r.provide,c;try{c=await o.resolve(a);}catch{continue}for(let f of s)typeof c[f.methodName]=="function"&&t.registerHandler(f.eventType,c,f.methodName);}}a(pt,"scanEventHandlers");function Ct(o){return typeof o=="function"?g(o)?o:null:"useClass"in o?o.useClass:null}a(Ct,"getProviderClass");var X=class{static{a(this,"BackendApplication");}container;registry;initialized=false;options;eventBus;prefix="";constructor(e){this.options=e,this.container=new E,this.registry=new b;}async init(){if(this.initialized)return;this.eventBus=new h,this.options.eventBus&&this.eventBus.setOptions(this.options.eventBus),this.container.register({provide:h,useValue:this.eventBus});let e$1=new e;this.container.register({provide:e,useValue:e$1}),this.registry.scan(this.options.rootModule),this.registry.registerAll(this.container);let t=this.registry.getAllProviders();e$1._init(this.container,t),await this.registry.callLifecycleHooks(this.container,"onModuleInit"),await pt(this.container,t),await this.registry.callLifecycleHooks(this.container,"onApplicationBootstrap"),this.initialized=true;}setGlobalPrefix(e){return this.prefix=e,this}getGlobalPrefix(){return this.prefix}async resolve(e){return this.ensureInitialized(),this.container.resolve(e)}has(e){return this.container.has(e)}getContainer(){return this.container}getControllers(){return this.ensureInitialized(),this.registry.getAllControllers()}getProviders(){return this.ensureInitialized(),this.registry.getAllProviders()}getEventBus(){return this.ensureInitialized(),this.eventBus}createHandler(e){return this.ensureInitialized(),H(this.container,this.getGlobalOptions(),e)}async shutdown(){this.initialized&&(await this.registry.callLifecycleHooks(this.container,"onModuleDestroy"),await this.registry.callLifecycleHooks(this.container,"onApplicationShutdown"),this.eventBus.clear(),await this.container.dispose(),this.initialized=false);}getGlobalOptions(){return {guards:this.options.globalGuards,interceptors:this.options.globalInterceptors,pipes:this.options.globalPipes,filters:this.options.globalFilters}}ensureInitialized(){if(!this.initialized)throw new Error("BackendApplication not initialized. Call init() first.")}};export{dt as Auth,X as BackendApplication,j as BaseExecutionContext,rt as Body,qe as Catch,B as ConfigurableModuleBuilder,E as Container,Fe as Controller,J as ControllerRouter,at as Cookie,Ye as DefaultValuePipe,Ue as Delete,Z as DomainEvent,h as EventBus,nt as FormData,Oe as Get,ct as Headers,st as Ip,b as ModuleRegistry,Be as NoGuard,Je as OnEvent,tt as Param,W as ParseIdPipe,Q as ParseIntPipe,$e as Patch,_e as Post,ke as Put,et as Query,ot as RawBody,Ge as RouteGuards,le as UOW_INSTANCE_KEY,ue as UOW_SESSION_KEY,q as UnitOfWorkInterceptor,Le as UseFilters,Ve as UseInterceptors,ze as UseMiddleware,Qe as UsePipes,it as UserAgent,Y as ZodParamPipe,z as ZodValidationPipe,ft as createParamDecorator,H as createPipeline,we as defineAuth,Ne as forwardRef,se as getControllerGuards,M as getControllerPath,L as getEffectiveInterceptors,V as getEffectiveMiddlewares,de as getInterceptorsMetadata,G as getMethodGuards,fe as getMethodInterceptors,ge as getMethodMiddlewares,me as getMiddlewaresMetadata,$ as getRouteMetadata,ut as getRouteParams,U as resolveForwardRef,lt as resolveParamArgs};
|
package/dist/saga.d.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A single step in a saga.
|
|
3
|
+
*
|
|
4
|
+
* @template T - The return type of the execute function
|
|
5
|
+
*/
|
|
6
|
+
interface SagaStep<T = unknown> {
|
|
7
|
+
/** Human-readable name for logging/debugging. */
|
|
8
|
+
name: string;
|
|
9
|
+
/** The forward action. Returns a result that is passed to compensate on failure. */
|
|
10
|
+
execute: (signal?: AbortSignal) => T | Promise<T>;
|
|
11
|
+
/**
|
|
12
|
+
* The compensating action. Called with the result of execute() if a LATER step fails.
|
|
13
|
+
* Should undo the effect of execute().
|
|
14
|
+
* If not provided, the step is considered non-compensatable (e.g., the last step).
|
|
15
|
+
*/
|
|
16
|
+
compensate?: (result: T) => void | Promise<void>;
|
|
17
|
+
}
|
|
18
|
+
interface SagaResult<T = unknown> {
|
|
19
|
+
/** Whether all steps completed successfully. */
|
|
20
|
+
success: boolean;
|
|
21
|
+
/** Results of each completed step, keyed by step name. */
|
|
22
|
+
results: Record<string, unknown>;
|
|
23
|
+
/** The result of the last step (convenience). */
|
|
24
|
+
value?: T;
|
|
25
|
+
/** If failed, the error that caused the failure. */
|
|
26
|
+
error?: unknown;
|
|
27
|
+
/** Name of the step that failed. */
|
|
28
|
+
failedStep?: string;
|
|
29
|
+
/** Names of steps that were successfully compensated. */
|
|
30
|
+
compensated: string[];
|
|
31
|
+
/** Compensation errors, if any. Keyed by step name. */
|
|
32
|
+
compensationErrors: Record<string, unknown>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
interface SagaExecuteOptions {
|
|
36
|
+
/** AbortSignal that cancels pending steps and triggers compensation. */
|
|
37
|
+
signal?: AbortSignal;
|
|
38
|
+
/** Called when a compensation step throws. Defaults to a no-op. */
|
|
39
|
+
onCompensationError?: (stepName: string, error: unknown) => void;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Executes a sequence of steps with automatic compensation on failure.
|
|
43
|
+
*
|
|
44
|
+
* If step N fails, steps N-1..0 are compensated in reverse order.
|
|
45
|
+
* Compensation errors are captured but do NOT prevent other compensations.
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```typescript
|
|
49
|
+
* @UseCase()
|
|
50
|
+
* class CreateOrderUseCase {
|
|
51
|
+
* constructor(private saga: SagaOrchestrator) {}
|
|
52
|
+
*
|
|
53
|
+
* async execute(input: CreateOrderInput) {
|
|
54
|
+
* const result = await this.saga.execute([
|
|
55
|
+
* {
|
|
56
|
+
* name: 'reserve-inventory',
|
|
57
|
+
* execute: () => inventoryService.reserve(input.items),
|
|
58
|
+
* compensate: (res) => inventoryService.release(res.reservationId),
|
|
59
|
+
* },
|
|
60
|
+
* {
|
|
61
|
+
* name: 'charge-payment',
|
|
62
|
+
* execute: () => paymentService.charge(input.amount),
|
|
63
|
+
* compensate: (res) => paymentService.refund(res.chargeId),
|
|
64
|
+
* },
|
|
65
|
+
* {
|
|
66
|
+
* name: 'create-order',
|
|
67
|
+
* execute: () => orderService.create(input),
|
|
68
|
+
* },
|
|
69
|
+
* ])
|
|
70
|
+
*
|
|
71
|
+
* if (!result.success) throw result.error
|
|
72
|
+
* return result.value
|
|
73
|
+
* }
|
|
74
|
+
* }
|
|
75
|
+
* ```
|
|
76
|
+
*/
|
|
77
|
+
declare class SagaOrchestrator {
|
|
78
|
+
execute<T = unknown>(steps: SagaStep[], options?: SagaExecuteOptions): Promise<SagaResult<T>>;
|
|
79
|
+
private buildFailure;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export { type SagaExecuteOptions, SagaOrchestrator, type SagaResult, type SagaStep };
|
package/dist/saga.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {g}from'./chunk-XVPJFMLQ.js';import {a,d as d$1}from'./chunk-RMR6UXWO.js';function d(i,n,r,o){var c=arguments.length,e=c<3?n:o===null?o=Object.getOwnPropertyDescriptor(n,r):o,t;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")e=Reflect.decorate(i,n,r,o);else for(var u=i.length-1;u>=0;u--)(t=i[u])&&(e=(c<3?t(e):c>3?t(n,r,e):t(n,r))||e);return c>3&&e&&Object.defineProperty(n,r,e),e}a(d,"_ts_decorate");var l=class{static{a(this,"SagaOrchestrator");}async execute(n,r){let o=r?.signal,c=r?.onCompensationError??(()=>{}),e=[],t={};for(let a of n){if(o?.aborted)return this.buildFailure(new g,a.name,e,t,c);try{let s=await a.execute(o);e.push({step:a,result:s}),t[a.name]=s;}catch(s){return this.buildFailure(s,a.name,e,t,c)}}let u=e.length>0?e[e.length-1].result:void 0;return {success:true,results:t,value:u,compensated:[],compensationErrors:{}}}async buildFailure(n,r,o,c,e){let t=[],u={};for(let a=o.length-1;a>=0;a--){let{step:s,result:b}=o[a];if(s.compensate)try{await s.compensate(b),t.push(s.name);}catch(m){u[s.name]=m,e(s.name,m);}}return {success:false,results:c,error:n,failedStep:r,compensated:t,compensationErrors:u}}};l=d([d$1()],l);export{l as SagaOrchestrator};
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { D as DynamicModule } from './types-D-An5cXP.js';
|
|
2
|
+
|
|
3
|
+
interface CronOptions {
|
|
4
|
+
/** Optional name for the task (used for programmatic access via SchedulerRegistry). */
|
|
5
|
+
name?: string;
|
|
6
|
+
/** Whether the cron job should start immediately. Defaults to true. */
|
|
7
|
+
enabled?: boolean;
|
|
8
|
+
}
|
|
9
|
+
interface IntervalOptions {
|
|
10
|
+
/** Optional name for the task. */
|
|
11
|
+
name?: string;
|
|
12
|
+
/** Whether the interval should start immediately. Defaults to true. */
|
|
13
|
+
enabled?: boolean;
|
|
14
|
+
}
|
|
15
|
+
interface TimeoutOptions {
|
|
16
|
+
/** Optional name for the task. */
|
|
17
|
+
name?: string;
|
|
18
|
+
/** Whether the timeout should be scheduled immediately. Defaults to true. */
|
|
19
|
+
enabled?: boolean;
|
|
20
|
+
}
|
|
21
|
+
interface SchedulerTask {
|
|
22
|
+
type: 'cron' | 'interval' | 'timeout';
|
|
23
|
+
name: string;
|
|
24
|
+
stop: () => void;
|
|
25
|
+
}
|
|
26
|
+
interface ScheduleModuleOptions {
|
|
27
|
+
/** Called when a scheduled handler throws. Defaults to console.error. */
|
|
28
|
+
onError?: (error: unknown, taskName: string) => void;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Method decorator that schedules the method using a cron expression.
|
|
33
|
+
*
|
|
34
|
+
* Requires `ScheduleModule.forRoot()` in your module imports.
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```typescript
|
|
38
|
+
* @Injectable()
|
|
39
|
+
* class ReportService {
|
|
40
|
+
* @Cron('0 * * * *') // Every hour
|
|
41
|
+
* async generateReport() { ... }
|
|
42
|
+
*
|
|
43
|
+
* @Cron('0 0 * * *', { name: 'daily-cleanup' })
|
|
44
|
+
* async cleanup() { ... }
|
|
45
|
+
* }
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
declare function Cron(expression: string, options?: CronOptions): MethodDecorator;
|
|
49
|
+
/**
|
|
50
|
+
* Method decorator that runs the method at a fixed interval.
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* ```typescript
|
|
54
|
+
* @Injectable()
|
|
55
|
+
* class HealthCheckService {
|
|
56
|
+
* @Interval(30_000) // Every 30 seconds
|
|
57
|
+
* async ping() { ... }
|
|
58
|
+
* }
|
|
59
|
+
* ```
|
|
60
|
+
*/
|
|
61
|
+
declare function Interval(ms: number, options?: IntervalOptions): MethodDecorator;
|
|
62
|
+
/**
|
|
63
|
+
* Method decorator that runs the method once after a delay.
|
|
64
|
+
*
|
|
65
|
+
* @example
|
|
66
|
+
* ```typescript
|
|
67
|
+
* @Injectable()
|
|
68
|
+
* class StartupService {
|
|
69
|
+
* @Timeout(5_000) // 5 seconds after bootstrap
|
|
70
|
+
* async warmupCache() { ... }
|
|
71
|
+
* }
|
|
72
|
+
* ```
|
|
73
|
+
*/
|
|
74
|
+
declare function Timeout(ms: number, options?: TimeoutOptions): MethodDecorator;
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Enables declarative task scheduling with @Cron, @Interval, and @Timeout decorators.
|
|
78
|
+
*
|
|
79
|
+
* Import with `ScheduleModule.forRoot()` in your root module.
|
|
80
|
+
* The module automatically scans all providers for schedule decorators
|
|
81
|
+
* during bootstrap and stops all tasks on shutdown.
|
|
82
|
+
*
|
|
83
|
+
* @example
|
|
84
|
+
* ```typescript
|
|
85
|
+
* @Module({
|
|
86
|
+
* imports: [ScheduleModule.forRoot()],
|
|
87
|
+
* })
|
|
88
|
+
* export class AppModule {}
|
|
89
|
+
*
|
|
90
|
+
* // Then in any @Injectable() service:
|
|
91
|
+
* @Injectable()
|
|
92
|
+
* class SyncService {
|
|
93
|
+
* @Cron('0 * * * *')
|
|
94
|
+
* async syncData() { ... }
|
|
95
|
+
*
|
|
96
|
+
* @Interval(30_000)
|
|
97
|
+
* async healthCheck() { ... }
|
|
98
|
+
* }
|
|
99
|
+
* ```
|
|
100
|
+
*/
|
|
101
|
+
declare class ScheduleModule {
|
|
102
|
+
static forRoot(options?: ScheduleModuleOptions): DynamicModule;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Registry that tracks all running scheduled tasks.
|
|
107
|
+
* Inject this to programmatically manage tasks at runtime.
|
|
108
|
+
*
|
|
109
|
+
* @example
|
|
110
|
+
* ```typescript
|
|
111
|
+
* @Injectable()
|
|
112
|
+
* @Inject(SchedulerRegistry)
|
|
113
|
+
* class AdminService {
|
|
114
|
+
* constructor(private readonly scheduler: SchedulerRegistry) {}
|
|
115
|
+
*
|
|
116
|
+
* pauseSync() {
|
|
117
|
+
* this.scheduler.stopTask('sync-job')
|
|
118
|
+
* }
|
|
119
|
+
* }
|
|
120
|
+
* ```
|
|
121
|
+
*/
|
|
122
|
+
declare class SchedulerRegistry {
|
|
123
|
+
private tasks;
|
|
124
|
+
register(task: SchedulerTask): void;
|
|
125
|
+
getTask(name: string): SchedulerTask | undefined;
|
|
126
|
+
stopTask(name: string): boolean;
|
|
127
|
+
stopAll(): void;
|
|
128
|
+
getTaskNames(): string[];
|
|
129
|
+
get size(): number;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export { Cron, type CronOptions, Interval, type IntervalOptions, ScheduleModule, type ScheduleModuleOptions, SchedulerRegistry, type SchedulerTask, Timeout, type TimeoutOptions };
|
package/dist/schedule.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {e as e$1,b as b$1,a as a$1}from'./chunk-F5KXBDV2.js';import {a,d,e}from'./chunk-RMR6UXWO.js';import'reflect-metadata';import {Cron}from'croner';var g=Symbol("schedule:cron"),v=Symbol("schedule:interval"),T=Symbol("schedule:timeout"),b=Symbol("schedule:options");function x(n,t){return (r,e,s)=>{let o=Reflect.getOwnMetadata(g,r.constructor)??[];o.push({expression:n,methodName:String(e),options:t??{}}),Reflect.defineMetadata(g,o,r.constructor);}}a(x,"Cron");function I(n,t){return (r,e,s)=>{let o=Reflect.getOwnMetadata(v,r.constructor)??[];o.push({ms:n,methodName:String(e),options:t??{}}),Reflect.defineMetadata(v,o,r.constructor);}}a(I,"Interval");function N(n,t){return (r,e,s)=>{let o=Reflect.getOwnMetadata(T,r.constructor)??[];o.push({ms:n,methodName:String(e),options:t??{}}),Reflect.defineMetadata(T,o,r.constructor);}}a(N,"Timeout");function E(n){return Reflect.getOwnMetadata(g,n)??[]}a(E,"getCronMetadata");function A(n){return Reflect.getOwnMetadata(v,n)??[]}a(A,"getIntervalMetadata");function S(n){return Reflect.getOwnMetadata(T,n)??[]}a(S,"getTimeoutMetadata");function j(n,t,r,e){var s=arguments.length,o=s<3?t:e===null?e=Object.getOwnPropertyDescriptor(t,r):e,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,t,r,e);else for(var c=n.length-1;c>=0;c--)(i=n[c])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o}a(j,"_ts_decorate");var l=class{static{a(this,"SchedulerRegistry");}tasks=new Map;register(t){this.tasks.has(t.name)&&this.tasks.get(t.name).stop(),this.tasks.set(t.name,t);}getTask(t){return this.tasks.get(t)}stopTask(t){let r=this.tasks.get(t);return r?(r.stop(),this.tasks.delete(t),true):false}stopAll(){for(let t of this.tasks.values())t.stop();this.tasks.clear();}getTaskNames(){return [...this.tasks.keys()]}get size(){return this.tasks.size}};l=j([d()],l);function w(n,t,r,e){var s=arguments.length,o=s<3?t:e===null?e=Object.getOwnPropertyDescriptor(t,r):e,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,t,r,e);else for(var c=n.length-1;c>=0;c--)(i=n[c])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o}a(w,"_ts_decorate");function _(n,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,t)}a(_,"_ts_metadata");var p=class{static{a(this,"ScheduleExplorer");}discovery;registry;options;onError;constructor(t,r,e){this.discovery=t,this.registry=r,this.options=e,this.onError=e.onError??D;}async onApplicationBootstrap(){let t=this.discovery.getProviders();for(let r of t){let e=this.discovery.getProviderClass(r);if(!e)continue;let s=E(e),o=A(e),i=S(e);if(s.length===0&&o.length===0&&i.length===0)continue;let c=typeof r=="function"?r:r.provide,f;try{f=await this.discovery.resolve(c);}catch{continue}let O=e.name;for(let u of s)this.registerCron(f,O,u);for(let u of o)this.registerInterval(f,O,u);for(let u of i)this.registerTimeout(f,O,u);}}onApplicationShutdown(){this.registry.stopAll();}registerCron(t,r,e){let s=e.options.enabled!==false,o=e.options.name??`${r}.${e.methodName}`,i=t[e.methodName].bind(t),c=new Cron(e.expression,{paused:!s},async()=>{try{await i();}catch(f){this.onError(f,o);}});this.registry.register({type:"cron",name:o,stop:a(()=>c.stop(),"stop")});}registerInterval(t,r,e){let s=e.options.enabled!==false,o=e.options.name??`${r}.${e.methodName}`;if(!s)return;let i=t[e.methodName].bind(t),c=setInterval(async()=>{try{await i();}catch(f){this.onError(f,o);}},e.ms);this.registry.register({type:"interval",name:o,stop:a(()=>clearInterval(c),"stop")});}registerTimeout(t,r,e){let s=e.options.enabled!==false,o=e.options.name??`${r}.${e.methodName}`;if(!s)return;let i=t[e.methodName].bind(t),c=setTimeout(async()=>{try{await i();}catch(f){this.onError(f,o);}},e.ms);this.registry.register({type:"timeout",name:o,stop:a(()=>clearTimeout(c),"stop")});}};p=w([d(),e(e$1,l,b),_("design:type",Function),_("design:paramtypes",[typeof e$1>"u"?Object:e$1,typeof l>"u"?Object:l,typeof ScheduleModuleOptions>"u"?Object:ScheduleModuleOptions])],p);function D(n,t){console.error(`[Schedule] Task "${t}" failed:`,n);}a(D,"defaultErrorHandler");function P(n,t,r,e){var s=arguments.length,o=s<3?t:e===null?e=Object.getOwnPropertyDescriptor(t,r):e,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,t,r,e);else for(var c=n.length-1;c>=0;c--)(i=n[c])&&(o=(s<3?i(o):s>3?i(t,r,o):i(t,r))||o);return s>3&&o&&Object.defineProperty(t,r,o),o}a(P,"_ts_decorate");var m=class n{static{a(this,"ScheduleModule");}static forRoot(t){return {module:n,global:true,providers:[{provide:b,useValue:t??{}},l,p],exports:[l]}}};m=P([b$1(),a$1({})],m);export{x as Cron,I as Interval,m as ScheduleModule,l as SchedulerRegistry,N as Timeout};
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
declare enum Scope {
|
|
2
|
+
SINGLETON = "singleton",
|
|
3
|
+
REQUEST = "request",
|
|
4
|
+
TRANSIENT = "transient"
|
|
5
|
+
}
|
|
6
|
+
interface Type<T = unknown> extends Function {
|
|
7
|
+
new (...args: any[]): T;
|
|
8
|
+
}
|
|
9
|
+
interface InjectableOptions {
|
|
10
|
+
scope?: Scope;
|
|
11
|
+
}
|
|
12
|
+
interface ClassProvider<T = unknown> {
|
|
13
|
+
provide: Token<T>;
|
|
14
|
+
useClass: Type<T>;
|
|
15
|
+
scope?: Scope;
|
|
16
|
+
}
|
|
17
|
+
interface ValueProvider<T = unknown> {
|
|
18
|
+
provide: Token<T>;
|
|
19
|
+
useValue: T;
|
|
20
|
+
}
|
|
21
|
+
interface FactoryProvider<T = unknown> {
|
|
22
|
+
provide: Token<T>;
|
|
23
|
+
useFactory: (...args: any[]) => T | Promise<T>;
|
|
24
|
+
inject?: Token[];
|
|
25
|
+
scope?: Scope;
|
|
26
|
+
}
|
|
27
|
+
interface ExistingProvider<T = unknown> {
|
|
28
|
+
provide: Token<T>;
|
|
29
|
+
useExisting: Token<T>;
|
|
30
|
+
}
|
|
31
|
+
type Provider<T = unknown> = Type<T> | ClassProvider<T> | ValueProvider<T> | FactoryProvider<T> | ExistingProvider<T>;
|
|
32
|
+
type Token<T = unknown> = Type<T> | string | symbol | InjectionToken<T>;
|
|
33
|
+
declare class InjectionToken<T = unknown> {
|
|
34
|
+
readonly description: string;
|
|
35
|
+
constructor(description: string);
|
|
36
|
+
toString(): string;
|
|
37
|
+
}
|
|
38
|
+
interface ForwardRef<T = unknown> {
|
|
39
|
+
forwardRef: () => Type<T>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface ModuleMetadata {
|
|
43
|
+
imports?: Array<Type | DynamicModule>;
|
|
44
|
+
controllers?: Type[];
|
|
45
|
+
providers?: Provider[];
|
|
46
|
+
exports?: Token[];
|
|
47
|
+
}
|
|
48
|
+
interface DynamicModule {
|
|
49
|
+
module: Type;
|
|
50
|
+
imports?: Array<Type | DynamicModule>;
|
|
51
|
+
controllers?: Type[];
|
|
52
|
+
providers?: Provider[];
|
|
53
|
+
exports?: Token[];
|
|
54
|
+
global?: boolean;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Factory class interface for `useClass` / `useExisting` async options.
|
|
58
|
+
* Implement this on a class to provide module options asynchronously.
|
|
59
|
+
*/
|
|
60
|
+
interface ModuleOptionsFactory<T> {
|
|
61
|
+
createModuleOptions(): T | Promise<T>;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Async options accepted by `forRootAsync()`.
|
|
65
|
+
*
|
|
66
|
+
* Exactly one of `useFactory`, `useClass`, or `useExisting` must be provided.
|
|
67
|
+
*/
|
|
68
|
+
type ModuleAsyncOptions<T> = {
|
|
69
|
+
imports?: Array<Type | DynamicModule>;
|
|
70
|
+
useFactory: (...args: any[]) => T | Promise<T>;
|
|
71
|
+
inject?: Token[];
|
|
72
|
+
useClass?: never;
|
|
73
|
+
useExisting?: never;
|
|
74
|
+
} | {
|
|
75
|
+
imports?: Array<Type | DynamicModule>;
|
|
76
|
+
useClass: Type<ModuleOptionsFactory<T>>;
|
|
77
|
+
useFactory?: never;
|
|
78
|
+
inject?: never;
|
|
79
|
+
useExisting?: never;
|
|
80
|
+
} | {
|
|
81
|
+
imports?: Array<Type | DynamicModule>;
|
|
82
|
+
useExisting: Type<ModuleOptionsFactory<T>>;
|
|
83
|
+
useFactory?: never;
|
|
84
|
+
inject?: never;
|
|
85
|
+
useClass?: never;
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
export { type ClassProvider as C, type DynamicModule as D, type ExistingProvider as E, type ForwardRef as F, type InjectableOptions as I, type ModuleMetadata as M, type Provider as P, Scope as S, type Token as T, type ValueProvider as V, type Type as a, type ModuleAsyncOptions as b, InjectionToken as c, type FactoryProvider as d, type ModuleOptionsFactory as e };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "truxie",
|
|
3
|
-
"version": "0.1.0-test.
|
|
3
|
+
"version": "0.1.0-test.4",
|
|
4
4
|
"description": "NestJS-like structural backend library with DI, modules, guards, interceptors, pipes, and exception filters",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -11,6 +11,16 @@
|
|
|
11
11
|
"types": "./dist/index.d.ts",
|
|
12
12
|
"import": "./dist/index.js",
|
|
13
13
|
"default": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./saga": {
|
|
16
|
+
"types": "./dist/saga.d.ts",
|
|
17
|
+
"import": "./dist/saga.js",
|
|
18
|
+
"default": "./dist/saga.js"
|
|
19
|
+
},
|
|
20
|
+
"./schedule": {
|
|
21
|
+
"types": "./dist/schedule.d.ts",
|
|
22
|
+
"import": "./dist/schedule.js",
|
|
23
|
+
"default": "./dist/schedule.js"
|
|
14
24
|
}
|
|
15
25
|
},
|
|
16
26
|
"files": [
|
|
@@ -27,9 +37,13 @@
|
|
|
27
37
|
"reflect-metadata": "^0.2.2"
|
|
28
38
|
},
|
|
29
39
|
"peerDependencies": {
|
|
40
|
+
"croner": "^9.0.0",
|
|
30
41
|
"zod": "^3.22.0"
|
|
31
42
|
},
|
|
32
43
|
"peerDependenciesMeta": {
|
|
44
|
+
"croner": {
|
|
45
|
+
"optional": true
|
|
46
|
+
},
|
|
33
47
|
"zod": {
|
|
34
48
|
"optional": true
|
|
35
49
|
}
|
|
@@ -37,8 +51,10 @@
|
|
|
37
51
|
"devDependencies": {
|
|
38
52
|
"@swc/core": "^1.15.18",
|
|
39
53
|
"@types/node": "^22.10.5",
|
|
54
|
+
"croner": "^9.1.0",
|
|
40
55
|
"tsup": "^8.0.0",
|
|
41
56
|
"typescript": "^5.0.0",
|
|
57
|
+
"vitest": "^4.0.18",
|
|
42
58
|
"zod": "^3.22.0"
|
|
43
59
|
},
|
|
44
60
|
"keywords": [
|