truxie 0.1.0-test.5 → 0.1.0-test.6
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/cache.d.ts +170 -0
- package/dist/cache.js +1 -0
- package/dist/chunk-EI7MMDWY.js +1 -0
- package/dist/chunk-LUBJE4B3.js +1 -0
- package/dist/chunk-N277L4OB.js +1 -0
- package/dist/chunk-NXAGO5NO.js +1 -0
- package/dist/{chunk-XVPJFMLQ.js → chunk-PT5RXFB5.js} +1 -1
- package/dist/chunk-RLQ7JJW6.js +1 -0
- package/dist/chunk-XZNMJJJU.js +1 -0
- package/dist/container-BQEpLL35.d.ts +21 -0
- package/dist/event-bus-BQ4piYUx.d.ts +97 -0
- package/dist/health.d.ts +163 -0
- package/dist/health.js +1 -0
- package/dist/index.d.ts +176 -198
- package/dist/index.js +3 -3
- package/dist/interfaces-zvtMSS9r.d.ts +70 -0
- package/dist/logger.d.ts +146 -0
- package/dist/logger.js +1 -0
- package/dist/saga.js +1 -1
- package/dist/schedule.js +1 -1
- package/dist/testing.d.ts +91 -0
- package/dist/testing.js +1 -0
- package/dist/throttle.d.ts +127 -0
- package/dist/throttle.js +1 -0
- package/dist/types-G2NQp5Jb.d.ts +118 -0
- package/dist/ws.d.ts +137 -0
- package/dist/ws.js +1 -0
- package/package.json +31 -1
- package/dist/chunk-F5KXBDV2.js +0 -1
- package/dist/chunk-RMR6UXWO.js +0 -1
package/dist/cache.d.ts
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { D as DynamicModule, c as InjectionToken } from './types-D-An5cXP.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Pluggable cache store interface.
|
|
5
|
+
* Implement this to create custom stores (Redis, Memcached, etc.).
|
|
6
|
+
*/
|
|
7
|
+
interface CacheStore {
|
|
8
|
+
get<T = unknown>(key: string): Promise<T | undefined>;
|
|
9
|
+
set<T = unknown>(key: string, value: T, ttl?: number): Promise<void>;
|
|
10
|
+
del(key: string): Promise<void>;
|
|
11
|
+
clear(): Promise<void>;
|
|
12
|
+
}
|
|
13
|
+
interface CacheModuleOptions {
|
|
14
|
+
/** Cache store implementation. Defaults to in-memory store. */
|
|
15
|
+
store?: CacheStore;
|
|
16
|
+
/** Default TTL in seconds. 0 = no expiration. @default 0 */
|
|
17
|
+
ttl?: number;
|
|
18
|
+
/** Max entries for the built-in memory store. 0 = unlimited. @default 0 */
|
|
19
|
+
max?: number;
|
|
20
|
+
/** Error handler for cache operations. Defaults to console.error. */
|
|
21
|
+
onError?: (error: unknown, operation: string, key: string) => void;
|
|
22
|
+
}
|
|
23
|
+
interface CacheableOptions {
|
|
24
|
+
/**
|
|
25
|
+
* Cache key template. Supports `{argIndex}` placeholders that are
|
|
26
|
+
* replaced with the stringified argument at that index.
|
|
27
|
+
*
|
|
28
|
+
* @example 'user:{0}' — replaces {0} with the first argument
|
|
29
|
+
*/
|
|
30
|
+
key: string;
|
|
31
|
+
/** TTL in seconds. Overrides the module default. */
|
|
32
|
+
ttl?: number;
|
|
33
|
+
}
|
|
34
|
+
interface CacheEvictOptions {
|
|
35
|
+
/**
|
|
36
|
+
* Cache key template to evict. Same `{argIndex}` placeholder syntax.
|
|
37
|
+
*/
|
|
38
|
+
key: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Enables caching with @Cacheable / @CacheEvict decorators and
|
|
43
|
+
* programmatic CacheManager injection.
|
|
44
|
+
*
|
|
45
|
+
* Import with `CacheModule.forRoot()` in your root module.
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```typescript
|
|
49
|
+
* // In-memory cache (default)
|
|
50
|
+
* @Module({
|
|
51
|
+
* imports: [CacheModule.forRoot({ ttl: 300, max: 1000 })],
|
|
52
|
+
* })
|
|
53
|
+
* export class AppModule {}
|
|
54
|
+
*
|
|
55
|
+
* // Custom store (e.g. Redis)
|
|
56
|
+
* @Module({
|
|
57
|
+
* imports: [CacheModule.forRoot({ store: new RedisStore(redisClient), ttl: 60 })],
|
|
58
|
+
* })
|
|
59
|
+
* export class AppModule {}
|
|
60
|
+
*
|
|
61
|
+
* // Then in any @Injectable() service:
|
|
62
|
+
* @Injectable()
|
|
63
|
+
* class ProductService {
|
|
64
|
+
* @Cacheable({ key: 'product:{0}', ttl: 300 })
|
|
65
|
+
* async findById(id: string) { ... }
|
|
66
|
+
*
|
|
67
|
+
* @CacheEvict({ key: 'product:{0}' })
|
|
68
|
+
* async update(id: string, data: any) { ... }
|
|
69
|
+
* }
|
|
70
|
+
*
|
|
71
|
+
* // Or inject CacheManager directly:
|
|
72
|
+
* @Injectable()
|
|
73
|
+
* @Inject(CacheManager)
|
|
74
|
+
* class MyService {
|
|
75
|
+
* constructor(private cache: CacheManager) {}
|
|
76
|
+
* }
|
|
77
|
+
* ```
|
|
78
|
+
*/
|
|
79
|
+
declare class CacheModule {
|
|
80
|
+
static forRoot(options?: CacheModuleOptions): DynamicModule;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Injectable cache manager — provides a unified API for cache operations.
|
|
85
|
+
*
|
|
86
|
+
* Uses the configured store (or in-memory by default) with module-level
|
|
87
|
+
* TTL defaults.
|
|
88
|
+
*
|
|
89
|
+
* @example
|
|
90
|
+
* ```ts
|
|
91
|
+
* @Injectable()
|
|
92
|
+
* @Inject(CacheManager)
|
|
93
|
+
* class ProductService {
|
|
94
|
+
* constructor(private readonly cache: CacheManager) {}
|
|
95
|
+
*
|
|
96
|
+
* async findById(id: string) {
|
|
97
|
+
* const cached = await this.cache.get<Product>(`product:${id}`)
|
|
98
|
+
* if (cached) return cached
|
|
99
|
+
* const product = await this.repo.findById(id)
|
|
100
|
+
* await this.cache.set(`product:${id}`, product, 300)
|
|
101
|
+
* return product
|
|
102
|
+
* }
|
|
103
|
+
* }
|
|
104
|
+
* ```
|
|
105
|
+
*/
|
|
106
|
+
declare class CacheManager {
|
|
107
|
+
private readonly store;
|
|
108
|
+
private readonly defaultTtl;
|
|
109
|
+
private readonly onError;
|
|
110
|
+
constructor(options: CacheModuleOptions);
|
|
111
|
+
/** Get a cached value by key. Returns undefined on miss. */
|
|
112
|
+
get<T = unknown>(key: string): Promise<T | undefined>;
|
|
113
|
+
/** Set a cached value. TTL in seconds (overrides module default). */
|
|
114
|
+
set<T = unknown>(key: string, value: T, ttl?: number): Promise<void>;
|
|
115
|
+
/** Delete a cached value by key. */
|
|
116
|
+
del(key: string): Promise<void>;
|
|
117
|
+
/** Clear the entire cache. */
|
|
118
|
+
clear(): Promise<void>;
|
|
119
|
+
/** Get the underlying store (for advanced use). */
|
|
120
|
+
getStore(): CacheStore;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
interface CacheableEntry {
|
|
124
|
+
methodName: string;
|
|
125
|
+
options: CacheableOptions;
|
|
126
|
+
}
|
|
127
|
+
interface CacheEvictEntry {
|
|
128
|
+
methodName: string;
|
|
129
|
+
options: CacheEvictOptions;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Method decorator that caches the return value of a method.
|
|
133
|
+
*
|
|
134
|
+
* The cache key supports `{0}`, `{1}`, etc. placeholders that are
|
|
135
|
+
* replaced with the stringified method arguments at those indices.
|
|
136
|
+
*
|
|
137
|
+
* @example
|
|
138
|
+
* ```ts
|
|
139
|
+
* @Injectable()
|
|
140
|
+
* class UserService {
|
|
141
|
+
* @Cacheable({ key: 'user:{0}', ttl: 300 })
|
|
142
|
+
* async findById(id: string): Promise<User> {
|
|
143
|
+
* return this.repo.findById(id) // cached for 5 min
|
|
144
|
+
* }
|
|
145
|
+
* }
|
|
146
|
+
* ```
|
|
147
|
+
*/
|
|
148
|
+
declare function Cacheable(options: CacheableOptions): MethodDecorator;
|
|
149
|
+
/**
|
|
150
|
+
* Method decorator that evicts a cache entry when the method is called.
|
|
151
|
+
*
|
|
152
|
+
* @example
|
|
153
|
+
* ```ts
|
|
154
|
+
* @Injectable()
|
|
155
|
+
* class UserService {
|
|
156
|
+
* @CacheEvict({ key: 'user:{0}' })
|
|
157
|
+
* async update(id: string, data: any): Promise<User> {
|
|
158
|
+
* return this.repo.update(id, data) // invalidates user:{id}
|
|
159
|
+
* }
|
|
160
|
+
* }
|
|
161
|
+
* ```
|
|
162
|
+
*/
|
|
163
|
+
declare function CacheEvict(options: CacheEvictOptions): MethodDecorator;
|
|
164
|
+
declare function getCacheableMetadata(target: Function): CacheableEntry[];
|
|
165
|
+
declare function getCacheEvictMetadata(target: Function): CacheEvictEntry[];
|
|
166
|
+
|
|
167
|
+
declare const CACHE_OPTIONS: InjectionToken<CacheModuleOptions>;
|
|
168
|
+
declare const CACHE_MANAGER: InjectionToken<CacheManager>;
|
|
169
|
+
|
|
170
|
+
export { CACHE_MANAGER, CACHE_OPTIONS, CacheEvict, type CacheEvictOptions, CacheManager, CacheModule, type CacheModuleOptions, type CacheStore, Cacheable, type CacheableOptions, getCacheEvictMetadata, getCacheableMetadata };
|
package/dist/cache.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-NXAGO5NO.js';import {b as b$2,a as a$2}from'./chunk-XZNMJJJU.js';import {b as b$1,c,d as d$1}from'./chunk-N277L4OB.js';import {a}from'./chunk-EI7MMDWY.js';import'reflect-metadata';var h=new b$1("CACHE_OPTIONS"),p=new b$1("CACHE_MANAGER");var v=class{static{a(this,"MemoryStore");}store=new Map;max;constructor(t=0){this.max=t;}async get(t){let r=this.store.get(t);if(r){if(r.expiresAt>0&&Date.now()>r.expiresAt){this.store.delete(t);return}return r.value}}async set(t,r,o){if(this.max>0&&this.store.size>=this.max&&!this.store.has(t)){let e=this.store.keys().next().value;e!==void 0&&this.store.delete(e);}let n=o&&o>0?Date.now()+o*1e3:0;this.store.set(t,{value:r,expiresAt:n});}async del(t){this.store.delete(t);}async clear(){this.store.clear();}};function P(c,t,r,o){var n=arguments.length,e=n<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,r):o,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")e=Reflect.decorate(c,t,r,o);else for(var i=c.length-1;i>=0;i--)(a=c[i])&&(e=(n<3?a(e):n>3?a(t,r,e):a(t,r))||e);return n>3&&e&&Object.defineProperty(t,r,e),e}a(P,"_ts_decorate");function T(c,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(c,t)}a(T,"_ts_metadata");var f=class{static{a(this,"CacheManager");}store;defaultTtl;onError;constructor(t){this.store=t.store??new v(t.max),this.defaultTtl=t.ttl??0,this.onError=t.onError??S;}async get(t){try{return await this.store.get(t)}catch(r){this.onError(r,"get",t);return}}async set(t,r,o){try{await this.store.set(t,r,o??this.defaultTtl);}catch(n){this.onError(n,"set",t);}}async del(t){try{await this.store.del(t);}catch(r){this.onError(r,"del",t);}}async clear(){try{await this.store.clear();}catch(t){this.onError(t,"clear","*");}}getStore(){return this.store}};f=P([c(),d$1(h),T("design:type",Function),T("design:paramtypes",[typeof CacheModuleOptions>"u"?Object:CacheModuleOptions])],f);function S(c,t,r){console.error(`[Cache] ${t} failed for key "${r}":`,c);}a(S,"defaultOnError");var b=Symbol("cache:cacheable"),O=Symbol("cache:evict");function H(c){return (t,r,o)=>{let n=t.constructor,e=Reflect.getOwnMetadata(b,n)??[];Reflect.defineMetadata(b,[...e,{methodName:String(r),options:c}],n);}}a(H,"Cacheable");function I(c){return (t,r,o)=>{let n=t.constructor,e=Reflect.getOwnMetadata(O,n)??[];Reflect.defineMetadata(O,[...e,{methodName:String(r),options:c}],n);}}a(I,"CacheEvict");function x(c){return Reflect.getOwnMetadata(b,c)??[]}a(x,"getCacheableMetadata");function w(c){return Reflect.getOwnMetadata(O,c)??[]}a(w,"getCacheEvictMetadata");function R(c,t){return c.replace(/\{(\d+)\}/g,(r,o)=>{let n=parseInt(o,10),e=t[n];return e==null?"":typeof e=="object"?JSON.stringify(e):String(e)})}a(R,"resolveKeyTemplate");function D(c,t,r,o){var n=arguments.length,e=n<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,r):o,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")e=Reflect.decorate(c,t,r,o);else for(var i=c.length-1;i>=0;i--)(a=c[i])&&(e=(n<3?a(e):n>3?a(t,r,e):a(t,r))||e);return n>3&&e&&Object.defineProperty(t,r,e),e}a(D,"_ts_decorate");function N(c,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(c,t)}a(N,"_ts_metadata");var u=class{static{a(this,"CacheExplorer");}discovery;cache;constructor(t,r){this.discovery=t,this.cache=r;}async onApplicationBootstrap(){let t=this.discovery.getProviders();for(let r of t){let o=this.discovery.getProviderClass(r);if(!o)continue;let n=x(o),e=w(o);if(n.length===0&&e.length===0)continue;let a=typeof r=="function"?r:r.provide,i;try{i=await this.discovery.resolve(a);}catch{continue}for(let l of n)this.wrapCacheable(i,o,l.methodName,l.options.key,l.options.ttl);for(let l of e)this.wrapCacheEvict(i,o,l.methodName,l.options.key);}}wrapCacheable(t,r,o,n,e){let a=t[o];if(typeof a!="function")return;let i=this.cache;t[o]=async function(...l){let m=R(n,l),_=await i.get(m);if(_!==void 0)return _;let y=await a.apply(this,l);return y!=null&&await i.set(m,y,e),y};}wrapCacheEvict(t,r,o,n){let e=t[o];if(typeof e!="function")return;let a=this.cache;t[o]=async function(...i){let l=await e.apply(this,i),m=R(n,i);return await a.del(m),l};}};u=D([c(),d$1(a$1,p),N("design:type",Function),N("design:paramtypes",[typeof a$1>"u"?Object:a$1,typeof f>"u"?Object:f])],u);function G(c,t,r,o){var n=arguments.length,e=n<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,r):o,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")e=Reflect.decorate(c,t,r,o);else for(var i=c.length-1;i>=0;i--)(a=c[i])&&(e=(n<3?a(e):n>3?a(t,r,e):a(t,r))||e);return n>3&&e&&Object.defineProperty(t,r,e),e}a(G,"_ts_decorate");var d=class c{static{a(this,"CacheModule");}static forRoot(t={}){return {module:c,global:true,providers:[{provide:h,useValue:t},f,{provide:p,useExisting:f},u],exports:[f,p]}}};d=G([b$2(),a$2({})],d);export{p as CACHE_MANAGER,h as CACHE_OPTIONS,I as CacheEvict,f as CacheManager,d as CacheModule,H as Cacheable,w as getCacheEvictMetadata,x as getCacheableMetadata};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var c=Object.defineProperty;var d=(a,b)=>c(a,"name",{value:b,configurable:true});export{d as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {i as i$1}from'./chunk-RLQ7JJW6.js';import {c,d}from'./chunk-XZNMJJJU.js';import {f,a as a$1,g,h as h$1,i,b,c as c$1}from'./chunk-N277L4OB.js';import {a}from'./chunk-EI7MMDWY.js';import'reflect-metadata';function V(r){return {forwardRef:r}}a(V,"forwardRef");function G(r){return typeof r=="object"&&"forwardRef"in r?r.forwardRef():r}a(G,"resolveForwardRef");var j=class r{static{a(this,"Container");}registrations=new Map;resolving=new Set;parent=null;children=[];register(...t){for(let e of t)this.registerOne(e);}registerOne(t){if(typeof t=="function"){let s=f(t)?.scope??a$1.SINGLETON;this.registrations.set(t,{provider:t,scope:s});return}let e=t.provide,n=a$1.SINGLETON;if("useClass"in t){let o=f(t.useClass);n=t.scope??o?.scope??a$1.SINGLETON;}else "useFactory"in t&&(n=t.scope??a$1.SINGLETON);this.registrations.set(e,{provider:t,scope:n});}async resolve(t){let e=G(t),n=e!==t?e:t,o=this.registrations.get(n)??this.parent?.findRegistration(n);if(!o)throw new Error(`No provider found for ${y(n)}`);if(o.scope===a$1.SINGLETON&&o.instance!==void 0||o.scope===a$1.REQUEST&&this.parent!==null&&o.instance!==void 0)return o.instance;if(this.resolving.has(n))throw new Error(`Circular dependency detected for ${y(n)}`);this.resolving.add(n);try{let s=await this.createInstance(o);return (o.scope===a$1.SINGLETON||o.scope===a$1.REQUEST&&this.parent!==null)&&(o.instance=s),s}finally{this.resolving.delete(n);}}has(t){return this.registrations.has(t)||(this.parent?.has(t)??false)}hasRequestScoped(){for(let[,t]of this.registrations)if(t.scope===a$1.REQUEST)return true;return false}findRegistration(t){return this.registrations.get(t)??this.parent?.findRegistration(t)}createChild(){let t=new r;t.parent=this;for(let[e,n]of this.registrations)n.scope===a$1.REQUEST&&t.registrations.set(e,{provider:n.provider,scope:a$1.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 e=t.instance;typeof e.onModuleDestroy=="function"&&await e.onModuleDestroy();}this.registrations.clear(),this.resolving.clear();}async createInstance(t){let{provider:e}=t;if(typeof e=="function")return this.instantiateClass(e);if("useValue"in e)return e.useValue;if("useClass"in e)return this.instantiateClass(e.useClass);if("useFactory"in e){let n=e,o=[];if(n.inject)for(let s of n.inject)o.push(await this.resolve(s));return n.useFactory(...o)}if("useExisting"in e)return this.resolve(e.useExisting);throw new Error("Unknown provider type")}async instantiateClass(t){let e=Reflect.getMetadata("design:paramtypes",t)??[],n=g(t),o=h$1(t),s=i(t),i$1=o.size>0?Math.max(...o.keys())+1:0,a=Math.max(e.length,i$1,n.length),f=[];for(let l=0;l<a;l++){let R=o.get(l)??n[l]??e[l],_=s.has(l);try{f.push(await this.resolve(R));}catch{if(_)f.push(void 0);else throw new Error(`Cannot resolve parameter at index ${l} (${y(R)}) of ${t.name}`)}}return new t(...f)}};function y(r){return typeof r=="string"?r:typeof r=="symbol"||r instanceof b?r.toString():typeof r=="function"?r.name:String(r)}a(y,"tokenToString");var I=Symbol("controller:path"),E=Symbol("controller:guards"),w=Symbol("route:metadata"),M=Symbol("method:route"),h=Symbol("method:guards"),x=Symbol("method:noguard");function K(r){return t=>{Reflect.defineMetadata(I,r,t);}}a(K,"Controller");function m(r){return (t="")=>(e,n,o)=>{let s=o!==void 0,i=String(s?n:n?.name??n),a=s?o?.value:e;if(typeof a=="function"&&(a[M]={method:r,path:t,methodName:i}),s){let f=Reflect.getOwnMetadata(w,e.constructor)??[];return f.push({method:r,path:t,methodName:i}),Reflect.defineMetadata(w,f,e.constructor),o}return e}}a(m,"createMethodDecorator");var tt=m("GET"),et=m("POST"),ot=m("PUT"),nt=m("DELETE"),st=m("PATCH");function rt(...r){return (t,e,n)=>{if(e==null){Reflect.defineMetadata(E,r,t);return}if(n!==void 0){if(n?.value){let o=n.value[h]??[];n.value[h]=[...o,...r];}return n}if(typeof t=="function"){let o=t[h]??[];t[h]=[...o,...r];}return typeof t=="function"&&e?.kind==="class"&&Reflect.defineMetadata(E,r,t),t}}a(rt,"RouteGuards");function it(){return (r,t,e)=>e!==void 0?(e?.value&&(e.value[x]=true),e):(typeof r=="function"&&(r[x]=true),r)}a(it,"NoGuard");function A(r){return Reflect.getOwnMetadata(I,r)}a(A,"getControllerPath");function H(r){return Reflect.getOwnMetadata(E,r)??[]}a(H,"getControllerGuards");function at(r){let t=[],e=r.prototype;if(e){let n=Object.getOwnPropertyNames(e);for(let o of n){if(o==="constructor")continue;let s=e[o];typeof s=="function"&&s[M]&&t.push(s[M]);}}return t.length>0?t:Reflect.getOwnMetadata(w,r)??[]}a(at,"getRouteMetadata");function ct(r,t){let n=r.prototype?.[t],o=typeof n=="function"&&n[x]===true,s=typeof n=="function"&&n[h]||[];return o?s:[...H(r),...s]}a(ct,"getMethodGuards");var $=class{static{a(this,"ModuleRegistry");}resolved=new Map;sortedModules=[];scan(t){this.resolveModule(t),this.sortedModules=this.topologicalSort(),this.validateExports();}registerAll(t){let e=new Set;for(let n of this.sortedModules)if(n.global)for(let o of n.providers)e.add(o);e.size>0&&t.register(...e);for(let n of this.sortedModules){t.register(...n.providers);for(let o of n.metadata.imports??[]){let s=this.getModuleType(o),i=this.resolved.get(s);if(i)for(let a of i.exports){let f=this.findProvider(i,a)??this.findReExportedProvider(i,a);f&&t.register(f);}}}}getAllProviders(){let t=[];for(let e of this.sortedModules)t.push(...e.providers);return t}getAllControllers(){let t=new Set,e=[];for(let n of this.sortedModules){for(let o of n.controllers)t.has(o)||(t.add(o),e.push(o));for(let o of n.metadata.providers??[])typeof o=="function"&&A(o)!==void 0&&!t.has(o)&&(t.add(o),e.push(o));}return e}getAllGateways(){let t=new Set,e=[];for(let n of this.sortedModules)for(let o of n.providers)typeof o=="function"&&i$1(o)!==void 0&&!t.has(o)&&(t.add(o),e.push(o));return e}async callLifecycleHooks(t,e,n){for(let o of this.sortedModules)for(let s of o.providers){let i=typeof s=="function"?s:s.provide;if(t.has(i))try{let a=await t.resolve(i);a&&typeof a=="object"&&typeof a[e]=="function"&&await a[e](n);}catch{}}}resolveModule(t){let e=typeof t=="object"&&"module"in t,n=e?t.module:t;if(this.resolved.has(n))return this.resolved.get(n);let o=c(n)??{},s=e?t:{},i=[...o.controllers??[],...s.controllers??[]],a={imports:[...o.imports??[],...s.imports??[]],controllers:i,providers:[...o.providers??[],...s.providers??[]],exports:[...o.exports??[],...s.exports??[]]},f={type:n,metadata:a,controllers:i,providers:[...i,...a.providers??[]],exports:new Set(a.exports??[]),global:e?t.global??d(n):d(n)};this.resolved.set(n,f);for(let l of a.imports??[])this.resolveModule(l);return f}getVisibleTokens(t){let e=new Set;for(let n of t.providers)e.add(this.getProviderToken(n));for(let n of t.metadata.imports??[]){let o=this.getModuleType(n),s=this.resolved.get(o);if(s)for(let i of s.exports)e.add(i);}for(let n of this.sortedModules)if(n.global)for(let o of n.providers)e.add(this.getProviderToken(o));return e}validateExports(){for(let t of this.sortedModules){let e=new Set(t.providers.map(o=>this.getProviderToken(o))),n=this.collectImportedExports(t);for(let o of t.exports)if(!e.has(o)&&!n.has(o)){let s=typeof o=="function"?o.name:String(o);throw new Error(`${t.type.name} exports ${s} but it is not in its providers and is not re-exported from an imported module`)}}}validateVisibility(){for(let t of this.sortedModules){let e=this.getVisibleTokens(t);for(let n of t.providers){if(typeof n!="function")continue;let o=g(n);for(let s of o)if(!e.has(s)){let i=typeof s=="function"?s.name:String(s);throw new Error(`${t.type.name}: ${n.name} depends on ${i}, but it is not provided in this module and not exported by any imported module`)}}}}getProviderToken(t){return typeof t=="function"?t:t.provide}collectImportedExports(t){let e=new Set;for(let n of t.metadata.imports??[]){let o=this.getModuleType(n),s=this.resolved.get(o);if(s)for(let i of s.exports)e.add(i);}return e}findProvider(t,e){return t.providers.find(n=>typeof n=="function"?n===e:n.provide===e)}findReExportedProvider(t,e){for(let n of t.metadata.imports??[]){let o=this.getModuleType(n),s=this.resolved.get(o);if(!s||!s.exports.has(e))continue;let i=this.findProvider(s,e);if(i)return i;let a=this.findReExportedProvider(s,e);if(a)return a}}getModuleType(t){return typeof t=="object"&&"module"in t?t.module:t}topologicalSort(){let t=new Set,e=new Set,n=[],o=a(s=>{if(t.has(s))return;if(e.has(s))throw new Error(`Circular module dependency detected: ${s.name}`);e.add(s);let i=this.resolved.get(s);if(i){for(let a of i.metadata.imports??[])o(this.getModuleType(a));e.delete(s),t.add(s),n.push(i);}},"visit");for(let[s]of this.resolved)o(s);return n}};function D(r,t,e,n){var o=arguments.length,s=o<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(r,t,e,n);else for(var a=r.length-1;a>=0;a--)(i=r[a])&&(s=(o<3?i(s):o>3?i(t,e,s):i(t,e))||s);return o>3&&s&&Object.defineProperty(t,e,s),s}a(D,"_ts_decorate");function L(r,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,t)}a(L,"_ts_metadata");var u=class{static{a(this,"EventBus");}handlers=new Map;onError;constructor(){this.onError=k;}setOptions(t){t.onError&&(this.onError=t.onError);}subscribe(t,e,n){let o=this.handlers.get(t)??[];o.push({instance:n?.instance??{},methodName:n?.methodName??"anonymous",handler:e}),this.handlers.set(t,o);}registerHandler(t,e,n){let o=e[n].bind(e);this.subscribe(t,o,{instance:e,methodName:n});}async emit(t){let e=this.handlers.get(t.type);if(!e||e.length===0)return;let n=await Promise.allSettled(e.map(o=>o.handler(t)));for(let o=0;o<n.length;o++){let s=n[o];if(s.status==="rejected"){let i=e[o],a=`${i.instance.constructor?.name??"Unknown"}.${i.methodName}`;this.onError(s.reason,t.type,a);}}}emitAsync(t){this.emit(t).catch(()=>{});}hasHandlers(t){let e=this.handlers.get(t);return e!==void 0&&e.length>0}handlerCount(t){return this.handlers.get(t)?.length??0}clear(){this.handlers.clear();}};u=D([c$1(),L("design:type",Function),L("design:paramtypes",[])],u);function k(r,t,e){console.error(`[EventBus] Handler "${e}" failed for event "${t}":`,r);}a(k,"defaultErrorHandler");var T=Symbol("on-event");function Mt(r){return (t,e,n)=>{let o=Reflect.getOwnMetadata(T,t.constructor)??[];o.push({eventType:r,methodName:String(e)}),Reflect.defineMetadata(T,o,t.constructor);}}a(Mt,"OnEvent");function U(r){return Reflect.getOwnMetadata(T,r)??[]}a(U,"getOnEventMetadata");async function Nt(r,t){let e=await r.resolve(u);for(let n of t){let o=F(n);if(!o)continue;let s=U(o);if(s.length===0)continue;let i=typeof n=="function"?n:n.provide,a;try{a=await r.resolve(i);}catch{continue}for(let f of s)typeof a[f.methodName]=="function"&&e.registerHandler(f.eventType,a,f.methodName);}}a(Nt,"scanEventHandlers");function F(r){return typeof r=="function"?f(r)?r:null:"useClass"in r?r.useClass:null}a(F,"getProviderClass");export{V as a,G as b,j as c,K as d,tt as e,et as f,ot as g,nt as h,st as i,rt as j,it as k,A as l,H as m,at as n,ct as o,$ as p,u as q,Mt as r,Nt as s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-EI7MMDWY.js';import'reflect-metadata';var p=(function(t){return t.SINGLETON="singleton",t.REQUEST="request",t.TRANSIENT="transient",t})({}),s=class{static{a$1(this,"InjectionToken");}description;constructor(n){this.description=n;}toString(){return `InjectionToken(${this.description})`}};var f=Symbol("injectable"),a=Symbol("inject:param"),l=Symbol("inject:deps"),r=Symbol("optional");function A(t){return n=>{Reflect.defineMetadata(f,{scope:t?.scope??p.SINGLETON},n);}}a$1(A,"Injectable");function E(...t){return (n,c,o)=>{if(typeof o=="number"){let i=Reflect.getOwnMetadata(a,n)??new Map;i.set(o,t[0]),Reflect.defineMetadata(a,i,n);}else Reflect.defineMetadata(l,t,n);}}a$1(E,"Inject");function R(){return (t,n,c)=>{let o=Reflect.getOwnMetadata(r,t)??new Set;o.add(c),Reflect.defineMetadata(r,o,t);}}a$1(R,"Optional");function O(t){return Reflect.getOwnMetadata(f,t)}a$1(O,"getInjectableMetadata");function g(t){return Reflect.getOwnMetadata(l,t)??[]}a$1(g,"getClassDeps");function S(t){return Reflect.getOwnMetadata(a,t)??new Map}a$1(S,"getInjectTokens");function w(t){return Reflect.getOwnMetadata(r,t)??new Set}a$1(w,"getOptionalParams");export{p as a,s as b,A as c,E as d,R as e,O as f,g,S as h,w as i};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {c}from'./chunk-N277L4OB.js';import {a as a$1}from'./chunk-EI7MMDWY.js';function a(r,e,n,o){var s=arguments.length,t=s<3?e:o===null?o=Object.getOwnPropertyDescriptor(e,n):o,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")t=Reflect.decorate(r,e,n,o);else for(var f=r.length-1;f>=0;f--)(i=r[f])&&(t=(s<3?i(t):s>3?i(e,n,t):i(e,n))||t);return s>3&&t&&Object.defineProperty(e,n,t),t}a$1(a,"_ts_decorate");var l=class{static{a$1(this,"DiscoveryService");}container;providers=[];_init(e,n){this.container=e,this.providers=n;}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}};l=a([c()],l);export{l as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-
|
|
1
|
+
import {a as a$1}from'./chunk-EI7MMDWY.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a}from'./chunk-EI7MMDWY.js';import'reflect-metadata';var S=Symbol("ws:gateway"),d=Symbol("ws:message"),f=Symbol("ws:params"),l=Symbol("ws:guards"),g=Symbol("ws:server");function p(e){return n=>{let o=typeof e=="string"?{path:e}:e??{},a={path:o.path??"/",namespace:o.namespace??"/",target:n};Reflect.defineMetadata(S,a,n);}}a(p,"WebSocketGateway");function w(e){return (n,o,a)=>{let s=n.constructor,r=Reflect.getOwnMetadata(d,s)??[];Reflect.defineMetadata(d,[...r,{event:e,methodName:String(o)}],s);}}a(w,"SubscribeMessage");function b(){return (e,n)=>{let o=e.constructor,a=Reflect.getOwnMetadata(g,o)??[];Reflect.defineMetadata(g,[...a,String(n)],o);}}a(b,"WebSocketServer");function i(e,n){return (o,a,s)=>{if(a===void 0)return;let r=o[a];if(typeof r!="function")return;let c=r[f]??[];r[f]=[...c,{type:e,index:s,extractor:n}];}}a(i,"buildWsParamDecorator");var M=a(()=>i("message-body"),"MessageBody"),W=a(()=>i("connected-socket"),"ConnectedSocket"),R=a(()=>i("ws-auth"),"WsAuth");function y(e){return ()=>i("custom",e)}a(y,"createWsParamDecorator");function A(...e){return n=>{Reflect.defineMetadata(l,e,n);}}a(A,"WsGuards");function h(e){return Reflect.getOwnMetadata(S,e)}a(h,"getGatewayMetadata");function k(e){return Reflect.getOwnMetadata(d,e)??[]}a(k,"getMessageHandlers");function _(e){return e[f]??[]}a(_,"getWsParams");function E(e){return Reflect.getOwnMetadata(l,e)??[]}a(E,"getWsGuards");function G(e){return Reflect.getOwnMetadata(g,e)??[]}a(G,"getWsServerProperties");function D(e,n,o,a){if(e.length===0)return [];let s=Math.max(...e.map(c=>c.index)),r=new Array(s+1).fill(void 0);for(let{type:c,index:u,extractor:x}of e)switch(c){case "message-body":r[u]=a;break;case "connected-socket":r[u]=n;break;case "ws-auth":r[u]=n.context.auth;break;case "custom":r[u]=x?x(n,o):void 0;break}return r}a(D,"resolveWsArgs");export{p as a,w as b,b as c,M as d,W as e,R as f,y as g,A as h,h as i,k as j,_ as k,E as l,G as m,D as n};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-EI7MMDWY.js';import'reflect-metadata';var o=Symbol("module"),a=Symbol("module:global");function r(e){return n=>{Reflect.defineMetadata(o,e,n);}}a$1(r,"Module");function u(){return e=>{Reflect.defineMetadata(a,true,e);}}a$1(u,"Global");function d(e){return Reflect.getOwnMetadata(o,e)}a$1(d,"getModuleMetadata");function M(e){return Reflect.getOwnMetadata(a,e)===true}a$1(M,"isGlobalModule");export{r as a,u as b,d as c,M as d};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { P as Provider, T as Token } from './types-D-An5cXP.js';
|
|
2
|
+
|
|
3
|
+
declare class Container {
|
|
4
|
+
private registrations;
|
|
5
|
+
private resolving;
|
|
6
|
+
private parent;
|
|
7
|
+
private children;
|
|
8
|
+
register(...providers: Provider[]): void;
|
|
9
|
+
private registerOne;
|
|
10
|
+
resolve<T>(token: Token<T>): Promise<T>;
|
|
11
|
+
has(token: Token): boolean;
|
|
12
|
+
/** Returns true if any registered provider uses Scope.REQUEST. */
|
|
13
|
+
hasRequestScoped(): boolean;
|
|
14
|
+
private findRegistration;
|
|
15
|
+
createChild(): Container;
|
|
16
|
+
dispose(): Promise<void>;
|
|
17
|
+
private createInstance;
|
|
18
|
+
private instantiateClass;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export { Container as C };
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Base class for all domain events.
|
|
3
|
+
*
|
|
4
|
+
* Events carry an immutable `type` string and a `payload`.
|
|
5
|
+
* The `type` is used for routing to @OnEvent() handlers.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* class ProjectCreatedEvent extends DomainEvent<{
|
|
10
|
+
* userId: string
|
|
11
|
+
* projectId: string
|
|
12
|
+
* }> {
|
|
13
|
+
* readonly type = 'project.created'
|
|
14
|
+
* }
|
|
15
|
+
*
|
|
16
|
+
* const event = new ProjectCreatedEvent({
|
|
17
|
+
* userId: '123',
|
|
18
|
+
* projectId: '456',
|
|
19
|
+
* })
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
declare abstract class DomainEvent<TPayload = unknown> {
|
|
23
|
+
readonly payload: TPayload;
|
|
24
|
+
abstract readonly type: string;
|
|
25
|
+
readonly timestamp: number;
|
|
26
|
+
constructor(payload: TPayload);
|
|
27
|
+
}
|
|
28
|
+
interface EventHandler {
|
|
29
|
+
(event: DomainEvent): void | Promise<void>;
|
|
30
|
+
}
|
|
31
|
+
interface EventBusOptions {
|
|
32
|
+
/** Called when an event handler throws. Defaults to console.error. */
|
|
33
|
+
onError?: (error: unknown, eventType: string, handlerName: string) => void;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* In-process async EventBus.
|
|
38
|
+
*
|
|
39
|
+
* - Handlers are fire-and-forget: errors are caught and reported, never propagated
|
|
40
|
+
* - Multiple handlers can subscribe to the same event type (fan-out)
|
|
41
|
+
* - Handlers run concurrently via Promise.allSettled
|
|
42
|
+
* - Replaces manual `.catch(() => {})` patterns
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* ```typescript
|
|
46
|
+
* // Emit from a UseCase
|
|
47
|
+
* this.eventBus.emit(new ProjectCreatedEvent({ userId, projectId }))
|
|
48
|
+
*
|
|
49
|
+
* // Subscribe programmatically (auto-done by @OnEvent scanner)
|
|
50
|
+
* eventBus.subscribe('project.created', async (event) => {
|
|
51
|
+
* await logService.create({ ... })
|
|
52
|
+
* })
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
declare class EventBus {
|
|
56
|
+
private handlers;
|
|
57
|
+
private onError;
|
|
58
|
+
constructor();
|
|
59
|
+
setOptions(options: EventBusOptions): void;
|
|
60
|
+
/**
|
|
61
|
+
* Register an event handler for a specific event type.
|
|
62
|
+
*/
|
|
63
|
+
subscribe(eventType: string, handler: EventHandler, meta?: {
|
|
64
|
+
instance?: object;
|
|
65
|
+
methodName?: string;
|
|
66
|
+
}): void;
|
|
67
|
+
/**
|
|
68
|
+
* Register an instance method as a handler (used by module scanner).
|
|
69
|
+
*/
|
|
70
|
+
registerHandler(eventType: string, instance: object, methodName: string): void;
|
|
71
|
+
/**
|
|
72
|
+
* Emit a domain event.
|
|
73
|
+
*
|
|
74
|
+
* All subscribed handlers execute concurrently.
|
|
75
|
+
* Errors are caught per-handler and reported via onError callback.
|
|
76
|
+
* The emit call itself never throws.
|
|
77
|
+
*/
|
|
78
|
+
emit(event: DomainEvent): Promise<void>;
|
|
79
|
+
/**
|
|
80
|
+
* Emit without awaiting. Truly fire-and-forget.
|
|
81
|
+
*/
|
|
82
|
+
emitAsync(event: DomainEvent): void;
|
|
83
|
+
/**
|
|
84
|
+
* Check if any handlers are registered for an event type.
|
|
85
|
+
*/
|
|
86
|
+
hasHandlers(eventType: string): boolean;
|
|
87
|
+
/**
|
|
88
|
+
* Get count of registered handlers for an event type.
|
|
89
|
+
*/
|
|
90
|
+
handlerCount(eventType: string): number;
|
|
91
|
+
/**
|
|
92
|
+
* Remove all handlers (used during shutdown).
|
|
93
|
+
*/
|
|
94
|
+
clear(): void;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export { DomainEvent as D, type EventBusOptions as E, EventBus as a, type EventHandler as b };
|
package/dist/health.d.ts
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { D as DynamicModule, c as InjectionToken } from './types-D-An5cXP.js';
|
|
2
|
+
|
|
3
|
+
type HealthStatus = 'up' | 'down';
|
|
4
|
+
interface HealthIndicatorResult {
|
|
5
|
+
status: HealthStatus;
|
|
6
|
+
details?: Record<string, unknown>;
|
|
7
|
+
}
|
|
8
|
+
interface HealthIndicator {
|
|
9
|
+
/** Check the health of this component. */
|
|
10
|
+
check(): Promise<HealthIndicatorResult>;
|
|
11
|
+
}
|
|
12
|
+
interface HealthCheckConfig {
|
|
13
|
+
/** Name of this health check (shown in the response). */
|
|
14
|
+
name: string;
|
|
15
|
+
/** The health indicator class or instance. */
|
|
16
|
+
check: HealthIndicator | (new (...args: any[]) => HealthIndicator);
|
|
17
|
+
/** Options passed to built-in indicators. */
|
|
18
|
+
options?: Record<string, unknown>;
|
|
19
|
+
}
|
|
20
|
+
interface HealthCheckResult {
|
|
21
|
+
status: HealthStatus;
|
|
22
|
+
uptime: number;
|
|
23
|
+
timestamp: string;
|
|
24
|
+
checks: Record<string, HealthIndicatorResult>;
|
|
25
|
+
}
|
|
26
|
+
interface HealthModuleOptions {
|
|
27
|
+
/** Health check indicators to register. */
|
|
28
|
+
checks?: HealthCheckConfig[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Enables health checks with built-in and custom indicators.
|
|
33
|
+
*
|
|
34
|
+
* Import with `HealthModule.forRoot()` in your root module.
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```typescript
|
|
38
|
+
* import { HealthModule, MemoryHealthIndicator, DiskHealthIndicator } from 'truxie/health'
|
|
39
|
+
*
|
|
40
|
+
* @Module({
|
|
41
|
+
* imports: [
|
|
42
|
+
* HealthModule.forRoot({
|
|
43
|
+
* checks: [
|
|
44
|
+
* { name: 'memory', check: new MemoryHealthIndicator(0.9) },
|
|
45
|
+
* { name: 'disk', check: new DiskHealthIndicator(0.9, '/') },
|
|
46
|
+
* { name: 'mongodb', check: new MongoHealthIndicator(mongoose) },
|
|
47
|
+
* ],
|
|
48
|
+
* }),
|
|
49
|
+
* ],
|
|
50
|
+
* })
|
|
51
|
+
* export class AppModule {}
|
|
52
|
+
*
|
|
53
|
+
* // Then create a controller:
|
|
54
|
+
* @Controller('health')
|
|
55
|
+
* export class HealthController {
|
|
56
|
+
* constructor(private readonly health: HealthService) {}
|
|
57
|
+
*
|
|
58
|
+
* @Get('/')
|
|
59
|
+
* @NoGuard()
|
|
60
|
+
* async check() {
|
|
61
|
+
* return this.health.check()
|
|
62
|
+
* }
|
|
63
|
+
* }
|
|
64
|
+
* ```
|
|
65
|
+
*
|
|
66
|
+
* Response format:
|
|
67
|
+
* ```json
|
|
68
|
+
* {
|
|
69
|
+
* "status": "up",
|
|
70
|
+
* "uptime": 3600,
|
|
71
|
+
* "timestamp": "2026-03-15T12:00:00.000Z",
|
|
72
|
+
* "checks": {
|
|
73
|
+
* "memory": { "status": "up", "details": { "heapUsedMB": 128, ... } },
|
|
74
|
+
* "disk": { "status": "up", "details": { "usagePercent": 45, ... } },
|
|
75
|
+
* "mongodb": { "status": "up", "details": { "ping": "1ms" } }
|
|
76
|
+
* }
|
|
77
|
+
* }
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
declare class HealthModule {
|
|
81
|
+
static forRoot(options?: HealthModuleOptions): DynamicModule;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Service that runs all registered health indicators and returns
|
|
86
|
+
* an aggregated health check result.
|
|
87
|
+
*
|
|
88
|
+
* @example
|
|
89
|
+
* ```ts
|
|
90
|
+
* @Injectable()
|
|
91
|
+
* @Inject(HealthService)
|
|
92
|
+
* class HealthController {
|
|
93
|
+
* constructor(private readonly health: HealthService) {}
|
|
94
|
+
*
|
|
95
|
+
* async check() {
|
|
96
|
+
* return this.health.check()
|
|
97
|
+
* }
|
|
98
|
+
* }
|
|
99
|
+
* ```
|
|
100
|
+
*/
|
|
101
|
+
declare class HealthService {
|
|
102
|
+
private readonly indicators;
|
|
103
|
+
constructor(options: HealthModuleOptions);
|
|
104
|
+
/**
|
|
105
|
+
* Run all registered health checks and return an aggregated result.
|
|
106
|
+
* Overall status is `down` if any individual check is `down`.
|
|
107
|
+
*/
|
|
108
|
+
check(): Promise<HealthCheckResult>;
|
|
109
|
+
/** Register an additional health indicator at runtime. */
|
|
110
|
+
addIndicator(name: string, indicator: HealthIndicator): void;
|
|
111
|
+
/** Remove a health indicator by name. */
|
|
112
|
+
removeIndicator(name: string): void;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
declare const HEALTH_OPTIONS: InjectionToken<HealthModuleOptions>;
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Built-in memory health indicator.
|
|
119
|
+
*
|
|
120
|
+
* Reports `down` when heap usage exceeds the configured threshold.
|
|
121
|
+
*
|
|
122
|
+
* @example
|
|
123
|
+
* ```ts
|
|
124
|
+
* HealthModule.forRoot({
|
|
125
|
+
* checks: [
|
|
126
|
+
* { name: 'memory', check: new MemoryHealthIndicator(0.9) }, // 90% threshold
|
|
127
|
+
* ],
|
|
128
|
+
* })
|
|
129
|
+
* ```
|
|
130
|
+
*/
|
|
131
|
+
declare class MemoryHealthIndicator implements HealthIndicator {
|
|
132
|
+
private readonly threshold;
|
|
133
|
+
/** @param threshold - Heap usage ratio (0-1). Default: 0.9 (90%) */
|
|
134
|
+
constructor(threshold?: number);
|
|
135
|
+
check(): Promise<HealthIndicatorResult>;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Built-in disk health indicator (Linux/macOS only).
|
|
140
|
+
*
|
|
141
|
+
* Reports `down` when disk usage exceeds the configured threshold.
|
|
142
|
+
*
|
|
143
|
+
* @example
|
|
144
|
+
* ```ts
|
|
145
|
+
* HealthModule.forRoot({
|
|
146
|
+
* checks: [
|
|
147
|
+
* { name: 'disk', check: new DiskHealthIndicator(0.9, '/') },
|
|
148
|
+
* ],
|
|
149
|
+
* })
|
|
150
|
+
* ```
|
|
151
|
+
*/
|
|
152
|
+
declare class DiskHealthIndicator implements HealthIndicator {
|
|
153
|
+
private readonly threshold;
|
|
154
|
+
private readonly path;
|
|
155
|
+
/**
|
|
156
|
+
* @param threshold - Disk usage ratio (0-1). Default: 0.9 (90%)
|
|
157
|
+
* @param path - Mount path to check. Default: '/'
|
|
158
|
+
*/
|
|
159
|
+
constructor(threshold?: number, path?: string);
|
|
160
|
+
check(): Promise<HealthIndicatorResult>;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export { DiskHealthIndicator, HEALTH_OPTIONS, type HealthCheckConfig, type HealthCheckResult, type HealthIndicator, type HealthIndicatorResult, HealthModule, type HealthModuleOptions, HealthService, type HealthStatus, MemoryHealthIndicator };
|
package/dist/health.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {b as b$1,a as a$1}from'./chunk-XZNMJJJU.js';import {b,c,d as d$1}from'./chunk-N277L4OB.js';import {a}from'./chunk-EI7MMDWY.js';import {execSync}from'child_process';var l=new b("HEALTH_OPTIONS");function x(a,t,e,r){var s=arguments.length,o=s<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,n;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(a,t,e,r);else for(var c=a.length-1;c>=0;c--)(n=a[c])&&(o=(s<3?n(o):s>3?n(t,e,o):n(t,e))||o);return s>3&&o&&Object.defineProperty(t,e,o),o}a(x,"_ts_decorate");function T(a,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(a,t)}a(T,"_ts_metadata");var y=Date.now(),h=class{static{a(this,"HealthService");}indicators=new Map;constructor(t){for(let e of t.checks??[]){let r=typeof e.check=="function"?new e.check:e.check;this.indicators.set(e.name,r);}}async check(){let t={},e="up",r=[...this.indicators.entries()],s=await Promise.allSettled(r.map(async([o,n])=>{let c=await n.check();return {name:o,result:c}}));for(let o of s)if(o.status==="fulfilled"){let{name:n,result:c}=o.value;t[n]=c,c.status==="down"&&(e="down");}else {let n=s.indexOf(o),c=r[n]?.[0]??"unknown";t[c]={status:"down",details:{error:o.reason instanceof Error?o.reason.message:String(o.reason)}},e="down";}return {status:e,uptime:Math.round((Date.now()-y)/1e3),timestamp:new Date().toISOString(),checks:t}}addIndicator(t,e){this.indicators.set(t,e);}removeIndicator(t){this.indicators.delete(t);}};h=x([c(),d$1(l),T("design:type",Function),T("design:paramtypes",[typeof HealthModuleOptions>"u"?Object:HealthModuleOptions])],h);function H(a,t,e,r){var s=arguments.length,o=s<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,n;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(a,t,e,r);else for(var c=a.length-1;c>=0;c--)(n=a[c])&&(o=(s<3?n(o):s>3?n(t,e,o):n(t,e))||o);return s>3&&o&&Object.defineProperty(t,e,o),o}a(H,"_ts_decorate");var u=class a$1{static{a(this,"HealthModule");}static forRoot(t={}){return {module:a$1,global:true,providers:[{provide:l,useValue:t},h],exports:[h]}}};u=H([b$1(),a$1({})],u);var d=class{static{a(this,"MemoryHealthIndicator");}threshold;constructor(t=.9){this.threshold=t;}async check(){let t=process.memoryUsage(),e=t.heapUsed,r=t.heapTotal,s=r>0?e/r:0;return {status:s<this.threshold?"up":"down",details:{heapUsedMB:Math.round(e/1024/1024),heapTotalMB:Math.round(r/1024/1024),rssMB:Math.round(t.rss/1024/1024),usagePercent:Math.round(s*100),threshold:Math.round(this.threshold*100)}}}};var p=class{static{a(this,"DiskHealthIndicator");}threshold;path;constructor(t=.9,e="/"){this.threshold=t,this.path=e;}async check(){try{let e=execSync(`df -P "${this.path}" | tail -1`,{encoding:"utf8",timeout:5e3}).trim().split(/\s+/),r=parseInt(e[1]??"0",10),s=parseInt(e[2]??"0",10),o=r>0?s/r:0;return {status:o<this.threshold?"up":"down",details:{totalGB:Math.round(r/1024/1024*10)/10,usedGB:Math.round(s/1024/1024*10)/10,usagePercent:Math.round(o*100),threshold:Math.round(this.threshold*100),path:this.path}}}catch{return {status:"down",details:{error:"Failed to check disk usage",path:this.path}}}}};export{p as DiskHealthIndicator,l as HEALTH_OPTIONS,u as HealthModule,h as HealthService,d as MemoryHealthIndicator};
|