truxie 0.3.0 → 0.3.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 +1 -1
- package/dist/chunk-3FLBEU46.js +1 -0
- package/dist/{chunk-D6XYRP2M.js → chunk-AGUTRLO2.js} +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +2 -2
- package/dist/testing.js +1 -1
- package/dist/{types-BHt3a4dp.d.ts → types-CUcndOdw.d.ts} +12 -1
- package/dist/ws.d.ts +2 -2
- package/dist/ws.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-RDP32XIU.js +0 -1
package/README.md
CHANGED
|
@@ -104,7 +104,7 @@ Dynamic modules (`forRoot` / `forRootAsync` / `forFeature`) come from `Configura
|
|
|
104
104
|
|
|
105
105
|
- **Events** — `EventEmitter2` and `@OnEvent('user.created')`, fan-out, error-isolated.
|
|
106
106
|
- **CQRS** (`truxie/cqrs`) — `CommandBus`, `QueryBus`, `EventBus`, `AggregateRoot`, `@CommandHandler`, `@QueryHandler`, `@EventsHandler`.
|
|
107
|
-
- **WebSockets** (`truxie/ws`) — `@WebSocketGateway`, `@SubscribeMessage`, adapter-agnostic peers.
|
|
107
|
+
- **WebSockets** (`truxie/ws`) — `@WebSocketGateway`, `@SubscribeMessage`, adapter-agnostic peers and opt-in raw frame gateways (`{ raw: true }`, `OnGatewayRawMessage`).
|
|
108
108
|
- **Testing** (`truxie/testing`) — `Test.createTestingModule(...)` with `overrideProvider`, running the same lifecycle the application runs.
|
|
109
109
|
- **Introspection** — `app.getRoutes()`, `@ApiDoc`, `describeRouteInput`, consumed by `@truxie/openapi` and `@truxie/mcp`. A handler that validates by hand documents its input with `@ApiDoc({request: {query, body, params}})`; a schema a param decorator records still wins, and `routeInputDrift(route)` reports keys the handler reads that the documentation misses, and the reverse.
|
|
110
110
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a}from'./chunk-EI7MMDWY.js';import'reflect-metadata';var l=Symbol.for("truxie:ws:gateway"),f=Symbol.for("truxie:ws:message"),d=Symbol.for("truxie:ws:params"),x=Symbol.for("truxie:ws:guards"),g=Symbol.for("truxie:ws:server");function w(e){return n=>{let r=typeof e=="string"?{path:e}:e??{},a={path:r.path??"/",namespace:r.namespace??"/",raw:r.raw??false,target:n};Reflect.defineMetadata(l,a,n);}}a(w,"WebSocketGateway");function p(e){return (n,r,a)=>{let s=n.constructor,o=Reflect.getOwnMetadata(f,s)??[];Reflect.defineMetadata(f,[...o,{event:e,methodName:String(r)}],s);}}a(p,"SubscribeMessage");function M(){return (e,n)=>{let r=e.constructor,a=Reflect.getOwnMetadata(g,r)??[];Reflect.defineMetadata(g,[...a,String(n)],r);}}a(M,"WebSocketServer");function i(e,n){return (r,a,s)=>{if(a===void 0)return;let o=r[a];if(typeof o!="function")return;let c=o[d]??[];o[d]=[...c,{type:e,index:s,extractor:n}];}}a(i,"buildWsParamDecorator");var b=a(()=>i("message-body"),"MessageBody"),R=a(()=>i("connected-socket"),"ConnectedSocket"),W=a(()=>i("ws-auth"),"WsAuth");function y(e){return ()=>i("custom",e)}a(y,"createWsParamDecorator");function A(...e){return n=>{let r=Reflect.getOwnMetadata(x,n)??[];Reflect.defineMetadata(x,[...r,...e],n);}}a(A,"WsGuards");function h(e){return Reflect.getOwnMetadata(l,e)}a(h,"getGatewayMetadata");function k(e){return Reflect.getOwnMetadata(f,e)??[]}a(k,"getMessageHandlers");function _(e){return e[d]??[]}a(_,"getWsParams");function E(e){return Reflect.getOwnMetadata(x,e)??[]}a(E,"getWsGuards");function G(e){return Reflect.getOwnMetadata(g,e)??[]}a(G,"getWsServerProperties");function D(e,n,r,a){if(e.length===0)return [];let s=Math.max(...e.map(c=>c.index)),o=new Array(s+1).fill(void 0);for(let{type:c,index:u,extractor:S}of e)switch(c){case "message-body":o[u]=a;break;case "connected-socket":o[u]=n;break;case "ws-auth":o[u]=n.context.auth;break;case "custom":o[u]=S?S(n,r):void 0;break}return o}a(D,"resolveWsArgs");export{w as a,p as b,M as c,b as d,R as e,W as f,y as g,A as h,h as i,k as j,_ as k,E as l,G as m,D as n};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {i as i$1}from'./chunk-
|
|
1
|
+
import {i as i$1}from'./chunk-3FLBEU46.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),d$1=a.createInstance(i,l).then(u=>(ne(u),f&&(i.instance=u,i.resolved=true),i.inFlight=void 0,u),u=>{throw i.inFlight=void 0,u});return f&&(i.inFlight=d$1),d$1}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 d=0;d<f;d++){let u=s.get(d)??o[d]??r[d];try{l.push(await this.resolveInternal(u,t));}catch(g){if(g instanceof _&&i$1.has(d)){l.push(void 0);continue}let M=g instanceof Error?g.message:String(g);throw new Error(`Cannot resolve parameter at index ${d} (${D(u)}) 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"),x=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 E(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(E,"createMethodDecorator");var De=E("GET"),Ne=E("POST"),Ce=E("PUT"),$e=E("DELETE"),Ie=E("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[x]??[];r.value[x]=[...o,...n];}return r}if(typeof e=="function"){let o=e[x]??[];e[x]=[...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 ke(n){return Reflect.getOwnMetadata(v,n)??[]}a(ke,"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 He(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(He,"getRouteMetadata");function Fe(n,e){let t=se(n,e),r=t!==void 0&&t[I]===true,o=t!==void 0&&t[x]||[];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
2
|
${t.map(o=>` - ${o}`).join(`
|
|
3
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,d)=>{if(!(t==="onModuleDestroy"&&!O(d)))try{await d[t](r.signal);}catch(u){o.push({hook:t,token:l,provider:B(l),duringResolve:false,error:u});}},"call");for(let l of e){let d=typeof l=="function"?l:l.provide;if(r.skip?.has(d)||!n.has(d))continue;let u;try{u=await n.resolve(d);}catch(g){o.push({hook:t,token:d,provider:B(d),duringResolve:true,error:g});continue}!u||typeof u!="object"||typeof u[t]=="function"&&(i.has(u)||(i.add(u),s?a$1.push({token:d,instance:u}):await f(d,u)));}if(s){a$1.reverse(),a$1.sort((l,d)=>(C(d.instance)??-1)-(C(l.instance)??-1));for(let{token:l,instance:d}of a$1)await f(l,d);}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.expandModuleReExports(),this.validateExports();}expandModuleReExports(){for(let e of this.sortedModules){let t=new Set((e.metadata.imports??[]).map(o=>this.getModuleType(o))),r=new Set(e.providers.map(o=>this.getProviderToken(o)));for(let o of [...e.exports]){if(typeof o!="function"||r.has(o))continue;let s=this.resolved.get(o);if(s){if(!t.has(o))throw new Error(`${e.type.name} exports module ${o.name} but does not import it`);e.exports.delete(o);for(let i of s.exports)e.exports.add(i);}}}}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??[]],d$1=[...i.exports??[],...a.exports??[]],u=l.map(h=>h&&typeof h=="object"&&"forwardRef"in h?d(h):h),g=d$1.map(h=>h&&typeof h=="object"&&"forwardRef"in h?d(h):h),M={imports:[...i.imports??[],...a.imports??[]],controllers:f,providers:u,exports:g},G={type:o$1,metadata:M,controllers:f,providers:[...f,...u],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
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 de(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(de,"_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=ue;}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),d=o.status==="fulfilled"?o.value.durationMs:0;return this.onError(f,t.type,a),{name:a,status:"failed",error:l,durationMs:d}})}};y=de([e(),ee("design:type",Function),ee("design:paramtypes",[])],y);function ue(n,e,t){console.error(`[EventEmitter2] Handler "${t}" failed for event "${e}":`,n);}a(ue,"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 ut(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(ut,"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,ke as l,He as m,Fe as n,P as o,J as p,ce as q,X as r,y as s,st as t,ut as u};
|
package/dist/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { C as Container, E as EventBusOptions, a as EventEmitter2 } from './even
|
|
|
2
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
|
-
import { W as WsPeer, a as WsMessage } from './types-
|
|
5
|
+
import { W as WsPeer, a as WsMessage } from './types-CUcndOdw.js';
|
|
6
6
|
|
|
7
7
|
declare function Injectable(options?: InjectableOptions): ClassDecorator;
|
|
8
8
|
/**
|
|
@@ -1496,6 +1496,8 @@ declare class TruxieApplication {
|
|
|
1496
1496
|
*/
|
|
1497
1497
|
private abortInit;
|
|
1498
1498
|
private createRequestContext;
|
|
1499
|
+
/** Check a transport upgrade path after initializing its gateway registry. */
|
|
1500
|
+
hasWebSocketGateway(path: string): Promise<boolean>;
|
|
1499
1501
|
private matchGatewayPath;
|
|
1500
1502
|
private initGateways;
|
|
1501
1503
|
private getGlobalOptions;
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
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-D6XYRP2M.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-D6XYRP2M.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}
|
|
1
|
+
import {k as k$1,m,n,a as a$1,r,s,u,o,p as p$1,q,b as b$2}from'./chunk-AGUTRLO2.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-AGUTRLO2.js';import {i,j,k as k$2,l,m as m$1,n as n$1}from'./chunk-3FLBEU46.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 ue(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(ue,"createAsyncOptionsProviders");var W=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=ue(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 H=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 ct(t,e,r=""){if(e!=="")try{t.setBody(JSON.parse(e));}catch(o){jt(e,r)&&t.setBodyParseError(o instanceof Error?o:new Error(String(o)));}}a(ct,"applyJsonBody");function jt(t,e){if(e.toLowerCase().includes("json"))return true;let r=t.trimStart().charAt(0);return r==="{"||r==="["}a(jt,"looksLikeJson");var de=Symbol.for("truxie:filters"),ut=Symbol.for("truxie:catch");function dt(...t){return (e,r,o)=>{let s=r?e.constructor:e,i=Reflect.getOwnMetadata(de,s)??[];Reflect.defineMetadata(de,[...i,...t],s);}}a(dt,"UseFilters");function ft(...t){return e=>{Reflect.defineMetadata(ut,t,e);}}a(ft,"Catch");function fe(t){return b$2(de,t)}a(fe,"getFiltersMetadata");function le(t){return Reflect.getOwnMetadata(ut,t)??[]}a(le,"getCatchMetadata");var g=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);}},L=class extends g{static{a(this,"NotFoundError");}constructor(e="Resource not found"){super(e,404);}},y=class extends g{static{a(this,"ValidationError");}errors;constructor(e="Validation failed",r){super(e,400),this.errors=r;}},K=class extends g{static{a(this,"UnauthorizedError");}constructor(e="Not authorized"){super(e,401);}},C=class extends g{static{a(this,"ForbiddenError");}constructor(e="Access forbidden"){super(e,403);}},Y=class extends g{static{a(this,"ConflictError");}constructor(e="Resource conflict"){super(e,409);}},S=class extends g{static{a(this,"RequestAbortedError");}constructor(e="Request aborted by client"){super(e,499);}};function O(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 R(t,d);try{E(o);let f=await R(t,s);return await zt(o,f,async()=>{E(o);let l=await R(t,i);for(let I of l)if(E(o),!await I.canActivate(o))throw new C("Access denied by guard");E(o);let p=await R(t,c);for(let I of p)E(o),await I.transform(o);E(o);let m=await R(t,a$1),h=a(async()=>(E(o),r.handler(o)),"handlerCall");return m.length===0?h():m.reduceRight((I,_e)=>async()=>(E(o),_e.intercept(o,I)),h)()})}catch(f){return Wt(f,o,u)}}}a(O,"createPipeline");async function zt(t,e,r){return e.length===0?r():e.reduceRight((s,i)=>()=>i.use(t,s),r)()}a(zt,"runMiddlewareChain");function E(t){if(t.getSignal().aborted)throw new S}a(E,"checkAborted");async function Wt(t,e,r){for(let o of r){let s=le(o.constructor);if(s.length===0||t instanceof Error&&s.some(a=>t instanceof a))return o.catch(t,e)}throw t}a(Wt,"handleError");async function R(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(Ht(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(R,"resolveRefs");function Ht(t){return i$1(t).length>0||j$1(t).size>0?true:(Reflect.getMetadata?.("design:paramtypes",t)??[]).length>0}a(Ht,"declaresDependencies");var pe=Symbol.for("truxie:interceptors"),he=Symbol.for("truxie:method:interceptors");function lt(...t){return (e,r,o)=>{if(r!==void 0){let i=o?.value??e,a=i[he]??[];return i[he]=[...a,...t],o}let s=Reflect.getOwnMetadata(pe,e)??[];Reflect.defineMetadata(pe,[...s,...t],e);}}a(lt,"UseInterceptors");function me(t){return b$2(pe,t)}a(me,"getInterceptorsMetadata");function ge(t,e){let o=t.prototype?.[e];return typeof o=="function"&&o[he]||[]}a(ge,"getMethodInterceptors");function V(t,e){return [...me(t),...ge(t,e)]}a(V,"getEffectiveInterceptors");var ye="uow:session",we="uow:instance",J=class{static{a(this,"UnitOfWorkInterceptor");}factory;constructor(e){this.factory=e;}async intercept(e,r){let o=this.factory();await o.start(),e.setData(ye,o.getContext()),e.setData(we,o);try{let s=await r();return await o.commit(),s}catch(s){throw await o.rollback(),s}}};var xe=Symbol.for("truxie:middlewares"),Ee=Symbol.for("truxie:method:middlewares");function pt(...t){return (e,r,o)=>{if(r!==void 0){let i=o?.value??e,a=i[Ee]??[];return i[Ee]=[...a,...t],o}let s=Reflect.getOwnMetadata(xe,e)??[];Reflect.defineMetadata(xe,[...s,...t],e);}}a(pt,"UseMiddleware");function Re(t){return b$2(xe,t)}a(Re,"getMiddlewaresMetadata");function be(t,e){let o=t.prototype?.[e];return typeof o=="function"&&o[Ee]||[]}a(be,"getMethodMiddlewares");function Q(t,e){return [...Re(t),...be(t,e)]}a(Q,"getEffectiveMiddlewares");var Me=Symbol.for("truxie:pipes");function ht(...t){return (e,r,o)=>{let s=r?e.constructor:e,i=Reflect.getOwnMetadata(Me,s)??[];Reflect.defineMetadata(Me,[...i,...t],s);}}a(ht,"UsePipes");function ve(t){return b$2(Me,t)}a(ve,"getPipesMetadata");var Lt=/^[0-9a-fA-F]{24}$/,X=class{static{a(this,"ParseIdPipe");}paramName;constructor(e="id"){this.paramName=e;}transform(e){let o=e.getParams()[this.paramName];if(!o||!Lt.test(o))throw new y(`Invalid ${this.paramName}: must be a valid ObjectId`)}};var Z=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 mt(t){return {transform(e){return e??t}}}a(mt,"DefaultValuePipe");var ee=class{static{a(this,"DomainEvent");}payload;timestamp;constructor(e){this.payload=e,this.timestamp=Date.now();}};function gt(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(gt,"clientSafeError");var b=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(r);for(let i of s){let a=yt(`${this.globalPrefix}/${o}/${i.path}`);Yt(a,r.name,i.methodName),this.checkDuplicate(a,i.method,r.name,i.methodName);let{pattern:c,paramNames:d}=wt(a),u=n(r,i.methodName),f=V(r,i.methodName),l=Q(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:ve(r),filterRefs:fe(r),rawPath:a});}}this.routes.sort((r,o)=>xt(r.rawPath)-xt(o.rawPath));}checkDuplicate(e,r,o,s){let{pattern:i}=wt(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=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};
|
|
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 wt(t){let e=[],r=t.split("/").map(o=>o.startsWith(":")?(e.push(o.slice(1)),"([^/]+)"):Kt(o)).join("/");return {pattern:new RegExp(`^${r}$`),paramNames:e}}a(wt,"compilePath");function Kt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(Kt,"escapeRegex");function xt(t){return t.split("/").filter(Boolean).reduce((e,r)=>e+(r.startsWith(":")?1:0),0)}a(xt,"routePriority");function Yt(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(Yt,"validatePath");var k="__trustProxy",Pe="__remoteAddress";function Et(t){return D(t.getNativeRequest())}a(Et,"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 te(t){let e=Vt(t);if(t.getData(k)!==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(te,"clientIp");function Vt(t){let e=t.getData(Pe);if(e)return e;let r=t.getNativeRequest();return r?.node?.req?.socket?.remoteAddress??r?.socket?.remoteAddress??""}a(Vt,"directAddress");var M=Symbol.for("truxie:route:params");function Jt(t){return t==null?false:typeof t=="function"||typeof t=="object"&&typeof t.transform=="function"}a(Jt,"isParamPipeRef");function re(t,e){return Jt(t)?{key:void 0,pipes:[t,...e??[]]}:{key:t,pipes:e??[]}}a(re,"resolveArgs");function w(t,e,r=[]){return (o,s,i)=>{if(s===void 0)return;let a=o[s];if(typeof a!="function")return;let c=a[M]??[];a[M]=[...c,{index:i,type:t,key:e,pipes:r.length>0?r:void 0}];}}a(w,"buildBuiltinDecorator");function Qt(t){return typeof t=="function"?new t:t}a(Qt,"resolveParamPipe");function Rt(t,...e){let{key:r,pipes:o}=re(t,e);return w("query",r,o)}a(Rt,"Query");function bt(t,...e){let{key:r,pipes:o}=re(t,e);return w("param",r,o)}a(bt,"Param");function Mt(t,...e){let{key:r,pipes:o}=re(t,e);return w("body",r,o)}a(Mt,"Body");var vt=a(()=>w("rawBody"),"RawBody"),Pt=a(()=>w("formData"),"FormData"),At=a(()=>w("ip"),"Ip"),Ct=a(()=>w("userAgent"),"UserAgent"),St=a(t=>w("cookie",t),"Cookie");function Dt(t,...e){let{key:r,pipes:o}=re(t,e);return w("headers",r,o)}a(Dt,"Headers");function Ae(t){return ()=>(e,r,o)=>{if(r===void 0)return;let s=e[r];if(typeof s!="function")return;let i=s[M]??[];s[M]=[...i,{index:o,type:"auth",extractor:t}];}}a(Ae,"defineAuth");var It=Ae();function _t(t,e){return ()=>(r,o,s)=>{if(o===void 0)return;let i=r[o];if(typeof i!="function")return;let a=i[M]??[];i[M]=[...a,{index:s,type:"custom",extractor:t,schema:e?.schema,source:e?.source}];}}a(_t,"createParamDecorator");function v(t,e){let r=t.prototype[e];if(typeof r!="function")return null;let o=r[M];return o&&o.length>0?o:null}a(v,"getRouteParams");async function oe(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(m=>m.trim()).find(m=>m.startsWith(a+"="));u=p?decodeURIComponent(p.slice(a.length+1)):void 0;}else u=void 0;break}case "ip":{u=te(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 Qt(f).transform(u);o[s]=u;}return o}a(oe,"resolveParamArgs");var ne=Symbol.for("truxie:api:doc");function Nt(t){return (e,r,o)=>o!==void 0?(typeof o.value=="function"&&Se(o.value,t,"override"),o):(typeof e=="function"&&Se(e,t,"override"),e)}a(Nt,"ApiDoc");function Tt(t,e){Se(t,e,"fill");}a(Tt,"contributeApiDoc");function Se(t,e,r){let o=t,s=Xt(o[ne])?o[ne]:{},i=Ce(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=Ce(s.request??{}),u=Ce(i.request??{});a.request=r==="override"?{...d,...u}:{...u,...d};}o[ne]=a;}a(Se,"writeApiDoc");function Ce(t){return Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0))}a(Ce,"defined");function Xt(t){return typeof t=="object"&&t!==null}a(Xt,"isRecord");function F(t,e){let r=t.prototype?.[e];if(typeof r!="function")return null;let o=r[ne];return Zt(o)?o:null}a(F,"getApiDoc");function Ot(t){return t?.returns?(Array.isArray(t.returns)?t.returns:[t.returns]).map(r=>({...r,status:r.status??200})):[]}a(Ot,"apiResponses");function Zt(t){return typeof t=="object"&&t!==null&&typeof t.summary=="string"}a(Zt,"isApiDoc");function $t(t,e={}){let r=v(t.controllerClass,t.methodName)??[],o=F(t.controllerClass,t.methodName)?.request,s=e.toJsonSchema,i={},a=De(r,"param",s)??se(o?.params,s)??rr(t.paramNames);a&&(i.params=a);let c=e.querySchema??De(r,"query",s)??se(o?.query,s)??kt(r,"query");if(c&&(i.query=c),t.method!=="GET"){let d=e.bodySchema??De(r,"body",s)??se(o?.body,s)??kt(r,"body")??tr(r);d&&Object.assign(i,{body:d},er(o));}return i}a($t,"describeRouteInput");function er(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(er,"bodyMedia");function De(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(De,"schemaFor");function se(t,e){if(t!==void 0)return Ie(t)?t:e?.(t,{io:"input"})??void 0}a(se,"documentedSchema");function kt(t,e){let r=Gt(t,e);if(r.length===0)return;let o={};for(let s of r)o[s]={};return {type:"object",properties:o}}a(kt,"keyedSchema");function tr(t){return t.some(r=>r.type==="body"||r.source==="body")?{type:"object",description:"Shape not declared by the handler."}:void 0}a(tr,"looseBody");function rr(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(rr,"pathParamsSchema");function Ie(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(Ie,"isJsonSchemaObject");function qt(t,e={}){let r=v(t.controllerClass,t.methodName)??[],o=F(t.controllerClass,t.methodName)?.request;return {query:Ft(r,"query",o?.query,e.toJsonSchema),body:Ft(r,"body",o?.body,e.toJsonSchema)}}a(qt,"routeInputDrift");function Ft(t,e,r,o){let s={undocumented:[],unread:[]};if(r===void 0||or(t,e))return s;let i=nr(se(r,o));if(!i)return s;let a=new Set(Gt(t,e)),c=new Set(i);return {undocumented:[...a].filter(d=>!c.has(d)),unread:i.filter(d=>!a.has(d))}}a(Ft,"partDrift");function Gt(t,e){let r=t.filter(o=>o.type===e&&typeof o.key=="string").map(o=>o.key);return [...new Set(r)]}a(Gt,"readKeys");function or(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(or,"readsWholeObject");function nr(t){let r=sr(t)?.properties;return typeof r!="object"||r===null?null:Object.keys(r)}a(nr,"propertyNames");function sr(t){let e=t?.$ref;if(typeof e!="string")return t;let r=/^#\/(\$defs|definitions)\/([^/]+)$/.exec(e);return r?t?.[r[1]]?.[ir(r[2])]??t:t}a(sr,"resolveRootRef");function ir(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}a(ir,"decodePointer");var Bt="__redirect";function Ut(t,e=302){return {__redirect:true,url:t,statusCode:e}}a(Ut,"redirect");function ie(t){return t!==null&&typeof t=="object"&&t.__redirect===true}a(ie,"isRedirect");function ae(){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(ae,"isServerless");var $=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??ae(),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 b(this.prefix),this.router.register(...this.registry.getAllControllers()),this.initialized=true;}setGlobalPrefix(e){return this.prefix=e,this.initialized&&(this.router=new b(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=v(e.controllerClass,e.methodName);r.setData("__controllerClass",e.controllerClass),r.setData("__methodName",e.methodName),r.setData(k,this.trustProxy),r.setHandler?.(a$1),r.setContainer?.(o);let f=await O(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 oe(d,l)):c(l),"handler")})(r);if(ie(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,o={async open(i){let c="/"+(e.getUrl(i).split("?")[0]??"/").replace(/^\/+|\/+$/g,""),d=r.matchGatewayPath(c);if(!d)return;let u=r.gateways.get(d),f=e.adaptPeer(i);for(let p of u.guards){let m=false;try{m=await p.canActivate(f);}catch(h){console.error(`[WS] ${u.className} guard error:`,h);}if(!m){f.close(1008,"Unauthorized");return}}let l=i.context;l&&(l._gatewayPath=d);for(let p of u.serverProps)u.instance[p]={peers:e.getPeers(i)??new Set};if(u.hasConnection)try{await u.instance.handleConnection(f);}catch(p){console.error(`[WS] ${u.className}.handleConnection error:`,p),u.rawMessage&&(l&&(l._rawGatewayFailed=true),f.close(1011,"Gateway connection failed"));}},async message(i,a){let c=i.context,d=c?._gatewayPath;if(!d)return;let u=r.gateways.get(d);if(!u)return;let f=e.adaptPeer(i),l=e.adaptMessage(a);if(u.rawMessage){if(c?._rawGatewayFailed)return;try{let h=await u.rawMessage(f,l);h!=null&&f.send(h);}catch(h){console.error(`[WS] ${u.className}.handleRawMessage error:`,h),f.close(1011,"Gateway message failed"),c&&(c._rawGatewayFailed=true);}return}let p;try{p=l.json();}catch{return}if(!p.event||typeof p.event!="string")return;let m=u.messageHandlers.get(p.event);if(m)try{let h=n$1(m.paramMeta,f,l,p.data),q=await m.method(...h);q!=null&&f.send(q);}catch(h){console.error(`[WS] ${u.className}.${p.event} error:`,h);}},async close(i,a){let d=i.context?._gatewayPath;if(!d)return;let u=r.gateways.get(d);if(!u?.hasDisconnect)return;let f=e.adaptPeer(i);try{await u.instance.handleDisconnect(f,a);}catch(l){console.error(`[WS] ${u.className}.handleDisconnect error:`,l);}},async error(i,a){let c=i?.id??"unknown";console.error(`[WS] Peer ${String(c)} error:`,a);}},s=new Map;return {open(i){let a="/"+(e.getUrl(i).split("?")[0]??"/").replace(/^\/+|\/+$/g,""),c=r.matchGatewayPath(a),d=o.open(i);return c&&r.gateways.get(c)?.rawMessage&&s.set(i,d),d},message(i,a){let c=s.get(i);if(!c)return o.message(i,a);let d=c.then(()=>o.message(i,a));return s.set(i,d),d},close(i,a){let c=s.get(i);if(!c)return o.close(i,a);let d=c.then(()=>o.close(i,a));return s.set(i,d),d.finally(()=>s.delete(i))},error:o.error}}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(),O(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")}}async hasWebSocketGateway(e){this.ensureInitialized(),await this.initGateways();let r="/"+(e.split("?")[0]??"/").replace(/^\/+|\/+$/g,"");return this.matchGatewayPath(r)!==void 0}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 c of j(e)){let d=o[c.methodName];typeof d=="function"&&s.set(c.event,{method:d.bind(o),paramMeta:k$2(e.prototype[c.methodName])});}let i$1=o.handleRawMessage;if(r.raw&&(typeof i$1!="function"||s.size))throw new Error(`Raw WebSocket gateway ${e.name} requires handleRawMessage and cannot use @SubscribeMessage`);let a=await R(this.container,l(e));if(this.gateways.set(r.path,{instance:o,className:e.name,messageHandlers:s,rawMessage:r.raw?i$1.bind(o):void 0,hasConnection:typeof o.handleConnection=="function",hasDisconnect:typeof o.handleDisconnect=="function",serverProps:m$1(e),guards:a}),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().")}},ce=class{static{a(this,"TruxieFactory");}static async create(e,r){let o=new $(e,r);return await o.init(),o}};export{Nt as ApiDoc,g as AppError,It as Auth,H as BaseExecutionContext,Mt as Body,ft as Catch,W as ConfigurableModuleBuilder,Y as ConflictError,b as ControllerRouter,St as Cookie,mt as DefaultValuePipe,ee as DomainEvent,C as ForbiddenError,Pt as FormData,Dt as Headers,At as Ip,L as NotFoundError,bt as Param,X as ParseIdPipe,Z as ParseIntPipe,Rt as Query,Bt as REDIRECT_BRAND,Pe as REMOTE_ADDRESS_KEY,vt as RawBody,S as RequestAbortedError,k as TRUST_PROXY_KEY,$ as TruxieApplication,ce as TruxieFactory,we as UOW_INSTANCE_KEY,ye as UOW_SESSION_KEY,K as UnauthorizedError,J as UnitOfWorkInterceptor,dt as UseFilters,lt as UseInterceptors,pt as UseMiddleware,ht as UsePipes,Ct as UserAgent,y as ValidationError,Ot as apiResponses,ct as applyJsonBody,te as clientIp,gt as clientSafeError,Tt as contributeApiDoc,ue as createAsyncOptionsProviders,_t as createParamDecorator,O as createPipeline,Ae as defineAuth,$t as describeRouteInput,F as getApiDoc,V as getEffectiveInterceptors,Q as getEffectiveMiddlewares,me as getInterceptorsMetadata,ge as getMethodInterceptors,be as getMethodMiddlewares,Re as getMiddlewaresMetadata,Et as getRequestHeaders,v as getRouteParams,Ie as isJsonSchemaObject,ie as isRedirect,ae as isServerless,Ut as redirect,oe as resolveParamArgs,qt as routeInputDrift};
|
package/dist/testing.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a as a$1,s,r,p as p$1,u,o,q}from'./chunk-
|
|
1
|
+
import {a as a$1,s,r,p as p$1,u,o,q}from'./chunk-AGUTRLO2.js';import'./chunk-3FLBEU46.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};
|
|
@@ -4,6 +4,8 @@ interface WsPeer {
|
|
|
4
4
|
readonly id: string;
|
|
5
5
|
/** Client IP address, if available */
|
|
6
6
|
readonly remoteAddress?: string;
|
|
7
|
+
/** Number of queued outgoing bytes, when the adapter exposes it. */
|
|
8
|
+
bufferedAmount?(): number;
|
|
7
9
|
/** Custom context attached during upgrade */
|
|
8
10
|
readonly context: Record<string, unknown>;
|
|
9
11
|
/** Send data to this peer */
|
|
@@ -41,6 +43,8 @@ interface WsGuard {
|
|
|
41
43
|
interface WsMessage {
|
|
42
44
|
/** Raw data */
|
|
43
45
|
readonly rawData: unknown;
|
|
46
|
+
/** Frame bytes, when the adapter supplies them. */
|
|
47
|
+
bytes?(): Uint8Array;
|
|
44
48
|
/** Get message as string */
|
|
45
49
|
text(): string;
|
|
46
50
|
/** Parse message as JSON */
|
|
@@ -53,12 +57,15 @@ interface WsCloseDetails {
|
|
|
53
57
|
interface GatewayOptions {
|
|
54
58
|
/** WebSocket path. @default '/' */
|
|
55
59
|
path?: string;
|
|
60
|
+
/** Deliver frames unchanged to handleRawMessage instead of JSON event dispatch. */
|
|
61
|
+
raw?: boolean;
|
|
56
62
|
/** Namespace for grouping. @default '/' */
|
|
57
63
|
namespace?: string;
|
|
58
64
|
}
|
|
59
65
|
interface GatewayMetadata {
|
|
60
66
|
path: string;
|
|
61
67
|
namespace: string;
|
|
68
|
+
raw?: boolean;
|
|
62
69
|
target: Function;
|
|
63
70
|
}
|
|
64
71
|
interface MessageHandlerEntry {
|
|
@@ -124,5 +131,9 @@ interface OnGatewayDisconnect {
|
|
|
124
131
|
interface OnGatewayInit {
|
|
125
132
|
afterInit(): void | Promise<void>;
|
|
126
133
|
}
|
|
134
|
+
/** Raw gateways receive the original frame, including binary payloads. */
|
|
135
|
+
interface OnGatewayRawMessage {
|
|
136
|
+
handleRawMessage(peer: WsPeer, message: WsMessage): unknown | Promise<unknown>;
|
|
137
|
+
}
|
|
127
138
|
|
|
128
|
-
export type { GatewayOptions as G, MessageHandlerEntry as M, OnGatewayConnection as O, WsPeer as W, WsMessage as a, WsGuard as b, GatewayMetadata as c, WsParamType as d, OnGatewayDisconnect as e, OnGatewayInit as f,
|
|
139
|
+
export type { GatewayOptions as G, MessageHandlerEntry as M, OnGatewayConnection as O, WsPeer as W, WsMessage as a, WsGuard as b, GatewayMetadata as c, WsParamType as d, OnGatewayDisconnect as e, OnGatewayInit as f, OnGatewayRawMessage as g, WsCloseDetails as h };
|
package/dist/ws.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { G as GatewayOptions, b as WsGuard, W as WsPeer, a as WsMessage, c as GatewayMetadata, M as MessageHandlerEntry, d as WsParamType } from './types-
|
|
2
|
-
export { O as OnGatewayConnection, e as OnGatewayDisconnect, f as OnGatewayInit, g as WsCloseDetails } from './types-
|
|
1
|
+
import { G as GatewayOptions, b as WsGuard, W as WsPeer, a as WsMessage, c as GatewayMetadata, M as MessageHandlerEntry, d as WsParamType } from './types-CUcndOdw.js';
|
|
2
|
+
export { O as OnGatewayConnection, e as OnGatewayDisconnect, f as OnGatewayInit, g as OnGatewayRawMessage, h as WsCloseDetails } from './types-CUcndOdw.js';
|
|
3
3
|
|
|
4
4
|
/** Constructor of a gateway guard, as accepted by `@WsGuards`. */
|
|
5
5
|
type WsGuardClass = new (...args: any[]) => WsGuard;
|
package/dist/ws.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{e as ConnectedSocket,d as MessageBody,b as SubscribeMessage,a as WebSocketGateway,c as WebSocketServer,f as WsAuth,h as WsGuards,g as createWsParamDecorator,i as getGatewayMetadata,j as getMessageHandlers,l as getWsGuards,k as getWsParams,m as getWsServerProperties,n as resolveWsArgs}from'./chunk-
|
|
1
|
+
export{e as ConnectedSocket,d as MessageBody,b as SubscribeMessage,a as WebSocketGateway,c as WebSocketServer,f as WsAuth,h as WsGuards,g as createWsParamDecorator,i as getGatewayMetadata,j as getMessageHandlers,l as getWsGuards,k as getWsParams,m as getWsServerProperties,n as resolveWsArgs}from'./chunk-3FLBEU46.js';import'./chunk-EI7MMDWY.js';
|
package/package.json
CHANGED
package/dist/chunk-RDP32XIU.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import {a}from'./chunk-EI7MMDWY.js';import'reflect-metadata';var l=Symbol.for("truxie:ws:gateway"),f=Symbol.for("truxie:ws:message"),d=Symbol.for("truxie:ws:params"),x=Symbol.for("truxie:ws:guards"),g=Symbol.for("truxie:ws:server");function w(e){return n=>{let o=typeof e=="string"?{path:e}:e??{},a={path:o.path??"/",namespace:o.namespace??"/",target:n};Reflect.defineMetadata(l,a,n);}}a(w,"WebSocketGateway");function p(e){return (n,o,a)=>{let s=n.constructor,r=Reflect.getOwnMetadata(f,s)??[];Reflect.defineMetadata(f,[...r,{event:e,methodName:String(o)}],s);}}a(p,"SubscribeMessage");function M(){return (e,n)=>{let o=e.constructor,a=Reflect.getOwnMetadata(g,o)??[];Reflect.defineMetadata(g,[...a,String(n)],o);}}a(M,"WebSocketServer");function i(e,n){return (o,a,s)=>{if(a===void 0)return;let r=o[a];if(typeof r!="function")return;let c=r[d]??[];r[d]=[...c,{type:e,index:s,extractor:n}];}}a(i,"buildWsParamDecorator");var b=a(()=>i("message-body"),"MessageBody"),R=a(()=>i("connected-socket"),"ConnectedSocket"),W=a(()=>i("ws-auth"),"WsAuth");function y(e){return ()=>i("custom",e)}a(y,"createWsParamDecorator");function A(...e){return n=>{let o=Reflect.getOwnMetadata(x,n)??[];Reflect.defineMetadata(x,[...o,...e],n);}}a(A,"WsGuards");function h(e){return Reflect.getOwnMetadata(l,e)}a(h,"getGatewayMetadata");function k(e){return Reflect.getOwnMetadata(f,e)??[]}a(k,"getMessageHandlers");function _(e){return e[d]??[]}a(_,"getWsParams");function E(e){return Reflect.getOwnMetadata(x,e)??[]}a(E,"getWsGuards");function G(e){return Reflect.getOwnMetadata(g,e)??[]}a(G,"getWsServerProperties");function D(e,n,o,a){if(e.length===0)return [];let s=Math.max(...e.map(c=>c.index)),r=new Array(s+1).fill(void 0);for(let{type:c,index:u,extractor:S}of e)switch(c){case "message-body":r[u]=a;break;case "connected-socket":r[u]=n;break;case "ws-auth":r[u]=n.context.auth;break;case "custom":r[u]=S?S(n,o):void 0;break}return r}a(D,"resolveWsArgs");export{w as a,p as b,M as c,b as d,R as e,W as f,y as g,A as h,h as i,k as j,_ as k,E as l,G as m,D as n};
|