truxie 0.1.3 → 0.2.1
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/README.md +5 -1
- package/dist/chunk-TB76O5JV.js +4 -0
- package/dist/{event-bus-CaQGBKG0.d.ts → event-bus-CqsK7FDO.d.ts} +9 -0
- package/dist/index.d.ts +54 -4
- package/dist/index.js +2 -2
- package/dist/testing.d.ts +5 -2
- package/dist/testing.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-CD6QSDG5.js +0 -2
package/README.md
CHANGED
|
@@ -112,11 +112,15 @@ const testingModule = await Test.createTestingModule(UserModule)
|
|
|
112
112
|
|
|
113
113
|
`onModuleInit` → `onApplicationBootstrap` → … → `onModuleDestroy` → `onApplicationShutdown`. Each hook runs once per instance, whether the application or the container gets there first.
|
|
114
114
|
|
|
115
|
+
- **Boot fails loudly.** A provider that can't be built, or an `onModuleInit` / `onApplicationBootstrap` hook that throws, rejects `TruxieFactory.create` (and `Test...compile()`) with a `LifecycleError`. Every provider in the failing phase is still visited, so `error.failures` lists all of them. Anything already started is torn down before the error is thrown.
|
|
116
|
+
- **Shutdown runs dependents first.** Teardown hooks run in reverse order of instance creation, so a worker stops before the pool it queries closes, even when that pool lives in a `@Global()` module nobody imports explicitly. Stop consuming work in `onModuleDestroy` and release connections in `onApplicationShutdown`; every `onModuleDestroy` finishes before any `onApplicationShutdown` starts.
|
|
117
|
+
- **Shutdown is best-effort.** A hook that throws doesn't stop the rest. `app.shutdown()` finishes tearing everything down, then rejects with one `LifecycleError` listing every failure.
|
|
118
|
+
|
|
115
119
|
## The rest of the family
|
|
116
120
|
|
|
117
121
|
`@truxie/express` · `@truxie/next` · `@truxie/nitro` · `@truxie/sveltekit` — HTTP adapters.
|
|
118
122
|
`@truxie/zod` · `@truxie/openapi` · `@truxie/mcp` — validation, documentation, agents.
|
|
119
123
|
`@truxie/jwt` · `@truxie/rbac` · `@truxie/throttle` — authentication, authorization, rate limiting.
|
|
120
|
-
`@truxie/cache` · `@truxie/schedule` · `@truxie/bullmq` · `@truxie/nats` · `@truxie/health` · `@truxie/logger` — the usual infrastructure.
|
|
124
|
+
`@truxie/drizzle` · `@truxie/cache` · `@truxie/schedule` · `@truxie/bullmq` · `@truxie/nats` · `@truxie/health` · `@truxie/logger` — the usual infrastructure.
|
|
121
125
|
|
|
122
126
|
MIT.
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import {i as i$1}from'./chunk-RDP32XIU.js';import {d,h,a as a$1,i,j,k,b,n,o,e}from'./chunk-TSJZVSHP.js';import {a}from'./chunk-EI7MMDWY.js';import'reflect-metadata';var L=new WeakSet;function O(n){return L.has(n)?false:(L.add(n),true)}a(O,"claimDestroy");var _=class extends Error{static{a(this,"MissingProviderError");}},U=class extends AggregateError{static{a(this,"DisposeError");}constructor(e){super(e,`${e.length} onModuleDestroy hooks failed`);}},V=class n{static{a(this,"Container");}registrations=new Map;parent=null;children=[];register(...e){for(let t of e)this.registerOne(t);}registerOne(e){let t=e&&typeof e=="object"&&"forwardRef"in e?d(e):e;if(typeof t=="function"){let a=h(t)?.scope??a$1.SINGLETON;this.registrations.set(t,{provider:t,scope:a,resolved:false});return}let r=t.provide,o=a$1.SINGLETON,s=t;if("useClass"in t){let i=t.useClass,a=i&&typeof i=="object"&&"forwardRef"in i?d(i):i,f=h(a);o=t.scope??f?.scope??a$1.SINGLETON,s={...t,useClass:a};}else if("useExisting"in t){let i=t.useExisting,a=i&&typeof i=="object"&&"forwardRef"in i?d(i):i;s={...t,useExisting:a};}else "useFactory"in t&&(o=t.scope??a$1.SINGLETON);this.registrations.set(r,{provider:s,scope:o,resolved:false});}async resolve(e){return this.resolveInternal(e,oe)}async resolveInternal(e,t){let r=d(e),o=r!==e?r:e,s=this.findOwner(o);if(!s)throw new _(`No provider found for ${D(o)}`);let i=s.registrations.get(o),a=i.scope===a$1.SINGLETON?s:this,f=i.scope===a$1.SINGLETON||i.scope===a$1.REQUEST&&a.parent!==null;if(f&&i.resolved)return i.instance;if(t.has(o))throw new Error(`Circular dependency detected for ${D(o)}`);if(f&&i.inFlight)return i.inFlight;let l=new Set(t).add(o),u=a.createInstance(i,l).then(d=>(ne(d),f&&(i.instance=d,i.resolved=true),i.inFlight=void 0,d),d=>{throw i.inFlight=void 0,d});return f&&(i.inFlight=u),u}has(e){return this.registrations.has(e)||(this.parent?.has(e)??false)}hasRequestScoped(){for(let[,e]of this.registrations)if(e.scope===a$1.REQUEST)return true;return this.parent?.hasRequestScoped()??false}findOwner(e){return this.registrations.has(e)?this:this.parent?.findOwner(e)??null}createChild(){let e=new n;e.parent=this;for(let[t,r]of this.registrations)r.scope===a$1.REQUEST&&e.registrations.set(t,{provider:r.provider,scope:a$1.REQUEST,instance:void 0,resolved:false});return this.children.push(e),e}async dispose(){let e=[];for(let t of [...this.children])try{await t.dispose();}catch(r){r instanceof U?e.push(...r.errors):e.push(r);}this.children=[];for(let[,t]of this.registrations){if(!t.resolved)continue;let r=t.instance;if(!r||typeof r!="object")continue;let o=r;if(typeof o.onModuleDestroy=="function"&&O(r))try{await o.onModuleDestroy();}catch(s){e.push(s);}}if(this.registrations.clear(),this.parent){let t=this.parent.children.indexOf(this);t!==-1&&this.parent.children.splice(t,1),this.parent=null;}if(e.length===1)throw e[0];if(e.length>1)throw new U(e)}async createInstance(e,t){let{provider:r}=e;if(typeof r=="function")return this.instantiateClass(r,t);if("useValue"in r)return r.useValue;if("useClass"in r)return this.instantiateClass(r.useClass,t);if("useFactory"in r){let o=r,s=[];if(o.inject)for(let i of o.inject)s.push(await this.resolveInternal(i,t));return o.useFactory(...s)}if("useExisting"in r)return this.resolveInternal(r.useExisting,t);throw new Error("Unknown provider type")}async instantiateClass(e,t){let r=Reflect.getMetadata("design:paramtypes",e)??[],o=i(e),s=j(e),i$1=k(e),a=s.size>0?Math.max(...s.keys())+1:0,f=Math.max(r.length,a,o.length),l=[];for(let u=0;u<f;u++){let d=s.get(u)??o[u]??r[u];try{l.push(await this.resolveInternal(d,t));}catch(g){if(g instanceof _&&i$1.has(u)){l.push(void 0);continue}let M=g instanceof Error?g.message:String(g);throw new Error(`Cannot resolve parameter at index ${u} (${D(d)}) of ${e.name}: ${M}`,{cause:g})}}return new e(...l)}},oe=new Set,N=new WeakMap,re=0;function ne(n){n&&typeof n=="object"&&!N.has(n)&&N.set(n,re++);}a(ne,"recordCreation");function C(n){return N.get(n)}a(C,"creationOrder");function D(n){return typeof n=="string"?n:typeof n=="symbol"||n instanceof b?n.toString():typeof n=="function"?n.name:String(n)}a(D,"tokenToString");function Q(n,e){let t=[];for(let s=e;typeof s=="function"&&s!==Function.prototype;s=Object.getPrototypeOf(s)){let i=Reflect.getOwnMetadata(n,s);i!==void 0&&i.length>0&&t.push(i);}let r=new Set,o=[];for(let s of t.reverse())for(let i of s)r.has(i)||(r.add(i),o.push(i));return o}a(Q,"inheritedClassMetadata");var q=Symbol.for("truxie:controller:path"),v=Symbol.for("truxie:controller:guards"),$=Symbol.for("truxie:route:metadata"),z=Symbol.for("truxie:method:route"),E=Symbol.for("truxie:method:guards"),I=Symbol.for("truxie:method:noguard");function je(n){return e=>{Reflect.defineMetadata(q,n,e);}}a(je,"Controller");function x(n){return (e="")=>(t,r,o)=>{let s=o!==void 0,i=String(s?r:r?.name??r),a=s?o?.value:t;if(typeof a=="function"&&(a[z]={method:n,path:e,methodName:i}),s){let f=Reflect.getOwnMetadata($,t.constructor)??[];return f.push({method:n,path:e,methodName:i}),Reflect.defineMetadata($,f,t.constructor),o}return t}}a(x,"createMethodDecorator");var De=x("GET"),Ne=x("POST"),Ce=x("PUT"),$e=x("DELETE"),Ie=x("PATCH");function Ae(...n){return (e,t,r)=>{if(t==null){let o=Reflect.getOwnMetadata(v,e)??[];Reflect.defineMetadata(v,[...o,...n],e);return}if(r!==void 0){if(r?.value){let o=r.value[E]??[];r.value[E]=[...o,...n];}return r}if(typeof e=="function"){let o=e[E]??[];e[E]=[...o,...n];}if(typeof e=="function"&&t?.kind==="class"){let o=Reflect.getOwnMetadata(v,e)??[];Reflect.defineMetadata(v,[...o,...n],e);}return e}}a(Ae,"RouteGuards");function Ge(){return (n,e,t)=>t!==void 0?(t?.value&&(t.value[I]=true),t):(typeof n=="function"&&(n[I]=true),n)}a(Ge,"NoGuard");function W(n){return Reflect.getOwnMetadata(q,n)}a(W,"getControllerPath");function He(n){return Reflect.getOwnMetadata(v,n)??[]}a(He,"getControllerGuards");function Y(n){let e=new Map,t=n.prototype;for(;t&&t!==Object.prototype;){for(let r of Object.getOwnPropertyNames(t)){if(r==="constructor"||e.has(r))continue;let o=Object.getOwnPropertyDescriptor(t,r);!o||typeof o.value!="function"||e.set(r,o.value);}t=Object.getPrototypeOf(t);}return e}a(Y,"methodsOf");function se(n,e){return Y(n).get(e)}a(se,"methodOf");function ke(n){let e=[],t=new Set;for(let[r,o]of Y(n)){let s=o[z];!s||t.has(r)||(t.add(r),e.push(s));}if(e.length>0)return e;for(let r=n;r&&r!==Function.prototype;r=Object.getPrototypeOf(r)){let o=Reflect.getOwnMetadata($,r)??[];for(let s of o)t.has(s.methodName)||(t.add(s.methodName),e.push(s));}return e}a(ke,"getRouteMetadata");function Fe(n,e){let t=se(n,e),r=t!==void 0&&t[I]===true,o=t!==void 0&&t[E]||[];return r?o:[...ie(n),...o]}a(Fe,"getMethodGuards");function ie(n){return Q(v,n)}a(ie,"controllerGuardsOf");var P=class extends AggregateError{static{a(this,"LifecycleError");}failures;constructor(e){let t=e.map(ce),r=t.length===1?t[0]:`${t.length} lifecycle failures:
|
|
2
|
+
${t.map(o=>` - ${o}`).join(`
|
|
3
|
+
`)}`;super(e.map(o=>o.error),r,e.length===1?{cause:e[0].error}:void 0),this.name="LifecycleError",this.failures=e;}},ae=new Set(["onModuleDestroy","onApplicationShutdown"]);async function J(n,e,t,r={}){let o=[],s=ae.has(t),i=new Set,a$1=[],f=a(async(l,u)=>{if(!(t==="onModuleDestroy"&&!O(u)))try{await u[t](r.signal);}catch(d){o.push({hook:t,token:l,provider:B(l),duringResolve:false,error:d});}},"call");for(let l of e){let u=typeof l=="function"?l:l.provide;if(r.skip?.has(u)||!n.has(u))continue;let d;try{d=await n.resolve(u);}catch(g){o.push({hook:t,token:u,provider:B(u),duringResolve:true,error:g});continue}!d||typeof d!="object"||typeof d[t]=="function"&&(i.has(d)||(i.add(d),s?a$1.push({token:u,instance:d}):await f(u,d)));}if(s){a$1.reverse(),a$1.sort((l,u)=>(C(u.instance)??-1)-(C(l.instance)??-1));for(let{token:l,instance:u}of a$1)await f(l,u);}return o}a(J,"runLifecycleHook");function ce(n){let e=n.error instanceof Error?n.error.message:String(n.error);return n.duringResolve?`${n.provider} could not be resolved for ${n.hook}: ${e}`:`${n.provider}.${n.hook}() failed: ${e}`}a(ce,"describeFailure");function B(n){return typeof n=="function"?n.name:n instanceof b?n.toString():String(n)}a(B,"tokenName");var X=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 o of r.providers)t.add(o);t.size>0&&e.register(...t);for(let r of this.sortedModules){e.register(...r.providers);for(let o of r.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&&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 o of r.controllers)e.has(o)||(e.add(o),t.push(o));for(let o of r.metadata.providers??[])typeof o=="function"&&W(o)!==void 0&&!e.has(o)&&(e.add(o),t.push(o));}return t}getAllGateways(){let e=new Set,t=[];for(let r of this.sortedModules)for(let o of r.providers)typeof o=="function"&&i$1(o)!==void 0&&!e.has(o)&&(e.add(o),t.push(o));return t}async callLifecycleHooks(e,t,r,o={}){let s=await J(e,this.getAllProviders(),t,{...o,signal:r});if(s.length>0)throw new P(s)}resolveModule(e){let t=d(e),r=typeof t=="object"&&"module"in t,o$1=r?t.module:t,s=this.resolved.get(o$1);if(s)return r&&this.mergeDynamicModule(s,e),s;let i=n(o$1)??{},a=r?e:{},f=[...i.controllers??[],...a.controllers??[]],l=[...i.providers??[],...a.providers??[]],u=[...i.exports??[],...a.exports??[]],d$1=l.map(h=>h&&typeof h=="object"&&"forwardRef"in h?d(h):h),g=u.map(h=>h&&typeof h=="object"&&"forwardRef"in h?d(h):h),M={imports:[...i.imports??[],...a.imports??[]],controllers:f,providers:d$1,exports:g},G={type:o$1,metadata:M,controllers:f,providers:[...f,...d$1],exports:new Set(g),global:r?e.global??o(o$1):o(o$1)};this.resolved.set(o$1,G);for(let h of M.imports??[])this.resolveModule(h);return G}mergeDynamicModule(e,t){if(t.controllers&&t.controllers.length>0&&(e.controllers.push(...t.controllers),e.providers.push(...t.controllers),e.metadata.controllers=[...e.metadata.controllers??[],...t.controllers]),t.providers&&t.providers.length>0){let r=t.providers.map(o=>o&&typeof o=="object"&&"forwardRef"in o?d(o):o);e.providers.push(...r),e.metadata.providers=[...e.metadata.providers??[],...r];}if(t.exports&&t.exports.length>0){let r=t.exports.map(o=>o&&typeof o=="object"&&"forwardRef"in o?d(o):o);for(let o of r)e.exports.add(o);e.metadata.exports=[...e.metadata.exports??[],...r];}if(t.imports&&t.imports.length>0){e.metadata.imports=[...e.metadata.imports??[],...t.imports];for(let r of t.imports)this.resolveModule(r);}t.global===true&&(e.global=true);}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 o=this.getModuleType(r),s=this.resolved.get(o);if(s)for(let i of s.exports)t.add(i);}for(let r of this.sortedModules)if(r.global)for(let o of r.providers)t.add(this.getProviderToken(o));return t}validateExports(){for(let e of this.sortedModules){let t=new Set(e.providers.map(o=>this.getProviderToken(o))),r=this.collectImportedExports(e);for(let o of e.exports)if(!t.has(o)&&!r.has(o)){let s=typeof o=="function"?o.name:String(o);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(e=[]){let t=new Set(e),r=[];for(let o of this.sortedModules){let s=this.getVisibleTokens(o);for(let i of o.providers){let a=typeof i=="function"?i.name:Z(i.provide);for(let f of fe(i))!s.has(f)&&!t.has(f)&&r.push(`${o.type.name}: ${a} depends on ${Z(f)}, but it is not provided in this module and not exported by any imported module`);}}if(r.length>0)throw new Error(r.join(`
|
|
4
|
+
`))}getProviderToken(e){return typeof e=="function"?e:e.provide}collectImportedExports(e){let t=new Set;for(let r of e.metadata.imports??[]){let o=this.getModuleType(r),s=this.resolved.get(o);if(s)for(let i of s.exports)t.add(i);}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 o=this.getModuleType(r),s=this.resolved.get(o);if(!s||!s.exports.has(t))continue;let i=this.findProvider(s,t);if(i)return i;let a=this.findReExportedProvider(s,t);if(a)return a}}getModuleType(e){let t=d(e);return typeof t=="object"&&"module"in t?t.module:t}topologicalSort(){let e=new Set,t=new Set,r=[],o=a(s=>{if(e.has(s))return;if(t.has(s))throw new Error(`Circular module dependency detected: ${s.name}`);t.add(s);let i=this.resolved.get(s);if(i){for(let a of i.metadata.imports??[])o(this.getModuleType(a));t.delete(s),e.add(s),r.push(i);}},"visit");for(let[s]of this.resolved)o(s);return r}};function Z(n){return typeof n=="function"?n.name:String(n)}a(Z,"tokenName");function K(n){let e=i(n),t=j(n),r=k(n),o=Math.max(e.length,...[...t.keys()].map(i=>i+1),0),s=[];for(let i=0;i<o;i++){if(r.has(i))continue;let a=t.get(i)??e[i];a!==void 0&&s.push(a);}return s}a(K,"classDependencies");function fe(n){return typeof n=="function"?K(n):"useClass"in n?K(d(n.useClass)):"useFactory"in n?(n.inject??[]).map(e=>d(e)):"useExisting"in n?[d(n.useExisting)]:[]}a(fe,"providerDependencies");function ue(n,e,t,r){var o=arguments.length,s=o<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(n,e,t,r);else for(var a=n.length-1;a>=0;a--)(i=n[a])&&(s=(o<3?i(s):o>3?i(e,t,s):i(e,t))||s);return o>3&&s&&Object.defineProperty(e,t,s),s}a(ue,"_ts_decorate");function ee(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)}a(ee,"_ts_metadata");var y=class{static{a(this,"EventEmitter2");}handlers=new Map;pending=new Map;onError;constructor(){this.onError=de;}setOptions(e){e.onError&&(this.onError=e.onError);}subscribe(e,t,r){let o=this.handlers.get(e)??[];o.push({instance:r?.instance??{},methodName:r?.methodName??"anonymous",handler:t}),this.handlers.set(e,o);}registerHandler(e,t,r){let o=t[r].bind(t);this.subscribe(e,o,{instance:t,methodName:r});}async emit(e){let t=this.handlers.get(e.type);if(!t||t.length===0)return;let r=this.executeHandlers(t,e);this.pending.set(r,e.type);try{await r;}finally{this.pending.delete(r);}}emitAsync(e){let t=this.handlers.get(e.type);if(!t||t.length===0)return Promise.resolve([]);let r=this.executeHandlers(t,e).then(o=>(this.pending.delete(r),o),()=>(this.pending.delete(r),[]));return this.pending.set(r,e.type),r}async waitForAllDone(...e){for(;;){let t=this.getPending(e);if(t.length===0)break;await Promise.allSettled(t);}}getPending(e){if(e.length===0)return [...this.pending.keys()];let t=[];for(let[r,o]of this.pending)e.includes(o)&&t.push(r);return t}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();}async executeHandlers(e,t){return (await Promise.allSettled(e.map(async o=>{let s=Date.now();try{return {value:await o.handler(t),durationMs:Date.now()-s}}catch(i){return {err:i,durationMs:Date.now()-s,threw:true}}}))).map((o,s)=>{let i=e[s],a=`${i.instance.constructor?.name??"Unknown"}.${i.methodName}`;if(o.status==="fulfilled"&&!("threw"in o.value))return {name:a,status:"success",value:o.value.value,durationMs:o.value.durationMs};let f=o.status==="fulfilled"?o.value.err:o.reason,l=f instanceof Error?f.message:typeof f=="string"?f:String(f),u=o.status==="fulfilled"?o.value.durationMs:0;return this.onError(f,t.type,a),{name:a,status:"failed",error:l,durationMs:u}})}};y=ue([e(),ee("design:type",Function),ee("design:paramtypes",[])],y);function de(n,e,t){console.error(`[EventEmitter2] Handler "${t}" failed for event "${e}":`,n);}a(de,"defaultErrorHandler");var A=Symbol.for("truxie:on-event");function st(n){return (e,t,r)=>{let o=Reflect.getOwnMetadata(A,e.constructor)??[];o.push({eventType:n,methodName:String(t)}),Reflect.defineMetadata(A,o,e.constructor);}}a(st,"OnEvent");function te(n){return Reflect.getOwnMetadata(A,n)??[]}a(te,"getOnEventMetadata");async function dt(n,e){let t=await n.resolve(y);for(let r of e){let o=le(r);if(!o)continue;let s=te(o);if(s.length===0)continue;let i=typeof r=="function"?r:r.provide,a;try{a=await n.resolve(i);}catch{continue}for(let f of s)typeof a[f.methodName]=="function"&&t.registerHandler(f.eventType,a,f.methodName);}}a(dt,"scanEventHandlers");function le(n){return typeof n=="function"?h(n)?n:null:"useClass"in n?n.useClass:null}a(le,"getProviderClass");export{V as a,Q as b,je as c,De as d,Ne as e,Ce as f,$e as g,Ie as h,Ae as i,Ge as j,W as k,He as l,ke as m,Fe as n,P as o,J as p,ce as q,X as r,y as s,st as t,dt as u};
|
|
@@ -21,6 +21,15 @@ declare class Container {
|
|
|
21
21
|
/** The container that actually holds the registration, or null. */
|
|
22
22
|
private findOwner;
|
|
23
23
|
createChild(): Container;
|
|
24
|
+
/**
|
|
25
|
+
* Destroy every cached instance, then detach from the parent.
|
|
26
|
+
*
|
|
27
|
+
* A throwing `onModuleDestroy` does not stop the walk: stopping there left
|
|
28
|
+
* the remaining instances open and the child attached to its parent, so a
|
|
29
|
+
* per-request container with one failing hook leaked on every request. The
|
|
30
|
+
* failures are thrown once everything has been visited — the error itself
|
|
31
|
+
* when there is one, an `AggregateError` when there are several.
|
|
32
|
+
*/
|
|
24
33
|
dispose(): Promise<void>;
|
|
25
34
|
private createInstance;
|
|
26
35
|
private instantiateClass;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as Container, E as EventBusOptions, a as EventEmitter2 } from './event-bus-
|
|
2
|
-
export { D as DomainEvent, b as EventHandler } from './event-bus-
|
|
1
|
+
import { C as Container, E as EventBusOptions, a as EventEmitter2 } from './event-bus-CqsK7FDO.js';
|
|
2
|
+
export { D as DomainEvent, b as EventHandler } from './event-bus-CqsK7FDO.js';
|
|
3
3
|
import { T as Token, F as ForwardRef, I as InjectableOptions, a as Type, M as ModuleMetadata, D as DynamicModule, P as Provider, b as ModuleAsyncOptions, c as InjectionToken } from './types-BonRQLDb.js';
|
|
4
4
|
export { C as ClassProvider, E as ExistingProvider, d as FactoryProvider, e as ModuleOptionsFactory, S as Scope, V as ValueProvider } from './types-BonRQLDb.js';
|
|
5
5
|
import { W as WsPeer, a as WsMessage } from './types-BHt3a4dp.js';
|
|
@@ -39,6 +39,34 @@ declare function Global(): ClassDecorator;
|
|
|
39
39
|
declare function getModuleMetadata(target: Function): ModuleMetadata | undefined;
|
|
40
40
|
declare function isGlobalModule(target: Function): boolean;
|
|
41
41
|
|
|
42
|
+
/** One provider that failed during a lifecycle phase. */
|
|
43
|
+
interface LifecycleFailure {
|
|
44
|
+
/** The phase that was running. */
|
|
45
|
+
hook: string;
|
|
46
|
+
/** The provider's token. */
|
|
47
|
+
token: Token;
|
|
48
|
+
/** A readable name for the token. */
|
|
49
|
+
provider: string;
|
|
50
|
+
/** True when the provider could not be BUILT; false when its hook threw. */
|
|
51
|
+
duringResolve: boolean;
|
|
52
|
+
error: unknown;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Every failure of a lifecycle phase, raised once the phase has visited every
|
|
56
|
+
* provider. `errors` holds the original errors, `failures` says where each
|
|
57
|
+
* came from.
|
|
58
|
+
*/
|
|
59
|
+
declare class LifecycleError extends AggregateError {
|
|
60
|
+
readonly failures: LifecycleFailure[];
|
|
61
|
+
constructor(failures: LifecycleFailure[]);
|
|
62
|
+
}
|
|
63
|
+
interface RunLifecycleHookOptions {
|
|
64
|
+
/** Passed to the hook — `onApplicationShutdown(signal)`. */
|
|
65
|
+
signal?: string;
|
|
66
|
+
/** Tokens not to resolve at all — the ones that already failed to build. */
|
|
67
|
+
skip?: ReadonlySet<Token>;
|
|
68
|
+
}
|
|
69
|
+
|
|
42
70
|
interface ResolvedModule {
|
|
43
71
|
type: Type;
|
|
44
72
|
metadata: ModuleMetadata;
|
|
@@ -68,7 +96,14 @@ declare class ModuleRegistry {
|
|
|
68
96
|
* Discovered from providers[] — same pattern as controllers.
|
|
69
97
|
*/
|
|
70
98
|
getAllGateways(): Type[];
|
|
71
|
-
|
|
99
|
+
/**
|
|
100
|
+
* Call `hook` on every provider of every scanned module. Teardown hooks run
|
|
101
|
+
* dependents first (see `runLifecycleHook`).
|
|
102
|
+
*
|
|
103
|
+
* @throws LifecycleError once every provider has been visited, if any
|
|
104
|
+
* provider failed to build or its hook threw.
|
|
105
|
+
*/
|
|
106
|
+
callLifecycleHooks(container: Container, hook: string, signal?: string, options?: Omit<RunLifecycleHookOptions, 'signal'>): Promise<void>;
|
|
72
107
|
private resolveModule;
|
|
73
108
|
/**
|
|
74
109
|
* Append a second dynamic-module call's metadata into an already-resolved entry.
|
|
@@ -1438,7 +1473,22 @@ declare class TruxieApplication {
|
|
|
1438
1473
|
createHandler(options: Omit<CreatePipelineOptions, 'handler'> & {
|
|
1439
1474
|
handler: HandlerFn;
|
|
1440
1475
|
}): (ctx: ExecutionContext) => Promise<unknown>;
|
|
1476
|
+
/**
|
|
1477
|
+
* Run `onModuleDestroy`, then `onApplicationShutdown`, each dependents-first,
|
|
1478
|
+
* and dispose the container.
|
|
1479
|
+
*
|
|
1480
|
+
* Best-effort: a hook that throws does not stop the rest. Every failure is
|
|
1481
|
+
* collected and raised as one `LifecycleError` after the application is
|
|
1482
|
+
* fully torn down.
|
|
1483
|
+
*/
|
|
1441
1484
|
shutdown(): Promise<void>;
|
|
1485
|
+
private teardown;
|
|
1486
|
+
/**
|
|
1487
|
+
* Release what a failed boot already started — pools, workers, timers —
|
|
1488
|
+
* so the process is not kept alive by an application nobody holds.
|
|
1489
|
+
* Providers that failed to build are not built again just to be torn down.
|
|
1490
|
+
*/
|
|
1491
|
+
private abortInit;
|
|
1442
1492
|
private createRequestContext;
|
|
1443
1493
|
private matchGatewayPath;
|
|
1444
1494
|
private initGateways;
|
|
@@ -1449,4 +1499,4 @@ declare class TruxieFactory {
|
|
|
1449
1499
|
static create(rootModule: Type | DynamicModule, options?: ApplicationOptions): Promise<TruxieApplication>;
|
|
1450
1500
|
}
|
|
1451
1501
|
|
|
1452
|
-
export { ApiDoc, type ApiDocOptions, type ApiErrorDoc, type ApiExampleDoc, type ApiHeaderDoc, type ApiRequestDoc, type ApiResponseDoc, type ApiSecurityRequirement, AppError, type ApplicationOptions, Auth, type AuthExtractorFn, BaseExecutionContext, Body, Catch, type CompiledRoute, ConfigurableModuleBuilder, type ConfigurableModuleBuilderResult, type ConfigurableModuleClass, ConflictError, Container, Controller, ControllerRouter, Cookie, type CreatePipelineOptions, type CustomParamOptions, DefaultValuePipe, Delete, type DescribeRouteInputOptions, DiscoveryService, DynamicModule, EventBusOptions, EventEmitter2, 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 HttpDispatchResult, type HttpMethod, type ICanActivateGuard, type IUseCase, Inject, Injectable, InjectableOptions, InjectionToken, type Interceptor, type InterceptorRef, Ip, type JsonSchemaObject, type KeyDrift, 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, REDIRECT_BRAND, REMOTE_ADDRESS_KEY, RawBody, type RedirectResult, RequestAbortedError, RouteGuards, type RouteInput, type RouteInputDrift, type RouteMatch, type RouteMetadata, type RouteParamMetadata, type RouteParamType, TRUST_PROXY_KEY, type ToJsonSchema, type ToJsonSchemaOptions, Token, TruxieApplication, TruxieFactory, Type, UOW_INSTANCE_KEY, UOW_SESSION_KEY, UnauthorizedError, type UnitOfWork, type UnitOfWorkFactory, UnitOfWorkInterceptor, UseFilters, UseInterceptors, UseMiddleware, UsePipes, UserAgent, ValidationError, type WsHooks, type WsHooksAdapters, apiResponses, applyJsonBody, clientIp, clientSafeError, contributeApiDoc, createAsyncOptionsProviders, createParamDecorator, createPipeline, defineAuth, describeRouteInput, forwardRef, getApiDoc, getControllerGuards, getControllerPath, getEffectiveInterceptors, getEffectiveMiddlewares, getInterceptorsMetadata, getMethodGuards, getMethodInterceptors, getMethodMiddlewares, getMiddlewaresMetadata, getModuleMetadata, getRequestHeaders, getRouteMetadata, getRouteParams, isGlobalModule, isJsonSchemaObject, isRedirect, isServerless, redirect, resolveForwardRef, resolveParamArgs, routeInputDrift };
|
|
1502
|
+
export { ApiDoc, type ApiDocOptions, type ApiErrorDoc, type ApiExampleDoc, type ApiHeaderDoc, type ApiRequestDoc, type ApiResponseDoc, type ApiSecurityRequirement, AppError, type ApplicationOptions, Auth, type AuthExtractorFn, BaseExecutionContext, Body, Catch, type CompiledRoute, ConfigurableModuleBuilder, type ConfigurableModuleBuilderResult, type ConfigurableModuleClass, ConflictError, Container, Controller, ControllerRouter, Cookie, type CreatePipelineOptions, type CustomParamOptions, DefaultValuePipe, Delete, type DescribeRouteInputOptions, DiscoveryService, DynamicModule, EventBusOptions, EventEmitter2, 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 HttpDispatchResult, type HttpMethod, type ICanActivateGuard, type IUseCase, Inject, Injectable, InjectableOptions, InjectionToken, type Interceptor, type InterceptorRef, Ip, type JsonSchemaObject, type KeyDrift, LifecycleError, type LifecycleFailure, 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, REDIRECT_BRAND, REMOTE_ADDRESS_KEY, RawBody, type RedirectResult, RequestAbortedError, RouteGuards, type RouteInput, type RouteInputDrift, type RouteMatch, type RouteMetadata, type RouteParamMetadata, type RouteParamType, TRUST_PROXY_KEY, type ToJsonSchema, type ToJsonSchemaOptions, Token, TruxieApplication, TruxieFactory, Type, UOW_INSTANCE_KEY, UOW_SESSION_KEY, UnauthorizedError, type UnitOfWork, type UnitOfWorkFactory, UnitOfWorkInterceptor, UseFilters, UseInterceptors, UseMiddleware, UsePipes, UserAgent, ValidationError, type WsHooks, type WsHooksAdapters, apiResponses, applyJsonBody, clientIp, clientSafeError, contributeApiDoc, createAsyncOptionsProviders, createParamDecorator, createPipeline, defineAuth, describeRouteInput, forwardRef, getApiDoc, getControllerGuards, getControllerPath, getEffectiveInterceptors, getEffectiveMiddlewares, getInterceptorsMetadata, getMethodGuards, getMethodInterceptors, getMethodMiddlewares, getMiddlewaresMetadata, getModuleMetadata, getRequestHeaders, getRouteMetadata, getRouteParams, isGlobalModule, isJsonSchemaObject, isRedirect, isServerless, redirect, resolveForwardRef, resolveParamArgs, routeInputDrift };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {l,n,o,b as b$2,p,q,s,c}from'./chunk-CD6QSDG5.js';export{b as Container,d as Controller,h as Delete,q as EventEmitter2,e as Get,p as ModuleRegistry,k as NoGuard,r as OnEvent,i as Patch,f as Post,g as Put,j as RouteGuards,m as getControllerGuards,l as getControllerPath,o as getMethodGuards,n as getRouteMetadata}from'./chunk-CD6QSDG5.js';import {n as n$1,i,j as j$1,k,l as l$1,m as m$1}from'./chunk-RDP32XIU.js';import {b as b$1,p as p$1,i as i$1,j as j$2}from'./chunk-TSJZVSHP.js';export{p as DiscoveryService,m as Global,f as Inject,e as Injectable,b as InjectionToken,l as Module,g as Optional,a as Scope,c as forwardRef,n as getModuleMetadata,o as isGlobalModule,d as resolveForwardRef}from'./chunk-TSJZVSHP.js';import {a}from'./chunk-EI7MMDWY.js';import'reflect-metadata';function se(t,e){if("useFactory"in e&&e.useFactory){let r=e.useFactory;return [{provide:t,useFactory:r,inject:e.inject??[]}]}if("useClass"in e&&e.useClass){let r=e.useClass;return [{provide:t,useFactory:a(async o=>o.createModuleOptions(),"useFactory"),inject:[r]},r]}if("useExisting"in e&&e.useExisting){let r=e.useExisting;return [{provide:t,useFactory:a(async o=>o.createModuleOptions(),"useFactory"),inject:[r]}]}throw new Error("ModuleAsyncOptions must specify one of: useFactory, useClass, or useExisting")}a(se,"createAsyncOptionsProviders");var j=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 b$1(this.description),r=new b$1(this.featureDescription),o=this.onForRoot,s=this.onForFeature;return {ConfigurableModuleClass:class{static{a(this,"ConfigurableModuleClassImpl");}static forRoot(c,d={}){let u={module:this,global:d.global??false,providers:[{provide:e,useValue:c}],exports:[e]};return o&&(u=o(u,c)),u}static forRootAsync(c){let d=se(e,c),u={module:this,imports:c.imports??[],providers:d,exports:[e]};return o&&(u=o(u)),u}static forFeature(c,d={}){let u={module:this,global:d.global??false,providers:[{provide:r,useValue:c}],exports:[r]};return s&&(u=s(u,c)),u}},MODULE_OPTIONS_TOKEN:e,MODULE_FEATURE_TOKEN:r}}};var U=class{static{a(this,"BaseExecutionContext");}nativeRequest;handler;container;query;params;body;bodyParseError;rawBody;formData;auth;data=new Map;metadata=new Map;abortController;constructor(e,r,o,s={},i={},a){this.nativeRequest=e,this.handler=r,this.container=o,this.query=s,this.params=i,this.abortController=a??new AbortController;}getNativeRequest(){return this.nativeRequest}getHandler(){return this.handler}setHandler(e){this.handler=e;}getBody(){return this.body}setBody(e){this.body=e;}getRawBody(){return this.rawBody}setRawBody(e){this.rawBody=e;}getBodyParseError(){return this.bodyParseError}setBodyParseError(e){this.bodyParseError=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,r){this.metadata.set(e,r);}getData(e){return this.data.get(e)}setData(e,r){this.data.set(e,r);}getContainer(){return this.container}setContainer(e){this.container=e;}getSignal(){return this.abortController.signal}abort(e){this.abortController.abort(e);}};function nt(t,e,r=""){if(e!=="")try{t.setBody(JSON.parse(e));}catch(o){$t(e,r)&&t.setBodyParseError(o instanceof Error?o:new Error(String(o)));}}a(nt,"applyJsonBody");function $t(t,e){if(e.toLowerCase().includes("json"))return true;let r=t.trimStart().charAt(0);return r==="{"||r==="["}a($t,"looksLikeJson");var ie=Symbol.for("truxie:filters"),st=Symbol.for("truxie:catch");function it(...t){return (e,r,o)=>{let s=r?e.constructor:e,i=Reflect.getOwnMetadata(ie,s)??[];Reflect.defineMetadata(ie,[...i,...t],s);}}a(it,"UseFilters");function at(...t){return e=>{Reflect.defineMetadata(st,t,e);}}a(at,"Catch");function ae(t){return c(ie,t)}a(ae,"getFiltersMetadata");function ce(t){return Reflect.getOwnMetadata(st,t)??[]}a(ce,"getCatchMetadata");var m=class extends Error{static{a(this,"AppError");}statusCode;status;isOperational;constructor(e,r){super(e),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);}},G=class extends m{static{a(this,"NotFoundError");}constructor(e="Resource not found"){super(e,404);}},y=class extends m{static{a(this,"ValidationError");}errors;constructor(e="Validation failed",r){super(e,400),this.errors=r;}},z=class extends m{static{a(this,"UnauthorizedError");}constructor(e="Not authorized"){super(e,401);}},C=class extends m{static{a(this,"ForbiddenError");}constructor(e="Access forbidden"){super(e,403);}},W=class extends m{static{a(this,"ConflictError");}constructor(e="Resource conflict"){super(e,409);}},v=class extends m{static{a(this,"RequestAbortedError");}constructor(e="Request aborted by client"){super(e,499);}};function _(t,e,r){return async o=>{let s=[...e.middlewares??[],...r.middlewares??[]],i=[...e.guards??[],...r.guards??[]],a$1=[...e.interceptors??[],...r.interceptors??[]],c=[...e.pipes??[],...r.pipes??[]],d=[...e.filters??[],...r.filters??[]],u=await E(t,d);try{x(o);let f=await E(t,s);return await Bt(o,f,async()=>{x(o);let l=await E(t,i);for(let S of l)if(x(o),!await S.canActivate(o))throw new C("Access denied by guard");x(o);let p=await E(t,c);for(let S of p)x(o),await S.transform(o);x(o);let h=await E(t,a$1),ve=a(async()=>(x(o),r.handler(o)),"handlerCall");return h.length===0?ve():h.reduceRight((S,De)=>async()=>(x(o),De.intercept(o,S)),ve)()})}catch(f){return jt(f,o,u)}}}a(_,"createPipeline");async function Bt(t,e,r){return e.length===0?r():e.reduceRight((s,i)=>()=>i.use(t,s),r)()}a(Bt,"runMiddlewareChain");function x(t){if(t.getSignal().aborted)throw new v}a(x,"checkAborted");async function jt(t,e,r){for(let o of r){let s=ce(o.constructor);if(s.length===0||t instanceof Error&&s.some(a=>t instanceof a))return o.catch(t,e)}throw t}a(jt,"handleError");async function E(t,e){let r=[];for(let o of e){if(typeof o!="function"){r.push(o);continue}let s=o;if(t.has(s)){r.push(await t.resolve(s));continue}if(Ut(s))throw new Error(`${s.name} declares constructor dependencies but is not registered as a provider, so they cannot be injected. Add it to a module's \`providers\`, or read what it needs off the ExecutionContext instead (\`ctx.getContainer().resolve(...)\`).`);r.push(new s);}return r}a(E,"resolveRefs");function Ut(t){return i$1(t).length>0||j$2(t).size>0?true:(Reflect.getMetadata?.("design:paramtypes",t)??[]).length>0}a(Ut,"declaresDependencies");var ue=Symbol.for("truxie:interceptors"),de=Symbol.for("truxie:method:interceptors");function ct(...t){return (e,r,o)=>{if(r!==void 0){let i=o?.value??e,a=i[de]??[];return i[de]=[...a,...t],o}let s=Reflect.getOwnMetadata(ue,e)??[];Reflect.defineMetadata(ue,[...s,...t],e);}}a(ct,"UseInterceptors");function fe(t){return c(ue,t)}a(fe,"getInterceptorsMetadata");function le(t,e){let o=t.prototype?.[e];return typeof o=="function"&&o[de]||[]}a(le,"getMethodInterceptors");function H(t,e){return [...fe(t),...le(t,e)]}a(H,"getEffectiveInterceptors");var pe="uow:session",he="uow:instance",K=class{static{a(this,"UnitOfWorkInterceptor");}factory;constructor(e){this.factory=e;}async intercept(e,r){let o=this.factory();await o.start(),e.setData(pe,o.getContext()),e.setData(he,o);try{let s=await r();return await o.commit(),s}catch(s){throw await o.rollback(),s}}};var me=Symbol.for("truxie:middlewares"),ye=Symbol.for("truxie:method:middlewares");function ut(...t){return (e,r,o)=>{if(r!==void 0){let i=o?.value??e,a=i[ye]??[];return i[ye]=[...a,...t],o}let s=Reflect.getOwnMetadata(me,e)??[];Reflect.defineMetadata(me,[...s,...t],e);}}a(ut,"UseMiddleware");function ge(t){return c(me,t)}a(ge,"getMiddlewaresMetadata");function we(t,e){let o=t.prototype?.[e];return typeof o=="function"&&o[ye]||[]}a(we,"getMethodMiddlewares");function Y(t,e){return [...ge(t),...we(t,e)]}a(Y,"getEffectiveMiddlewares");var xe=Symbol.for("truxie:pipes");function dt(...t){return (e,r,o)=>{let s=r?e.constructor:e,i=Reflect.getOwnMetadata(xe,s)??[];Reflect.defineMetadata(xe,[...i,...t],s);}}a(dt,"UsePipes");function Ee(t){return c(xe,t)}a(Ee,"getPipesMetadata");var Gt=/^[0-9a-fA-F]{24}$/,L=class{static{a(this,"ParseIdPipe");}paramName;constructor(e="id"){this.paramName=e;}transform(e){let o=e.getParams()[this.paramName];if(!o||!Gt.test(o))throw new y(`Invalid ${this.paramName}: must be a valid ObjectId`)}};var V=class{static{a(this,"ParseIntPipe");}transform(e){let r=Number(e);if(!Number.isInteger(r)||e===""||e===null||e===void 0)throw new y(`Expected an integer, received: ${JSON.stringify(e)}`);return r}};function ft(t){return {transform(e){return e??t}}}a(ft,"DefaultValuePipe");var J=class{static{a(this,"DomainEvent");}payload;timestamp;constructor(e){this.payload=e,this.timestamp=Date.now();}};function lt(t){let e=t,r=typeof e?.statusCode=="number"&&e.statusCode>=400&&e.statusCode<=599?e.statusCode:500,s=(e?.isOperational===true||r>=400&&r<500)&&typeof e?.message=="string"&&e.message.length>0?e.message:"Internal server error";return {status:r,message:s}}a(lt,"clientSafeError");var R=class{static{a(this,"ControllerRouter");}routes=[];globalPrefix;constructor(e=""){this.globalPrefix=e;}register(...e){for(let r of e){let o$1=l(r)??"",s=n(r);for(let i of s){let a=pt(`${this.globalPrefix}/${o$1}/${i.path}`);Wt(a,r.name,i.methodName),this.checkDuplicate(a,i.method,r.name,i.methodName);let{pattern:c,paramNames:d}=ht(a),u=o(r,i.methodName),f=H(r,i.methodName),l=Y(r,i.methodName);this.routes.push({method:i.method,pattern:c,paramNames:d,controllerClass:r,methodName:i.methodName,guardClasses:u,interceptorRefs:f,middlewareRefs:l,pipeRefs:Ee(r),filterRefs:ae(r),rawPath:a});}}this.routes.sort((r,o)=>mt(r.rawPath)-mt(o.rawPath));}checkDuplicate(e,r,o,s){let{pattern:i}=ht(e),a=this.routes.find(c=>c.method===r&&c.pattern.source===i.source);if(a){let c=a.rawPath===e?e:`${a.rawPath} / ${e}`;throw new Error(`Duplicate route: ${r} ${c}
|
|
1
|
+
import {k as k$1,m as m$1,n,a as a$1,r,s,u,o,p as p$1,q,b as b$2}from'./chunk-TB76O5JV.js';export{a as Container,c as Controller,g as Delete,s as EventEmitter2,d as Get,o as LifecycleError,r as ModuleRegistry,j as NoGuard,t as OnEvent,h as Patch,e as Post,f as Put,i as RouteGuards,l as getControllerGuards,k as getControllerPath,n as getMethodGuards,m as getRouteMetadata}from'./chunk-TB76O5JV.js';import {n as n$1,i,j,k as k$2,l,m as m$2}from'./chunk-RDP32XIU.js';import {b as b$1,p,i as i$1,j as j$1}from'./chunk-TSJZVSHP.js';export{p as DiscoveryService,m as Global,f as Inject,e as Injectable,b as InjectionToken,l as Module,g as Optional,a as Scope,c as forwardRef,n as getModuleMetadata,o as isGlobalModule,d as resolveForwardRef}from'./chunk-TSJZVSHP.js';import {a}from'./chunk-EI7MMDWY.js';import'reflect-metadata';function ae(t,e){if("useFactory"in e&&e.useFactory){let r=e.useFactory;return [{provide:t,useFactory:r,inject:e.inject??[]}]}if("useClass"in e&&e.useClass){let r=e.useClass;return [{provide:t,useFactory:a(async o=>o.createModuleOptions(),"useFactory"),inject:[r]},r]}if("useExisting"in e&&e.useExisting){let r=e.useExisting;return [{provide:t,useFactory:a(async o=>o.createModuleOptions(),"useFactory"),inject:[r]}]}throw new Error("ModuleAsyncOptions must specify one of: useFactory, useClass, or useExisting")}a(ae,"createAsyncOptionsProviders");var G=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 b$1(this.description),r=new b$1(this.featureDescription),o=this.onForRoot,s=this.onForFeature;return {ConfigurableModuleClass:class{static{a(this,"ConfigurableModuleClassImpl");}static forRoot(c,d={}){let u={module:this,global:d.global??false,providers:[{provide:e,useValue:c}],exports:[e]};return o&&(u=o(u,c)),u}static forRootAsync(c){let d=ae(e,c),u={module:this,imports:c.imports??[],providers:d,exports:[e]};return o&&(u=o(u)),u}static forFeature(c,d={}){let u={module:this,global:d.global??false,providers:[{provide:r,useValue:c}],exports:[r]};return s&&(u=s(u,c)),u}},MODULE_OPTIONS_TOKEN:e,MODULE_FEATURE_TOKEN:r}}};var z=class{static{a(this,"BaseExecutionContext");}nativeRequest;handler;container;query;params;body;bodyParseError;rawBody;formData;auth;data=new Map;metadata=new Map;abortController;constructor(e,r,o,s={},i={},a){this.nativeRequest=e,this.handler=r,this.container=o,this.query=s,this.params=i,this.abortController=a??new AbortController;}getNativeRequest(){return this.nativeRequest}getHandler(){return this.handler}setHandler(e){this.handler=e;}getBody(){return this.body}setBody(e){this.body=e;}getRawBody(){return this.rawBody}setRawBody(e){this.rawBody=e;}getBodyParseError(){return this.bodyParseError}setBodyParseError(e){this.bodyParseError=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,r){this.metadata.set(e,r);}getData(e){return this.data.get(e)}setData(e,r){this.data.set(e,r);}getContainer(){return this.container}setContainer(e){this.container=e;}getSignal(){return this.abortController.signal}abort(e){this.abortController.abort(e);}};function at(t,e,r=""){if(e!=="")try{t.setBody(JSON.parse(e));}catch(o){Ut(e,r)&&t.setBodyParseError(o instanceof Error?o:new Error(String(o)));}}a(at,"applyJsonBody");function Ut(t,e){if(e.toLowerCase().includes("json"))return true;let r=t.trimStart().charAt(0);return r==="{"||r==="["}a(Ut,"looksLikeJson");var ce=Symbol.for("truxie:filters"),ct=Symbol.for("truxie:catch");function ut(...t){return (e,r,o)=>{let s=r?e.constructor:e,i=Reflect.getOwnMetadata(ce,s)??[];Reflect.defineMetadata(ce,[...i,...t],s);}}a(ut,"UseFilters");function dt(...t){return e=>{Reflect.defineMetadata(ct,t,e);}}a(dt,"Catch");function ue(t){return b$2(ce,t)}a(ue,"getFiltersMetadata");function de(t){return Reflect.getOwnMetadata(ct,t)??[]}a(de,"getCatchMetadata");var m=class extends Error{static{a(this,"AppError");}statusCode;status;isOperational;constructor(e,r){super(e),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);}},W=class extends m{static{a(this,"NotFoundError");}constructor(e="Resource not found"){super(e,404);}},y=class extends m{static{a(this,"ValidationError");}errors;constructor(e="Validation failed",r){super(e,400),this.errors=r;}},H=class extends m{static{a(this,"UnauthorizedError");}constructor(e="Not authorized"){super(e,401);}},P=class extends m{static{a(this,"ForbiddenError");}constructor(e="Access forbidden"){super(e,403);}},L=class extends m{static{a(this,"ConflictError");}constructor(e="Resource conflict"){super(e,409);}},C=class extends m{static{a(this,"RequestAbortedError");}constructor(e="Request aborted by client"){super(e,499);}};function T(t,e,r){return async o=>{let s=[...e.middlewares??[],...r.middlewares??[]],i=[...e.guards??[],...r.guards??[]],a$1=[...e.interceptors??[],...r.interceptors??[]],c=[...e.pipes??[],...r.pipes??[]],d=[...e.filters??[],...r.filters??[]],u=await E(t,d);try{x(o);let f=await E(t,s);return await Gt(o,f,async()=>{x(o);let l=await E(t,i);for(let S of l)if(x(o),!await S.canActivate(o))throw new P("Access denied by guard");x(o);let p=await E(t,c);for(let S of p)x(o),await S.transform(o);x(o);let h=await E(t,a$1),Se=a(async()=>(x(o),r.handler(o)),"handlerCall");return h.length===0?Se():h.reduceRight((S,Ie)=>async()=>(x(o),Ie.intercept(o,S)),Se)()})}catch(f){return zt(f,o,u)}}}a(T,"createPipeline");async function Gt(t,e,r){return e.length===0?r():e.reduceRight((s,i)=>()=>i.use(t,s),r)()}a(Gt,"runMiddlewareChain");function x(t){if(t.getSignal().aborted)throw new C}a(x,"checkAborted");async function zt(t,e,r){for(let o of r){let s=de(o.constructor);if(s.length===0||t instanceof Error&&s.some(a=>t instanceof a))return o.catch(t,e)}throw t}a(zt,"handleError");async function E(t,e){let r=[];for(let o of e){if(typeof o!="function"){r.push(o);continue}let s=o;if(t.has(s)){r.push(await t.resolve(s));continue}if(Wt(s))throw new Error(`${s.name} declares constructor dependencies but is not registered as a provider, so they cannot be injected. Add it to a module's \`providers\`, or read what it needs off the ExecutionContext instead (\`ctx.getContainer().resolve(...)\`).`);r.push(new s);}return r}a(E,"resolveRefs");function Wt(t){return i$1(t).length>0||j$1(t).size>0?true:(Reflect.getMetadata?.("design:paramtypes",t)??[]).length>0}a(Wt,"declaresDependencies");var fe=Symbol.for("truxie:interceptors"),le=Symbol.for("truxie:method:interceptors");function ft(...t){return (e,r,o)=>{if(r!==void 0){let i=o?.value??e,a=i[le]??[];return i[le]=[...a,...t],o}let s=Reflect.getOwnMetadata(fe,e)??[];Reflect.defineMetadata(fe,[...s,...t],e);}}a(ft,"UseInterceptors");function pe(t){return b$2(fe,t)}a(pe,"getInterceptorsMetadata");function he(t,e){let o=t.prototype?.[e];return typeof o=="function"&&o[le]||[]}a(he,"getMethodInterceptors");function K(t,e){return [...pe(t),...he(t,e)]}a(K,"getEffectiveInterceptors");var me="uow:session",ye="uow:instance",Y=class{static{a(this,"UnitOfWorkInterceptor");}factory;constructor(e){this.factory=e;}async intercept(e,r){let o=this.factory();await o.start(),e.setData(me,o.getContext()),e.setData(ye,o);try{let s=await r();return await o.commit(),s}catch(s){throw await o.rollback(),s}}};var ge=Symbol.for("truxie:middlewares"),we=Symbol.for("truxie:method:middlewares");function lt(...t){return (e,r,o)=>{if(r!==void 0){let i=o?.value??e,a=i[we]??[];return i[we]=[...a,...t],o}let s=Reflect.getOwnMetadata(ge,e)??[];Reflect.defineMetadata(ge,[...s,...t],e);}}a(lt,"UseMiddleware");function xe(t){return b$2(ge,t)}a(xe,"getMiddlewaresMetadata");function Ee(t,e){let o=t.prototype?.[e];return typeof o=="function"&&o[we]||[]}a(Ee,"getMethodMiddlewares");function V(t,e){return [...xe(t),...Ee(t,e)]}a(V,"getEffectiveMiddlewares");var Re=Symbol.for("truxie:pipes");function pt(...t){return (e,r,o)=>{let s=r?e.constructor:e,i=Reflect.getOwnMetadata(Re,s)??[];Reflect.defineMetadata(Re,[...i,...t],s);}}a(pt,"UsePipes");function be(t){return b$2(Re,t)}a(be,"getPipesMetadata");var Ht=/^[0-9a-fA-F]{24}$/,J=class{static{a(this,"ParseIdPipe");}paramName;constructor(e="id"){this.paramName=e;}transform(e){let o=e.getParams()[this.paramName];if(!o||!Ht.test(o))throw new y(`Invalid ${this.paramName}: must be a valid ObjectId`)}};var Q=class{static{a(this,"ParseIntPipe");}transform(e){let r=Number(e);if(!Number.isInteger(r)||e===""||e===null||e===void 0)throw new y(`Expected an integer, received: ${JSON.stringify(e)}`);return r}};function ht(t){return {transform(e){return e??t}}}a(ht,"DefaultValuePipe");var X=class{static{a(this,"DomainEvent");}payload;timestamp;constructor(e){this.payload=e,this.timestamp=Date.now();}};function mt(t){let e=t,r=typeof e?.statusCode=="number"&&e.statusCode>=400&&e.statusCode<=599?e.statusCode:500,s=(e?.isOperational===true||r>=400&&r<500)&&typeof e?.message=="string"&&e.message.length>0?e.message:"Internal server error";return {status:r,message:s}}a(mt,"clientSafeError");var R=class{static{a(this,"ControllerRouter");}routes=[];globalPrefix;constructor(e=""){this.globalPrefix=e;}register(...e){for(let r of e){let o=k$1(r)??"",s=m$1(r);for(let i of s){let a=yt(`${this.globalPrefix}/${o}/${i.path}`);Kt(a,r.name,i.methodName),this.checkDuplicate(a,i.method,r.name,i.methodName);let{pattern:c,paramNames:d}=gt(a),u=n(r,i.methodName),f=K(r,i.methodName),l=V(r,i.methodName);this.routes.push({method:i.method,pattern:c,paramNames:d,controllerClass:r,methodName:i.methodName,guardClasses:u,interceptorRefs:f,middlewareRefs:l,pipeRefs:be(r),filterRefs:ue(r),rawPath:a});}}this.routes.sort((r,o)=>wt(r.rawPath)-wt(o.rawPath));}checkDuplicate(e,r,o,s){let{pattern:i}=gt(e),a=this.routes.find(c=>c.method===r&&c.pattern.source===i.source);if(a){let c=a.rawPath===e?e:`${a.rawPath} / ${e}`;throw new Error(`Duplicate route: ${r} ${c}
|
|
2
2
|
Already registered by: ${a.controllerClass.name}.${a.methodName}
|
|
3
|
-
Conflicting with: ${o}.${s}`)}}match(e,r){let o=e.toUpperCase(),s=pt(r);for(let i of this.routes){if(i.method!==o)continue;let a=i.pattern.exec(s);if(!a)continue;let c={};for(let d=0;d<i.paramNames.length;d++)c[i.paramNames[d]]=a[d+1]??"";return {route:i,params:c}}return null}getRoutes(){return this.routes}};function pt(t){return "/"+t.replace(/\/+/g,"/").replace(/^\/|\/$/g,"")}a(pt,"normalizePath");function ht(t){let e=[],r=t.split("/").map(o=>o.startsWith(":")?(e.push(o.slice(1)),"([^/]+)"):zt(o)).join("/");return {pattern:new RegExp(`^${r}$`),paramNames:e}}a(ht,"compilePath");function zt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(zt,"escapeRegex");function mt(t){return t.split("/").filter(Boolean).reduce((e,r)=>e+(r.startsWith(":")?1:0),0)}a(mt,"routePriority");function Wt(t,e,r){let o=`Invalid path "${t}" on ${e}.${r}:`;if(!t.startsWith("/"))throw new Error(`${o} must start with /`);let s=t.split("/").filter((a,c)=>c>0),i=new Set;for(let a of s){if(a==="")throw new Error(`${o} 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(`${o} invalid param name ":${c}" \u2014 must be a valid identifier`);if(i.has(c))throw new Error(`${o} duplicate param name ":${c}"`);i.add(c);}}}a(Wt,"validatePath");var N="__trustProxy",Re="__remoteAddress";function yt(t){return D(t.getNativeRequest())}a(yt,"getRequestHeaders");function D(t){let e=t?.node?.req?.headers;if(e&&typeof e=="object")return e;let r=t?.headers;return r&&typeof r.entries=="function"?Object.fromEntries(r.entries()):r&&typeof r=="object"?r:{}}a(D,"headersOf");function Q(t){let e=Ht(t);if(t.getData(N)!==true)return e;let r=D(t.getNativeRequest()),o=r["cf-connecting-ip"];if(o)return String(o).trim();let s=r["x-forwarded-for"];if(s){let a=String(s).split(",")[0]?.trim();if(a)return a}let i=r["x-real-ip"];return i?String(i).trim():e}a(Q,"clientIp");function Ht(t){let e=t.getData(Re);if(e)return e;let r=t.getNativeRequest();return r?.node?.req?.socket?.remoteAddress??r?.socket?.remoteAddress??""}a(Ht,"directAddress");var b=Symbol.for("truxie:route:params");function Kt(t){return t==null?false:typeof t=="function"||typeof t=="object"&&typeof t.transform=="function"}a(Kt,"isParamPipeRef");function X(t,e){return Kt(t)?{key:void 0,pipes:[t,...e??[]]}:{key:t,pipes:e??[]}}a(X,"resolveArgs");function g(t,e,r=[]){return (o,s,i)=>{if(s===void 0)return;let a=o[s];if(typeof a!="function")return;let c=a[b]??[];a[b]=[...c,{index:i,type:t,key:e,pipes:r.length>0?r:void 0}];}}a(g,"buildBuiltinDecorator");function Yt(t){return typeof t=="function"?new t:t}a(Yt,"resolveParamPipe");function gt(t,...e){let{key:r,pipes:o}=X(t,e);return g("query",r,o)}a(gt,"Query");function wt(t,...e){let{key:r,pipes:o}=X(t,e);return g("param",r,o)}a(wt,"Param");function xt(t,...e){let{key:r,pipes:o}=X(t,e);return g("body",r,o)}a(xt,"Body");var Et=a(()=>g("rawBody"),"RawBody"),Rt=a(()=>g("formData"),"FormData"),bt=a(()=>g("ip"),"Ip"),Mt=a(()=>g("userAgent"),"UserAgent"),At=a(t=>g("cookie",t),"Cookie");function Pt(t,...e){let{key:r,pipes:o}=X(t,e);return g("headers",r,o)}a(Pt,"Headers");function be(t){return ()=>(e,r,o)=>{if(r===void 0)return;let s=e[r];if(typeof s!="function")return;let i=s[b]??[];s[b]=[...i,{index:o,type:"auth",extractor:t}];}}a(be,"defineAuth");var Ct=be();function vt(t,e){return ()=>(r,o,s)=>{if(o===void 0)return;let i=r[o];if(typeof i!="function")return;let a=i[b]??[];i[b]=[...a,{index:s,type:"custom",extractor:t,schema:e?.schema,source:e?.source}];}}a(vt,"createParamDecorator");function M(t,e){let r=t.prototype[e];if(typeof r!="function")return null;let o=r[b];return o&&o.length>0?o:null}a(M,"getRouteParams");async function Z(t,e){let r=Math.max(...t.map(s=>s.index)),o=new Array(r+1).fill(void 0);for(let{index:s,type:i,key:a,pipes:c,extractor:d}of t){let u;switch(i){case "query":{let f=e.getQuery();u=a!==void 0?f[a]:f;break}case "param":{let f=e.getParams();u=a!==void 0?f[a]:f;break}case "body":{let f=e.getBodyParseError();if(f)throw new y(`Malformed JSON body: ${f.message}`);let l=e.getBody()??{};u=a!==void 0?l[a]:l;break}case "rawBody":{u=e.getRawBody();break}case "formData":{u=e.getFormData();break}case "headers":{let f=D(e.getNativeRequest());u=a!==void 0?f[a.toLowerCase()]:f;break}case "cookie":{let l=D(e.getNativeRequest()).cookie??"";if(a&&l){let p=l.split(";").map(h=>h.trim()).find(h=>h.startsWith(a+"="));u=p?decodeURIComponent(p.slice(a.length+1)):void 0;}else u=void 0;break}case "ip":{u=Q(e);break}case "userAgent":{u=D(e.getNativeRequest())["user-agent"]??"";break}case "auth":{u=d?await d(e):e.getAuth();break}case "custom":{u=d?await d(e):void 0;break}}if(c&&c.length>0)for(let f of c)u=await Yt(f).transform(u);o[s]=u;}return o}a(Z,"resolveParamArgs");var ee=Symbol.for("truxie:api:doc");function Dt(t){return (e,r,o)=>o!==void 0?(typeof o.value=="function"&&Ae(o.value,t,"override"),o):(typeof e=="function"&&Ae(e,t,"override"),e)}a(Dt,"ApiDoc");function St(t,e){Ae(t,e,"fill");}a(St,"contributeApiDoc");function Ae(t,e,r){let o=t,s=Lt(o[ee])?o[ee]:{},i=Me(e),a=r==="override"?{...s,...i}:{...i,...s},c=r==="override"?{...s.extensions,...i.extensions}:{...i.extensions,...s.extensions};if(Object.keys(c).length>0&&(a.extensions=c),s.request||i.request){let d=Me(s.request??{}),u=Me(i.request??{});a.request=r==="override"?{...d,...u}:{...u,...d};}o[ee]=a;}a(Ae,"writeApiDoc");function Me(t){return Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0))}a(Me,"defined");function Lt(t){return typeof t=="object"&&t!==null}a(Lt,"isRecord");function T(t,e){let r=t.prototype?.[e];if(typeof r!="function")return null;let o=r[ee];return Vt(o)?o:null}a(T,"getApiDoc");function It(t){return t?.returns?(Array.isArray(t.returns)?t.returns:[t.returns]).map(r=>({...r,status:r.status??200})):[]}a(It,"apiResponses");function Vt(t){return typeof t=="object"&&t!==null&&typeof t.summary=="string"}a(Vt,"isApiDoc");function Tt(t,e={}){let r=M(t.controllerClass,t.methodName)??[],o=T(t.controllerClass,t.methodName)?.request,s=e.toJsonSchema,i={},a=Pe(r,"param",s)??te(o?.params,s)??Xt(t.paramNames);a&&(i.params=a);let c=e.querySchema??Pe(r,"query",s)??te(o?.query,s)??_t(r,"query");if(c&&(i.query=c),t.method!=="GET"){let d=e.bodySchema??Pe(r,"body",s)??te(o?.body,s)??_t(r,"body")??Qt(r);d&&Object.assign(i,{body:d},Jt(o));}return i}a(Tt,"describeRouteInput");function Jt(t){let e={},r=t?.contentType===void 0?[]:[t.contentType].flat();return r.length>0&&(e.bodyContentTypes=r),t?.bodyRequired!==void 0&&(e.bodyRequired=t.bodyRequired),e}a(Jt,"bodyMedia");function Pe(t,e,r){if(r)for(let o of t){if(o.schema===void 0||(o.source??o.type)!==e)continue;let s=r(o.schema,{io:"input"});if(s)return s}}a(Pe,"schemaFor");function te(t,e){if(t!==void 0)return Ce(t)?t:e?.(t,{io:"input"})??void 0}a(te,"documentedSchema");function _t(t,e){let r=kt(t,e);if(r.length===0)return;let o={};for(let s of r)o[s]={};return {type:"object",properties:o}}a(_t,"keyedSchema");function Qt(t){return t.some(r=>r.type==="body"||r.source==="body")?{type:"object",description:"Shape not declared by the handler."}:void 0}a(Qt,"looseBody");function Xt(t){if(t.length===0)return;let e={};for(let r of t)e[r]={type:"string"};return {type:"object",properties:e,required:[...t]}}a(Xt,"pathParamsSchema");function Ce(t){if(typeof t!="object"||t===null)return false;let e=t;return typeof e._def=="object"||typeof e._zod=="object"?false:"type"in e||"properties"in e||"$ref"in e||"anyOf"in e||"allOf"in e||"oneOf"in e}a(Ce,"isJsonSchemaObject");function Ot(t,e={}){let r=M(t.controllerClass,t.methodName)??[],o=T(t.controllerClass,t.methodName)?.request;return {query:Nt(r,"query",o?.query,e.toJsonSchema),body:Nt(r,"body",o?.body,e.toJsonSchema)}}a(Ot,"routeInputDrift");function Nt(t,e,r,o){let s={undocumented:[],unread:[]};if(r===void 0||Zt(t,e))return s;let i=er(te(r,o));if(!i)return s;let a=new Set(kt(t,e)),c=new Set(i);return {undocumented:[...a].filter(d=>!c.has(d)),unread:i.filter(d=>!a.has(d))}}a(Nt,"partDrift");function kt(t,e){let r=t.filter(o=>o.type===e&&typeof o.key=="string").map(o=>o.key);return [...new Set(r)]}a(kt,"readKeys");function Zt(t,e){return t.some(r=>r.type===e&&r.key===void 0||r.type==="custom"&&r.source===e?true:e==="body"&&(r.type==="rawBody"||r.type==="formData"))}a(Zt,"readsWholeObject");function er(t){let r=tr(t)?.properties;return typeof r!="object"||r===null?null:Object.keys(r)}a(er,"propertyNames");function tr(t){let e=t?.$ref;if(typeof e!="string")return t;let r=/^#\/(\$defs|definitions)\/([^/]+)$/.exec(e);return r?t?.[r[1]]?.[rr(r[2])]??t:t}a(tr,"resolveRootRef");function rr(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}a(rr,"decodePointer");var Ft="__redirect";function qt(t,e=302){return {__redirect:true,url:t,statusCode:e}}a(qt,"redirect");function re(t){return t!==null&&typeof t=="object"&&t.__redirect===true}a(re,"isRedirect");function oe(){return !!(process.env.VERCEL||process.env.AWS_LAMBDA_FUNCTION_NAME||process.env.LAMBDA_TASK_ROOT||process.env.FUNCTIONS_WORKER_RUNTIME||process.env.K_SERVICE||process.env.NETLIFY)}a(oe,"isServerless");var O=class{static{a(this,"TruxieApplication");}container;registry;initialized=false;rootModule;options;eventEmitter;prefix="";trustProxy;router;gateways=new Map;wsInitialized=false;constructor(e,r={}){this.rootModule=e,this.options=r,this.trustProxy=r.trustProxy??oe(),this.container=new b$2,this.registry=new p;}async init(){if(this.initialized)return;this.eventEmitter=new q,this.options.eventBus&&this.eventEmitter.setOptions(this.options.eventBus),this.container.register({provide:q,useValue:this.eventEmitter});let e=new p$1;this.container.register({provide:p$1,useValue:e}),this.registry.scan(this.rootModule),this.options.strictModuleBoundaries&&this.registry.validateVisibility([q,p$1]),this.registry.registerAll(this.container);let r=this.registry.getAllProviders();e._init(this.container,r),await this.registry.callLifecycleHooks(this.container,"onModuleInit"),await s(this.container,r),await this.registry.callLifecycleHooks(this.container,"onApplicationBootstrap"),this.router=new R(this.prefix),this.router.register(...this.registry.getAllControllers()),this.initialized=true;}setGlobalPrefix(e){return this.prefix=e,this.initialized&&(this.router=new R(this.prefix),this.router.register(...this.registry.getAllControllers())),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}matchRoute(e,r){return this.ensureInitialized(),this.router.match(e,r)??null}getRoutes(){return this.ensureInitialized(),this.router.getRoutes()}async handleRequest(e,r){this.ensureInitialized();let{container:o,dispose:s}=this.createRequestContext();try{let i=await o.resolve(e.controllerClass),a$1=i[e.methodName];if(typeof a$1!="function")throw new Error(`${e.controllerClass.name}.${e.methodName} is not a method on the resolved controller.`);let c=a$1.bind(i),d=M(e.controllerClass,e.methodName);r.setData("__controllerClass",e.controllerClass),r.setData("__methodName",e.methodName),r.setData(N,this.trustProxy),r.setHandler?.(a$1),r.setContainer?.(o);let f=await _(o,this.getGlobalOptions(),{middlewares:e.middlewareRefs,guards:e.guardClasses,interceptors:e.interceptorRefs,pipes:e.pipeRefs,filters:e.filterRefs,handler:a(async l=>d?c(...await Z(d,l)):c(l),"handler")})(r);if(re(f)){let l=f;return {value:f,isRedirect:!0,redirectUrl:l.url,redirectStatus:l.statusCode}}return {value:f,isRedirect:!1}}finally{await s();}}hasGateways(){return this.ensureInitialized(),this.registry.getAllGateways().length>0}async createWebSocketHooks(e){this.ensureInitialized(),await this.initGateways();let r=this;return {async open(o){let i="/"+(e.getUrl(o).split("?")[0]??"/").replace(/^\/+|\/+$/g,""),a=r.matchGatewayPath(i);if(!a)return;let c=r.gateways.get(a),d=e.adaptPeer(o);for(let f of c.guards){let l=false;try{l=await f.canActivate(d);}catch(p){console.error(`[WS] ${c.className} guard error:`,p);}if(!l){d.close(1008,"Unauthorized");return}}let u=o.context;u&&(u._gatewayPath=a);for(let f of c.serverProps)c.instance[f]={peers:e.getPeers(o)??new Set};if(c.hasConnection)try{await c.instance.handleConnection(d);}catch(f){console.error(`[WS] ${c.className}.handleConnection error:`,f);}},async message(o,s){let a=o.context?._gatewayPath;if(!a)return;let c=r.gateways.get(a);if(!c)return;let d=e.adaptPeer(o),u=e.adaptMessage(s),f;try{f=u.json();}catch{return}if(!f.event||typeof f.event!="string")return;let l=c.messageHandlers.get(f.event);if(l)try{let p=n$1(l.paramMeta,d,u,f.data),h=await l.method(...p);h!=null&&d.send(h);}catch(p){console.error(`[WS] ${c.className}.${f.event} error:`,p);}},async close(o,s){let a=o.context?._gatewayPath;if(!a)return;let c=r.gateways.get(a);if(!c?.hasDisconnect)return;let d=e.adaptPeer(o);try{await c.instance.handleDisconnect(d,s);}catch(u){console.error(`[WS] ${c.className}.handleDisconnect error:`,u);}},async error(o,s){let i=o?.id??"unknown";console.error(`[WS] Peer ${String(i)} error:`,s);}}}getControllers(){return this.ensureInitialized(),this.registry.getAllControllers()}getGateways(){return this.ensureInitialized(),this.registry.getAllGateways()}getProviders(){return this.ensureInitialized(),this.registry.getAllProviders()}getEventEmitter(){return this.ensureInitialized(),this.eventEmitter}getRouter(){return this.ensureInitialized(),this.router}createHandler(e){return this.ensureInitialized(),_(this.container,this.getGlobalOptions(),e)}async shutdown(){this.initialized&&(await this.registry.callLifecycleHooks(this.container,"onModuleDestroy"),await this.registry.callLifecycleHooks(this.container,"onApplicationShutdown"),this.eventEmitter.clear(),await this.container.dispose(),this.initialized=false);}createRequestContext(){if(!this.container.hasRequestScoped())return {container:this.container,dispose:a(async()=>{},"dispose")};let e=this.container.createChild();return {container:e,dispose:a(()=>e.dispose(),"dispose")}}matchGatewayPath(e){if(this.gateways.has(e))return e;if(this.prefix){let r="/"+this.prefix.replace(/^\/+|\/+$/g,"");if(r!=="/"&&e.startsWith(r+"/")){let o=e.slice(r.length);if(this.gateways.has(o))return o}}}async initGateways(){if(!this.wsInitialized){for(let e of this.registry.getAllGateways()){let r=i(e);if(!r)continue;let o=await this.container.resolve(e),s=new Map;for(let a of j$1(e)){let c=o[a.methodName];typeof c=="function"&&s.set(a.event,{method:c.bind(o),paramMeta:k(e.prototype[a.methodName])});}let i$1=await E(this.container,l$1(e));if(this.gateways.set(r.path,{instance:o,className:e.name,messageHandlers:s,hasConnection:typeof o.handleConnection=="function",hasDisconnect:typeof o.handleDisconnect=="function",serverProps:m$1(e),guards:i$1}),typeof o.afterInit=="function")try{await o.afterInit();}catch{}}this.wsInitialized=true;}}getGlobalOptions(){return {middlewares:this.options.globalMiddlewares,guards:this.options.globalGuards,interceptors:this.options.globalInterceptors,pipes:this.options.globalPipes,filters:this.options.globalFilters}}ensureInitialized(){if(!this.initialized)throw new Error("TruxieApplication not initialized. Call TruxieFactory.create() or app.init().")}},ne=class{static{a(this,"TruxieFactory");}static async create(e,r){let o=new O(e,r);return await o.init(),o}};export{Dt as ApiDoc,m as AppError,Ct as Auth,U as BaseExecutionContext,xt as Body,at as Catch,j as ConfigurableModuleBuilder,W as ConflictError,R as ControllerRouter,At as Cookie,ft as DefaultValuePipe,J as DomainEvent,C as ForbiddenError,Rt as FormData,Pt as Headers,bt as Ip,G as NotFoundError,wt as Param,L as ParseIdPipe,V as ParseIntPipe,gt as Query,Ft as REDIRECT_BRAND,Re as REMOTE_ADDRESS_KEY,Et as RawBody,v as RequestAbortedError,N as TRUST_PROXY_KEY,O as TruxieApplication,ne as TruxieFactory,he as UOW_INSTANCE_KEY,pe as UOW_SESSION_KEY,z as UnauthorizedError,K as UnitOfWorkInterceptor,it as UseFilters,ct as UseInterceptors,ut as UseMiddleware,dt as UsePipes,Mt as UserAgent,y as ValidationError,It as apiResponses,nt as applyJsonBody,Q as clientIp,lt as clientSafeError,St as contributeApiDoc,se as createAsyncOptionsProviders,vt as createParamDecorator,_ as createPipeline,be as defineAuth,Tt as describeRouteInput,T as getApiDoc,H as getEffectiveInterceptors,Y as getEffectiveMiddlewares,fe as getInterceptorsMetadata,le as getMethodInterceptors,we as getMethodMiddlewares,ge as getMiddlewaresMetadata,yt as getRequestHeaders,M as getRouteParams,Ce as isJsonSchemaObject,re as isRedirect,oe as isServerless,qt as redirect,Z as resolveParamArgs,Ot as routeInputDrift};
|
|
3
|
+
Conflicting with: ${o}.${s}`)}}match(e,r){let o=e.toUpperCase(),s=yt(r);for(let i of this.routes){if(i.method!==o)continue;let a=i.pattern.exec(s);if(!a)continue;let c={};for(let d=0;d<i.paramNames.length;d++)c[i.paramNames[d]]=a[d+1]??"";return {route:i,params:c}}return null}getRoutes(){return this.routes}};function yt(t){return "/"+t.replace(/\/+/g,"/").replace(/^\/|\/$/g,"")}a(yt,"normalizePath");function gt(t){let e=[],r=t.split("/").map(o=>o.startsWith(":")?(e.push(o.slice(1)),"([^/]+)"):Lt(o)).join("/");return {pattern:new RegExp(`^${r}$`),paramNames:e}}a(gt,"compilePath");function Lt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(Lt,"escapeRegex");function wt(t){return t.split("/").filter(Boolean).reduce((e,r)=>e+(r.startsWith(":")?1:0),0)}a(wt,"routePriority");function Kt(t,e,r){let o=`Invalid path "${t}" on ${e}.${r}:`;if(!t.startsWith("/"))throw new Error(`${o} must start with /`);let s=t.split("/").filter((a,c)=>c>0),i=new Set;for(let a of s){if(a==="")throw new Error(`${o} 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(`${o} invalid param name ":${c}" \u2014 must be a valid identifier`);if(i.has(c))throw new Error(`${o} duplicate param name ":${c}"`);i.add(c);}}}a(Kt,"validatePath");var O="__trustProxy",Me="__remoteAddress";function xt(t){return D(t.getNativeRequest())}a(xt,"getRequestHeaders");function D(t){let e=t?.node?.req?.headers;if(e&&typeof e=="object")return e;let r=t?.headers;return r&&typeof r.entries=="function"?Object.fromEntries(r.entries()):r&&typeof r=="object"?r:{}}a(D,"headersOf");function Z(t){let e=Yt(t);if(t.getData(O)!==true)return e;let r=D(t.getNativeRequest()),o=r["cf-connecting-ip"];if(o)return String(o).trim();let s=r["x-forwarded-for"];if(s){let a=String(s).split(",")[0]?.trim();if(a)return a}let i=r["x-real-ip"];return i?String(i).trim():e}a(Z,"clientIp");function Yt(t){let e=t.getData(Me);if(e)return e;let r=t.getNativeRequest();return r?.node?.req?.socket?.remoteAddress??r?.socket?.remoteAddress??""}a(Yt,"directAddress");var b=Symbol.for("truxie:route:params");function Vt(t){return t==null?false:typeof t=="function"||typeof t=="object"&&typeof t.transform=="function"}a(Vt,"isParamPipeRef");function ee(t,e){return Vt(t)?{key:void 0,pipes:[t,...e??[]]}:{key:t,pipes:e??[]}}a(ee,"resolveArgs");function g(t,e,r=[]){return (o,s,i)=>{if(s===void 0)return;let a=o[s];if(typeof a!="function")return;let c=a[b]??[];a[b]=[...c,{index:i,type:t,key:e,pipes:r.length>0?r:void 0}];}}a(g,"buildBuiltinDecorator");function Jt(t){return typeof t=="function"?new t:t}a(Jt,"resolveParamPipe");function Et(t,...e){let{key:r,pipes:o}=ee(t,e);return g("query",r,o)}a(Et,"Query");function Rt(t,...e){let{key:r,pipes:o}=ee(t,e);return g("param",r,o)}a(Rt,"Param");function bt(t,...e){let{key:r,pipes:o}=ee(t,e);return g("body",r,o)}a(bt,"Body");var Mt=a(()=>g("rawBody"),"RawBody"),vt=a(()=>g("formData"),"FormData"),At=a(()=>g("ip"),"Ip"),Pt=a(()=>g("userAgent"),"UserAgent"),Ct=a(t=>g("cookie",t),"Cookie");function Dt(t,...e){let{key:r,pipes:o}=ee(t,e);return g("headers",r,o)}a(Dt,"Headers");function ve(t){return ()=>(e,r,o)=>{if(r===void 0)return;let s=e[r];if(typeof s!="function")return;let i=s[b]??[];s[b]=[...i,{index:o,type:"auth",extractor:t}];}}a(ve,"defineAuth");var St=ve();function It(t,e){return ()=>(r,o,s)=>{if(o===void 0)return;let i=r[o];if(typeof i!="function")return;let a=i[b]??[];i[b]=[...a,{index:s,type:"custom",extractor:t,schema:e?.schema,source:e?.source}];}}a(It,"createParamDecorator");function M(t,e){let r=t.prototype[e];if(typeof r!="function")return null;let o=r[b];return o&&o.length>0?o:null}a(M,"getRouteParams");async function te(t,e){let r=Math.max(...t.map(s=>s.index)),o=new Array(r+1).fill(void 0);for(let{index:s,type:i,key:a,pipes:c,extractor:d}of t){let u;switch(i){case "query":{let f=e.getQuery();u=a!==void 0?f[a]:f;break}case "param":{let f=e.getParams();u=a!==void 0?f[a]:f;break}case "body":{let f=e.getBodyParseError();if(f)throw new y(`Malformed JSON body: ${f.message}`);let l=e.getBody()??{};u=a!==void 0?l[a]:l;break}case "rawBody":{u=e.getRawBody();break}case "formData":{u=e.getFormData();break}case "headers":{let f=D(e.getNativeRequest());u=a!==void 0?f[a.toLowerCase()]:f;break}case "cookie":{let l=D(e.getNativeRequest()).cookie??"";if(a&&l){let p=l.split(";").map(h=>h.trim()).find(h=>h.startsWith(a+"="));u=p?decodeURIComponent(p.slice(a.length+1)):void 0;}else u=void 0;break}case "ip":{u=Z(e);break}case "userAgent":{u=D(e.getNativeRequest())["user-agent"]??"";break}case "auth":{u=d?await d(e):e.getAuth();break}case "custom":{u=d?await d(e):void 0;break}}if(c&&c.length>0)for(let f of c)u=await Jt(f).transform(u);o[s]=u;}return o}a(te,"resolveParamArgs");var re=Symbol.for("truxie:api:doc");function _t(t){return (e,r,o)=>o!==void 0?(typeof o.value=="function"&&Pe(o.value,t,"override"),o):(typeof e=="function"&&Pe(e,t,"override"),e)}a(_t,"ApiDoc");function Nt(t,e){Pe(t,e,"fill");}a(Nt,"contributeApiDoc");function Pe(t,e,r){let o=t,s=Qt(o[re])?o[re]:{},i=Ae(e),a=r==="override"?{...s,...i}:{...i,...s},c=r==="override"?{...s.extensions,...i.extensions}:{...i.extensions,...s.extensions};if(Object.keys(c).length>0&&(a.extensions=c),s.request||i.request){let d=Ae(s.request??{}),u=Ae(i.request??{});a.request=r==="override"?{...d,...u}:{...u,...d};}o[re]=a;}a(Pe,"writeApiDoc");function Ae(t){return Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0))}a(Ae,"defined");function Qt(t){return typeof t=="object"&&t!==null}a(Qt,"isRecord");function k(t,e){let r=t.prototype?.[e];if(typeof r!="function")return null;let o=r[re];return Xt(o)?o:null}a(k,"getApiDoc");function Tt(t){return t?.returns?(Array.isArray(t.returns)?t.returns:[t.returns]).map(r=>({...r,status:r.status??200})):[]}a(Tt,"apiResponses");function Xt(t){return typeof t=="object"&&t!==null&&typeof t.summary=="string"}a(Xt,"isApiDoc");function Ft(t,e={}){let r=M(t.controllerClass,t.methodName)??[],o=k(t.controllerClass,t.methodName)?.request,s=e.toJsonSchema,i={},a=Ce(r,"param",s)??oe(o?.params,s)??tr(t.paramNames);a&&(i.params=a);let c=e.querySchema??Ce(r,"query",s)??oe(o?.query,s)??Ot(r,"query");if(c&&(i.query=c),t.method!=="GET"){let d=e.bodySchema??Ce(r,"body",s)??oe(o?.body,s)??Ot(r,"body")??er(r);d&&Object.assign(i,{body:d},Zt(o));}return i}a(Ft,"describeRouteInput");function Zt(t){let e={},r=t?.contentType===void 0?[]:[t.contentType].flat();return r.length>0&&(e.bodyContentTypes=r),t?.bodyRequired!==void 0&&(e.bodyRequired=t.bodyRequired),e}a(Zt,"bodyMedia");function Ce(t,e,r){if(r)for(let o of t){if(o.schema===void 0||(o.source??o.type)!==e)continue;let s=r(o.schema,{io:"input"});if(s)return s}}a(Ce,"schemaFor");function oe(t,e){if(t!==void 0)return De(t)?t:e?.(t,{io:"input"})??void 0}a(oe,"documentedSchema");function Ot(t,e){let r=$t(t,e);if(r.length===0)return;let o={};for(let s of r)o[s]={};return {type:"object",properties:o}}a(Ot,"keyedSchema");function er(t){return t.some(r=>r.type==="body"||r.source==="body")?{type:"object",description:"Shape not declared by the handler."}:void 0}a(er,"looseBody");function tr(t){if(t.length===0)return;let e={};for(let r of t)e[r]={type:"string"};return {type:"object",properties:e,required:[...t]}}a(tr,"pathParamsSchema");function De(t){if(typeof t!="object"||t===null)return false;let e=t;return typeof e._def=="object"||typeof e._zod=="object"?false:"type"in e||"properties"in e||"$ref"in e||"anyOf"in e||"allOf"in e||"oneOf"in e}a(De,"isJsonSchemaObject");function qt(t,e={}){let r=M(t.controllerClass,t.methodName)??[],o=k(t.controllerClass,t.methodName)?.request;return {query:kt(r,"query",o?.query,e.toJsonSchema),body:kt(r,"body",o?.body,e.toJsonSchema)}}a(qt,"routeInputDrift");function kt(t,e,r,o){let s={undocumented:[],unread:[]};if(r===void 0||rr(t,e))return s;let i=or(oe(r,o));if(!i)return s;let a=new Set($t(t,e)),c=new Set(i);return {undocumented:[...a].filter(d=>!c.has(d)),unread:i.filter(d=>!a.has(d))}}a(kt,"partDrift");function $t(t,e){let r=t.filter(o=>o.type===e&&typeof o.key=="string").map(o=>o.key);return [...new Set(r)]}a($t,"readKeys");function rr(t,e){return t.some(r=>r.type===e&&r.key===void 0||r.type==="custom"&&r.source===e?true:e==="body"&&(r.type==="rawBody"||r.type==="formData"))}a(rr,"readsWholeObject");function or(t){let r=nr(t)?.properties;return typeof r!="object"||r===null?null:Object.keys(r)}a(or,"propertyNames");function nr(t){let e=t?.$ref;if(typeof e!="string")return t;let r=/^#\/(\$defs|definitions)\/([^/]+)$/.exec(e);return r?t?.[r[1]]?.[sr(r[2])]??t:t}a(nr,"resolveRootRef");function sr(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}a(sr,"decodePointer");var Bt="__redirect";function jt(t,e=302){return {__redirect:true,url:t,statusCode:e}}a(jt,"redirect");function ne(t){return t!==null&&typeof t=="object"&&t.__redirect===true}a(ne,"isRedirect");function se(){return !!(process.env.VERCEL||process.env.AWS_LAMBDA_FUNCTION_NAME||process.env.LAMBDA_TASK_ROOT||process.env.FUNCTIONS_WORKER_RUNTIME||process.env.K_SERVICE||process.env.NETLIFY)}a(se,"isServerless");var F=class{static{a(this,"TruxieApplication");}container;registry;initialized=false;rootModule;options;eventEmitter;prefix="";trustProxy;router;gateways=new Map;wsInitialized=false;constructor(e,r$1={}){this.rootModule=e,this.options=r$1,this.trustProxy=r$1.trustProxy??se(),this.container=new a$1,this.registry=new r;}async init(){if(this.initialized)return;this.eventEmitter=new s,this.options.eventBus&&this.eventEmitter.setOptions(this.options.eventBus),this.container.register({provide:s,useValue:this.eventEmitter});let e=new p;this.container.register({provide:p,useValue:e}),this.registry.scan(this.rootModule),this.options.strictModuleBoundaries&&this.registry.validateVisibility([s,p]),this.registry.registerAll(this.container);let r=this.registry.getAllProviders();e._init(this.container,r);try{await this.registry.callLifecycleHooks(this.container,"onModuleInit"),await u(this.container,r),await this.registry.callLifecycleHooks(this.container,"onApplicationBootstrap");}catch(o){throw await this.abortInit(o),o}this.router=new R(this.prefix),this.router.register(...this.registry.getAllControllers()),this.initialized=true;}setGlobalPrefix(e){return this.prefix=e,this.initialized&&(this.router=new R(this.prefix),this.router.register(...this.registry.getAllControllers())),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}matchRoute(e,r){return this.ensureInitialized(),this.router.match(e,r)??null}getRoutes(){return this.ensureInitialized(),this.router.getRoutes()}async handleRequest(e,r){this.ensureInitialized();let{container:o,dispose:s}=this.createRequestContext();try{let i=await o.resolve(e.controllerClass),a$1=i[e.methodName];if(typeof a$1!="function")throw new Error(`${e.controllerClass.name}.${e.methodName} is not a method on the resolved controller.`);let c=a$1.bind(i),d=M(e.controllerClass,e.methodName);r.setData("__controllerClass",e.controllerClass),r.setData("__methodName",e.methodName),r.setData(O,this.trustProxy),r.setHandler?.(a$1),r.setContainer?.(o);let f=await T(o,this.getGlobalOptions(),{middlewares:e.middlewareRefs,guards:e.guardClasses,interceptors:e.interceptorRefs,pipes:e.pipeRefs,filters:e.filterRefs,handler:a(async l=>d?c(...await te(d,l)):c(l),"handler")})(r);if(ne(f)){let l=f;return {value:f,isRedirect:!0,redirectUrl:l.url,redirectStatus:l.statusCode}}return {value:f,isRedirect:!1}}finally{await s();}}hasGateways(){return this.ensureInitialized(),this.registry.getAllGateways().length>0}async createWebSocketHooks(e){this.ensureInitialized(),await this.initGateways();let r=this;return {async open(o){let i="/"+(e.getUrl(o).split("?")[0]??"/").replace(/^\/+|\/+$/g,""),a=r.matchGatewayPath(i);if(!a)return;let c=r.gateways.get(a),d=e.adaptPeer(o);for(let f of c.guards){let l=false;try{l=await f.canActivate(d);}catch(p){console.error(`[WS] ${c.className} guard error:`,p);}if(!l){d.close(1008,"Unauthorized");return}}let u=o.context;u&&(u._gatewayPath=a);for(let f of c.serverProps)c.instance[f]={peers:e.getPeers(o)??new Set};if(c.hasConnection)try{await c.instance.handleConnection(d);}catch(f){console.error(`[WS] ${c.className}.handleConnection error:`,f);}},async message(o,s){let a=o.context?._gatewayPath;if(!a)return;let c=r.gateways.get(a);if(!c)return;let d=e.adaptPeer(o),u=e.adaptMessage(s),f;try{f=u.json();}catch{return}if(!f.event||typeof f.event!="string")return;let l=c.messageHandlers.get(f.event);if(l)try{let p=n$1(l.paramMeta,d,u,f.data),h=await l.method(...p);h!=null&&d.send(h);}catch(p){console.error(`[WS] ${c.className}.${f.event} error:`,p);}},async close(o,s){let a=o.context?._gatewayPath;if(!a)return;let c=r.gateways.get(a);if(!c?.hasDisconnect)return;let d=e.adaptPeer(o);try{await c.instance.handleDisconnect(d,s);}catch(u){console.error(`[WS] ${c.className}.handleDisconnect error:`,u);}},async error(o,s){let i=o?.id??"unknown";console.error(`[WS] Peer ${String(i)} error:`,s);}}}getControllers(){return this.ensureInitialized(),this.registry.getAllControllers()}getGateways(){return this.ensureInitialized(),this.registry.getAllGateways()}getProviders(){return this.ensureInitialized(),this.registry.getAllProviders()}getEventEmitter(){return this.ensureInitialized(),this.eventEmitter}getRouter(){return this.ensureInitialized(),this.router}createHandler(e){return this.ensureInitialized(),T(this.container,this.getGlobalOptions(),e)}async shutdown(){if(!this.initialized)return;let e=await this.teardown();if(this.initialized=false,e.length>0)throw new o(e)}async teardown(e){let r=this.registry.getAllProviders(),o=[...await p$1(this.container,r,"onModuleDestroy",{skip:e}),...await p$1(this.container,r,"onApplicationShutdown",{skip:e})];this.eventEmitter.clear();try{await this.container.dispose();}catch(s){o.push({hook:"dispose",token:a$1,provider:"Container",duringResolve:false,error:s});}return o}async abortInit(e){let r=new Set(e instanceof o?e.failures.filter(s=>s.duringResolve).map(s=>s.token):[]),o$1=await this.teardown(r);for(let s of o$1)console.error(`[truxie] cleanup after a failed boot: ${q(s)}`,s.error);}createRequestContext(){if(!this.container.hasRequestScoped())return {container:this.container,dispose:a(async()=>{},"dispose")};let e=this.container.createChild();return {container:e,dispose:a(()=>e.dispose(),"dispose")}}matchGatewayPath(e){if(this.gateways.has(e))return e;if(this.prefix){let r="/"+this.prefix.replace(/^\/+|\/+$/g,"");if(r!=="/"&&e.startsWith(r+"/")){let o=e.slice(r.length);if(this.gateways.has(o))return o}}}async initGateways(){if(!this.wsInitialized){for(let e of this.registry.getAllGateways()){let r=i(e);if(!r)continue;let o=await this.container.resolve(e),s=new Map;for(let a of j(e)){let c=o[a.methodName];typeof c=="function"&&s.set(a.event,{method:c.bind(o),paramMeta:k$2(e.prototype[a.methodName])});}let i$1=await E(this.container,l(e));if(this.gateways.set(r.path,{instance:o,className:e.name,messageHandlers:s,hasConnection:typeof o.handleConnection=="function",hasDisconnect:typeof o.handleDisconnect=="function",serverProps:m$2(e),guards:i$1}),typeof o.afterInit=="function")try{await o.afterInit();}catch{}}this.wsInitialized=true;}}getGlobalOptions(){return {middlewares:this.options.globalMiddlewares,guards:this.options.globalGuards,interceptors:this.options.globalInterceptors,pipes:this.options.globalPipes,filters:this.options.globalFilters}}ensureInitialized(){if(!this.initialized)throw new Error("TruxieApplication not initialized. Call TruxieFactory.create() or app.init().")}},ie=class{static{a(this,"TruxieFactory");}static async create(e,r){let o=new F(e,r);return await o.init(),o}};export{_t as ApiDoc,m as AppError,St as Auth,z as BaseExecutionContext,bt as Body,dt as Catch,G as ConfigurableModuleBuilder,L as ConflictError,R as ControllerRouter,Ct as Cookie,ht as DefaultValuePipe,X as DomainEvent,P as ForbiddenError,vt as FormData,Dt as Headers,At as Ip,W as NotFoundError,Rt as Param,J as ParseIdPipe,Q as ParseIntPipe,Et as Query,Bt as REDIRECT_BRAND,Me as REMOTE_ADDRESS_KEY,Mt as RawBody,C as RequestAbortedError,O as TRUST_PROXY_KEY,F as TruxieApplication,ie as TruxieFactory,ye as UOW_INSTANCE_KEY,me as UOW_SESSION_KEY,H as UnauthorizedError,Y as UnitOfWorkInterceptor,ut as UseFilters,ft as UseInterceptors,lt as UseMiddleware,pt as UsePipes,Pt as UserAgent,y as ValidationError,Tt as apiResponses,at as applyJsonBody,Z as clientIp,mt as clientSafeError,Nt as contributeApiDoc,ae as createAsyncOptionsProviders,It as createParamDecorator,T as createPipeline,ve as defineAuth,Ft as describeRouteInput,k as getApiDoc,K as getEffectiveInterceptors,V as getEffectiveMiddlewares,pe as getInterceptorsMetadata,he as getMethodInterceptors,Ee as getMethodMiddlewares,xe as getMiddlewaresMetadata,xt as getRequestHeaders,M as getRouteParams,De as isJsonSchemaObject,ne as isRedirect,se as isServerless,jt as redirect,te as resolveParamArgs,qt as routeInputDrift};
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as Container, a as EventEmitter2 } from './event-bus-
|
|
1
|
+
import { C as Container, a as EventEmitter2 } from './event-bus-CqsK7FDO.js';
|
|
2
2
|
import { M as ModuleMetadata, a as Type, D as DynamicModule, T as Token } from './types-BonRQLDb.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -33,7 +33,10 @@ interface TestingModule {
|
|
|
33
33
|
getContainer(): Container;
|
|
34
34
|
/** Get the test EventEmitter2 */
|
|
35
35
|
getEventEmitter(): EventEmitter2;
|
|
36
|
-
/**
|
|
36
|
+
/**
|
|
37
|
+
* Shut down the module: onModuleDestroy, then onApplicationShutdown, each
|
|
38
|
+
* dependents-first. Best-effort; failures are raised together at the end.
|
|
39
|
+
*/
|
|
37
40
|
shutdown(): Promise<void>;
|
|
38
41
|
}
|
|
39
42
|
declare class TestBuilder {
|
package/dist/testing.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {a as a$1,s,r,p as p$1,u,o,q}from'./chunk-TB76O5JV.js';import'./chunk-RDP32XIU.js';import {p,d}from'./chunk-TSJZVSHP.js';import {a}from'./chunk-EI7MMDWY.js';var T=class{static{a(this,"TestBuilder");}metadata;overrides=new Map;constructor(e){this.metadata=e;}overrideProvider(e){return {useValue:a(s=>(this.overrides.set(e,{provide:e,useValue:s}),this),"useValue"),useClass:a(s=>(this.overrides.set(e,{provide:e,useClass:s}),this),"useClass"),useFactory:a((s,c)=>(this.overrides.set(e,{provide:e,useFactory:s,inject:c??[]}),this),"useFactory")}}async compile(){let e=new a$1,s$1=new s;e.register({provide:s,useValue:s$1});let c=new p;e.register({provide:p,useValue:c});let i=this.metadata,a$2=[];if(A(i)){let r$1=(i.providers??[]).map(t=>t&&typeof t=="object"&&"forwardRef"in t?d(t):t);if(e.register(...r$1),a$2=r$1,i.imports&&i.imports.length>0){let t=new r,E={module:class{static{a(this,"TempTestModule");}},imports:i.imports,providers:r$1,exports:i.exports??[]};t.scan(E),t.registerAll(e),a$2=t.getAllProviders();}}else {let r$1=new r;r$1.scan(i),r$1.registerAll(e),a$2=r$1.getAllProviders();}for(let[,r]of this.overrides)e.register(r);c._init(e,a$2);let h=a(async r=>{let t=[...await p$1(e,a$2,"onModuleDestroy",{skip:r}),...await p$1(e,a$2,"onApplicationShutdown",{skip:r})];s$1.clear();try{await e.dispose();}catch(n){t.push({hook:"dispose",token:a$1,provider:"Container",duringResolve:false,error:n});}return t},"teardown");try{await this.callHook(e,a$2,"onModuleInit"),await u(e,a$2),await this.callHook(e,a$2,"onApplicationBootstrap");}catch(r){let t=r instanceof o?new Set(r.failures.filter(n=>n.duringResolve).map(n=>n.token)):void 0;for(let n of await h(t))console.error(`[truxie] cleanup after a failed compile: ${q(n)}`,n.error);throw r}return {resolve:a(r=>e.resolve(r),"resolve"),has:a(r=>e.has(r),"has"),getContainer:a(()=>e,"getContainer"),getEventEmitter:a(()=>s$1,"getEventEmitter"),shutdown:a(async()=>{let r=await h();if(r.length>0)throw new o(r)},"shutdown")}}async callHook(e,s,c){let i=await p$1(e,s,c);if(i.length>0)throw new o(i)}};function A(l){return !(typeof l=="function"||l&&typeof l=="object"&&"module"in l)}a(A,"isModuleMetadata");var w=class{static{a(this,"Test");}static createTestingModule(e){return new T(e)}};export{w as Test};
|
package/package.json
CHANGED
package/dist/chunk-CD6QSDG5.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {i as i$1}from'./chunk-RDP32XIU.js';import {d,h,a as a$1,i,j as j$1,k as k$1,b,n,o,e}from'./chunk-TSJZVSHP.js';import {a}from'./chunk-EI7MMDWY.js';import'reflect-metadata';var $=new WeakSet;function S(i){return $.has(i)?false:($.add(i),true)}a(S,"claimDestroy");var k=class extends Error{static{a(this,"MissingProviderError");}},F=class i$1{static{a(this,"Container");}registrations=new Map;parent=null;children=[];register(...e){for(let t of e)this.registerOne(t);}registerOne(e){let t=e&&typeof e=="object"&&"forwardRef"in e?d(e):e;if(typeof t=="function"){let a=h(t)?.scope??a$1.SINGLETON;this.registrations.set(t,{provider:t,scope:a,resolved:false});return}let n=t.provide,o=a$1.SINGLETON,s=t;if("useClass"in t){let r=t.useClass,a=r&&typeof r=="object"&&"forwardRef"in r?d(r):r,f=h(a);o=t.scope??f?.scope??a$1.SINGLETON,s={...t,useClass:a};}else if("useExisting"in t){let r=t.useExisting,a=r&&typeof r=="object"&&"forwardRef"in r?d(r):r;s={...t,useExisting:a};}else "useFactory"in t&&(o=t.scope??a$1.SINGLETON);this.registrations.set(n,{provider:s,scope:o,resolved:false});}async resolve(e){return this.resolveInternal(e,J)}async resolveInternal(e,t){let n=d(e),o=n!==e?n:e,s=this.findOwner(o);if(!s)throw new k(`No provider found for ${P(o)}`);let r=s.registrations.get(o),a=r.scope===a$1.SINGLETON?s:this,f=r.scope===a$1.SINGLETON||r.scope===a$1.REQUEST&&a.parent!==null;if(f&&r.resolved)return r.instance;if(t.has(o))throw new Error(`Circular dependency detected for ${P(o)}`);if(f&&r.inFlight)return r.inFlight;let m=new Set(t).add(o),l=a.createInstance(r,m).then(h=>(f&&(r.instance=h,r.resolved=true),r.inFlight=void 0,h),h=>{throw r.inFlight=void 0,h});return f&&(r.inFlight=l),l}has(e){return this.registrations.has(e)||(this.parent?.has(e)??false)}hasRequestScoped(){for(let[,e]of this.registrations)if(e.scope===a$1.REQUEST)return true;return this.parent?.hasRequestScoped()??false}findOwner(e){return this.registrations.has(e)?this:this.parent?.findOwner(e)??null}createChild(){let e=new i$1;e.parent=this;for(let[t,n]of this.registrations)n.scope===a$1.REQUEST&&e.registrations.set(t,{provider:n.provider,scope:a$1.REQUEST,instance:void 0,resolved:false});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.resolved)continue;let t=e.instance;if(!t||typeof t!="object")continue;let n=t;typeof n.onModuleDestroy=="function"&&S(t)&&await n.onModuleDestroy();}if(this.registrations.clear(),this.parent){let e=this.parent.children.indexOf(this);e!==-1&&this.parent.children.splice(e,1),this.parent=null;}}async createInstance(e,t){let{provider:n}=e;if(typeof n=="function")return this.instantiateClass(n,t);if("useValue"in n)return n.useValue;if("useClass"in n)return this.instantiateClass(n.useClass,t);if("useFactory"in n){let o=n,s=[];if(o.inject)for(let r of o.inject)s.push(await this.resolveInternal(r,t));return o.useFactory(...s)}if("useExisting"in n)return this.resolveInternal(n.useExisting,t);throw new Error("Unknown provider type")}async instantiateClass(e,t){let n=Reflect.getMetadata("design:paramtypes",e)??[],o=i(e),s=j$1(e),r=k$1(e),a=s.size>0?Math.max(...s.keys())+1:0,f=Math.max(n.length,a,o.length),m=[];for(let l=0;l<f;l++){let h=s.get(l)??o[l]??n[l];try{m.push(await this.resolveInternal(h,t));}catch(g){if(g instanceof k&&r.has(l)){m.push(void 0);continue}let M=g instanceof Error?g.message:String(g);throw new Error(`Cannot resolve parameter at index ${l} (${P(h)}) of ${e.name}: ${M}`,{cause:g})}}return new e(...m)}},J=new Set;function P(i){return typeof i=="string"?i:typeof i=="symbol"||i instanceof b?i.toString():typeof i=="function"?i.name:String(i)}a(P,"tokenToString");function _(i,e){let t=[];for(let s=e;typeof s=="function"&&s!==Function.prototype;s=Object.getPrototypeOf(s)){let r=Reflect.getOwnMetadata(i,s);r!==void 0&&r.length>0&&t.push(r);}let n=new Set,o=[];for(let s of t.reverse())for(let r of s)n.has(r)||(n.add(r),o.push(r));return o}a(_,"inheritedClassMetadata");var L=Symbol.for("truxie:controller:path"),v=Symbol.for("truxie:controller:guards"),j=Symbol.for("truxie:route:metadata"),U=Symbol.for("truxie:method:route"),E=Symbol.for("truxie:method:guards"),N=Symbol.for("truxie:method:noguard");function ye(i){return e=>{Reflect.defineMetadata(L,i,e);}}a(ye,"Controller");function x(i){return (e="")=>(t,n,o)=>{let s=o!==void 0,r=String(s?n:n?.name??n),a=s?o?.value:t;if(typeof a=="function"&&(a[U]={method:i,path:e,methodName:r}),s){let f=Reflect.getOwnMetadata(j,t.constructor)??[];return f.push({method:i,path:e,methodName:r}),Reflect.defineMetadata(j,f,t.constructor),o}return t}}a(x,"createMethodDecorator");var we=x("GET"),Ee=x("POST"),xe=x("PUT"),Me=x("DELETE"),be=x("PATCH");function Te(...i){return (e,t,n)=>{if(t==null){let o=Reflect.getOwnMetadata(v,e)??[];Reflect.defineMetadata(v,[...o,...i],e);return}if(n!==void 0){if(n?.value){let o=n.value[E]??[];n.value[E]=[...o,...i];}return n}if(typeof e=="function"){let o=e[E]??[];e[E]=[...o,...i];}if(typeof e=="function"&&t?.kind==="class"){let o=Reflect.getOwnMetadata(v,e)??[];Reflect.defineMetadata(v,[...o,...i],e);}return e}}a(Te,"RouteGuards");function Re(){return (i,e,t)=>t!==void 0?(t?.value&&(t.value[N]=true),t):(typeof i=="function"&&(i[N]=true),i)}a(Re,"NoGuard");function V(i){return Reflect.getOwnMetadata(L,i)}a(V,"getControllerPath");function Se(i){return Reflect.getOwnMetadata(v,i)??[]}a(Se,"getControllerGuards");function Q(i){let e=new Map,t=i.prototype;for(;t&&t!==Object.prototype;){for(let n of Object.getOwnPropertyNames(t)){if(n==="constructor"||e.has(n))continue;let o=Object.getOwnPropertyDescriptor(t,n);!o||typeof o.value!="function"||e.set(n,o.value);}t=Object.getPrototypeOf(t);}return e}a(Q,"methodsOf");function X(i,e){return Q(i).get(e)}a(X,"methodOf");function Oe(i){let e=[],t=new Set;for(let[n,o]of Q(i)){let s=o[U];!s||t.has(n)||(t.add(n),e.push(s));}if(e.length>0)return e;for(let n=i;n&&n!==Function.prototype;n=Object.getPrototypeOf(n)){let o=Reflect.getOwnMetadata(j,n)??[];for(let s of o)t.has(s.methodName)||(t.add(s.methodName),e.push(s));}return e}a(Oe,"getRouteMetadata");function Pe(i,e){let t=X(i,e),n=t!==void 0&&t[N]===true,o=t!==void 0&&t[E]||[];return n?o:[...Z(i),...o]}a(Pe,"getMethodGuards");function Z(i){return _(v,i)}a(Z,"controllerGuardsOf");var z=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 n of this.sortedModules)if(n.global)for(let o of n.providers)t.add(o);t.size>0&&e.register(...t);for(let n of this.sortedModules){e.register(...n.providers);for(let o of n.metadata.imports??[]){let s=this.getModuleType(o),r=this.resolved.get(s);if(r)for(let a of r.exports){let f=this.findProvider(r,a)??this.findReExportedProvider(r,a);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 n of this.sortedModules){for(let o of n.controllers)e.has(o)||(e.add(o),t.push(o));for(let o of n.metadata.providers??[])typeof o=="function"&&V(o)!==void 0&&!e.has(o)&&(e.add(o),t.push(o));}return t}getAllGateways(){let e=new Set,t=[];for(let n of this.sortedModules)for(let o of n.providers)typeof o=="function"&&i$1(o)!==void 0&&!e.has(o)&&(e.add(o),t.push(o));return t}async callLifecycleHooks(e,t,n){for(let o of this.sortedModules)for(let s of o.providers){let r=typeof s=="function"?s:s.provide;if(e.has(r))try{let a=await e.resolve(r);if(a&&typeof a=="object"&&typeof a[t]=="function"){if(t==="onModuleDestroy"&&!S(a))continue;await a[t](n);}}catch{}}}resolveModule(e){let t=d(e),n$1=typeof t=="object"&&"module"in t,o$1=n$1?t.module:t,s=this.resolved.get(o$1);if(s)return n$1&&this.mergeDynamicModule(s,e),s;let r=n(o$1)??{},a=n$1?e:{},f=[...r.controllers??[],...a.controllers??[]],m=[...r.providers??[],...a.providers??[]],l=[...r.exports??[],...a.exports??[]],h=m.map(u=>u&&typeof u=="object"&&"forwardRef"in u?d(u):u),g=l.map(u=>u&&typeof u=="object"&&"forwardRef"in u?d(u):u),M={imports:[...r.imports??[],...a.imports??[]],controllers:f,providers:h,exports:g},D={type:o$1,metadata:M,controllers:f,providers:[...f,...h],exports:new Set(g),global:n$1?e.global??o(o$1):o(o$1)};this.resolved.set(o$1,D);for(let u of M.imports??[])this.resolveModule(u);return D}mergeDynamicModule(e,t){if(t.controllers&&t.controllers.length>0&&(e.controllers.push(...t.controllers),e.providers.push(...t.controllers),e.metadata.controllers=[...e.metadata.controllers??[],...t.controllers]),t.providers&&t.providers.length>0){let n=t.providers.map(o=>o&&typeof o=="object"&&"forwardRef"in o?d(o):o);e.providers.push(...n),e.metadata.providers=[...e.metadata.providers??[],...n];}if(t.exports&&t.exports.length>0){let n=t.exports.map(o=>o&&typeof o=="object"&&"forwardRef"in o?d(o):o);for(let o of n)e.exports.add(o);e.metadata.exports=[...e.metadata.exports??[],...n];}if(t.imports&&t.imports.length>0){e.metadata.imports=[...e.metadata.imports??[],...t.imports];for(let n of t.imports)this.resolveModule(n);}t.global===true&&(e.global=true);}getVisibleTokens(e){let t=new Set;for(let n of e.providers)t.add(this.getProviderToken(n));for(let n of e.metadata.imports??[]){let o=this.getModuleType(n),s=this.resolved.get(o);if(s)for(let r of s.exports)t.add(r);}for(let n of this.sortedModules)if(n.global)for(let o of n.providers)t.add(this.getProviderToken(o));return t}validateExports(){for(let e of this.sortedModules){let t=new Set(e.providers.map(o=>this.getProviderToken(o))),n=this.collectImportedExports(e);for(let o of e.exports)if(!t.has(o)&&!n.has(o)){let s=typeof o=="function"?o.name:String(o);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(e=[]){let t=new Set(e),n=[];for(let o of this.sortedModules){let s=this.getVisibleTokens(o);for(let r of o.providers){let a=typeof r=="function"?r.name:q(r.provide);for(let f of K(r))!s.has(f)&&!t.has(f)&&n.push(`${o.type.name}: ${a} depends on ${q(f)}, but it is not provided in this module and not exported by any imported module`);}}if(n.length>0)throw new Error(n.join(`
|
|
2
|
-
`))}getProviderToken(e){return typeof e=="function"?e:e.provide}collectImportedExports(e){let t=new Set;for(let n of e.metadata.imports??[]){let o=this.getModuleType(n),s=this.resolved.get(o);if(s)for(let r of s.exports)t.add(r);}return t}findProvider(e,t){return e.providers.find(n=>typeof n=="function"?n===t:n.provide===t)}findReExportedProvider(e,t){for(let n of e.metadata.imports??[]){let o=this.getModuleType(n),s=this.resolved.get(o);if(!s||!s.exports.has(t))continue;let r=this.findProvider(s,t);if(r)return r;let a=this.findReExportedProvider(s,t);if(a)return a}}getModuleType(e){let t=d(e);return typeof t=="object"&&"module"in t?t.module:t}topologicalSort(){let e=new Set,t=new Set,n=[],o=a(s=>{if(e.has(s))return;if(t.has(s))throw new Error(`Circular module dependency detected: ${s.name}`);t.add(s);let r=this.resolved.get(s);if(r){for(let a of r.metadata.imports??[])o(this.getModuleType(a));t.delete(s),e.add(s),n.push(r);}},"visit");for(let[s]of this.resolved)o(s);return n}};function q(i){return typeof i=="function"?i.name:String(i)}a(q,"tokenName");function W(i$1){let e=i(i$1),t=j$1(i$1),n=k$1(i$1),o=Math.max(e.length,...[...t.keys()].map(r=>r+1),0),s=[];for(let r=0;r<o;r++){if(n.has(r))continue;let a=t.get(r)??e[r];a!==void 0&&s.push(a);}return s}a(W,"classDependencies");function K(i){return typeof i=="function"?W(i):"useClass"in i?W(d(i.useClass)):"useFactory"in i?(i.inject??[]).map(e=>d(e)):"useExisting"in i?[d(i.useExisting)]:[]}a(K,"providerDependencies");function ee(i,e,t,n){var o=arguments.length,s=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,r;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(i,e,t,n);else for(var a=i.length-1;a>=0;a--)(r=i[a])&&(s=(o<3?r(s):o>3?r(e,t,s):r(e,t))||s);return o>3&&s&&Object.defineProperty(e,t,s),s}a(ee,"_ts_decorate");function Y(i,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(i,e)}a(Y,"_ts_metadata");var y=class{static{a(this,"EventEmitter2");}handlers=new Map;pending=new Map;onError;constructor(){this.onError=te;}setOptions(e){e.onError&&(this.onError=e.onError);}subscribe(e,t,n){let o=this.handlers.get(e)??[];o.push({instance:n?.instance??{},methodName:n?.methodName??"anonymous",handler:t}),this.handlers.set(e,o);}registerHandler(e,t,n){let o=t[n].bind(t);this.subscribe(e,o,{instance:t,methodName:n});}async emit(e){let t=this.handlers.get(e.type);if(!t||t.length===0)return;let n=this.executeHandlers(t,e);this.pending.set(n,e.type);try{await n;}finally{this.pending.delete(n);}}emitAsync(e){let t=this.handlers.get(e.type);if(!t||t.length===0)return Promise.resolve([]);let n=this.executeHandlers(t,e).then(o=>(this.pending.delete(n),o),()=>(this.pending.delete(n),[]));return this.pending.set(n,e.type),n}async waitForAllDone(...e){for(;;){let t=this.getPending(e);if(t.length===0)break;await Promise.allSettled(t);}}getPending(e){if(e.length===0)return [...this.pending.keys()];let t=[];for(let[n,o]of this.pending)e.includes(o)&&t.push(n);return t}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();}async executeHandlers(e,t){return (await Promise.allSettled(e.map(async o=>{let s=Date.now();try{return {value:await o.handler(t),durationMs:Date.now()-s}}catch(r){return {err:r,durationMs:Date.now()-s,threw:true}}}))).map((o,s)=>{let r=e[s],a=`${r.instance.constructor?.name??"Unknown"}.${r.methodName}`;if(o.status==="fulfilled"&&!("threw"in o.value))return {name:a,status:"success",value:o.value.value,durationMs:o.value.durationMs};let f=o.status==="fulfilled"?o.value.err:o.reason,m=f instanceof Error?f.message:typeof f=="string"?f:String(f),l=o.status==="fulfilled"?o.value.durationMs:0;return this.onError(f,t.type,a),{name:a,status:"failed",error:m,durationMs:l}})}};y=ee([e(),Y("design:type",Function),Y("design:paramtypes",[])],y);function te(i,e,t){console.error(`[EventEmitter2] Handler "${t}" failed for event "${e}":`,i);}a(te,"defaultErrorHandler");var C=Symbol.for("truxie:on-event");function Ve(i){return (e,t,n)=>{let o=Reflect.getOwnMetadata(C,e.constructor)??[];o.push({eventType:i,methodName:String(t)}),Reflect.defineMetadata(C,o,e.constructor);}}a(Ve,"OnEvent");function B(i){return Reflect.getOwnMetadata(C,i)??[]}a(B,"getOnEventMetadata");async function Be(i,e){let t=await i.resolve(y);for(let n of e){let o=oe(n);if(!o)continue;let s=B(o);if(s.length===0)continue;let r=typeof n=="function"?n:n.provide,a;try{a=await i.resolve(r);}catch{continue}for(let f of s)typeof a[f.methodName]=="function"&&t.registerHandler(f.eventType,a,f.methodName);}}a(Be,"scanEventHandlers");function oe(i){return typeof i=="function"?h(i)?i:null:"useClass"in i?i.useClass:null}a(oe,"getProviderClass");export{S as a,F as b,_ as c,ye as d,we as e,Ee as f,xe as g,Me as h,be as i,Te as j,Re as k,V as l,Se as m,Oe as n,Pe as o,z as p,y as q,Ve as r,Be as s};
|