@truxie/nitro 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -22,6 +22,35 @@ One catch-all handler serves every `@Controller` route, and every `@WebSocketGat
22
22
 
23
23
  A returned `Response` is passed through, a `redirect()` becomes `sendRedirect`, and a status recorded by a filter is applied with `setResponseStatus`.
24
24
 
25
+ ### Lazy applications and native HTTP transports
26
+
27
+ Use `app: () => getApp()` when a Nitro plugin owns application initialization.
28
+ `headFallback: true` maps HEAD to GET, `methodNotAllowed: true` returns 405 for
29
+ known paths, and `parseBody: false` leaves the H3 body untouched for native
30
+ streaming or multipart handlers. `@MethodlessTransport()` on a POST controller
31
+ lets that operation negotiate the incoming method without exposing other POST
32
+ routes. `websocket: false` disables upgrades on HTTP-only mounts.
33
+
34
+ ### Binary WebSocket gateways
35
+
36
+ ```ts
37
+ import { Injectable } from 'truxie'
38
+ import { WebSocketGateway, type WsPeer, type WsMessage, type OnGatewayRawMessage } from 'truxie/ws'
39
+
40
+ @Injectable()
41
+ @WebSocketGateway({ path: '/api/binary', raw: true })
42
+ class BinaryGateway implements OnGatewayRawMessage {
43
+ handleRawMessage(peer: WsPeer, message: WsMessage) {
44
+ peer.send(message.bytes?.() ?? message.rawData)
45
+ }
46
+ }
47
+ ```
48
+
49
+ Register the gateway in module providers. Raw gateways receive frames without
50
+ JSON event parsing, preserve binary bytes on send/publish, offer queued-byte
51
+ counts when available, and process open, messages and close in order per peer.
52
+ JSON gateways and `@WsGuards` keep their existing behavior.
53
+
25
54
  ## One handler, without a controller
26
55
 
27
56
  For a single endpoint that does not want a controller class:
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { H3Event, EventHandler } from 'h3';
2
- import { BaseExecutionContext, Container, PipelineOptions, TruxieApplication, ExecutionContext } from 'truxie';
2
+ import * as truxie from 'truxie';
3
+ import { BaseExecutionContext, Container, PipelineOptions, TruxieApplication, ExecutionContext, CompiledRoute } from 'truxie';
3
4
 
4
5
  declare class NitroExecutionContext extends BaseExecutionContext<H3Event> {
5
6
  constructor(event: H3Event, handler: Function, container: Container);
@@ -29,10 +30,23 @@ declare function nitroHandler(app: TruxieApplication, options: NitroHandlerOptio
29
30
  */
30
31
  declare function defineHandler(app: TruxieApplication, optionsOrHandler: NitroHandlerOptions | NitroHandlerFn, maybeHandler?: NitroHandlerFn): EventHandler;
31
32
 
33
+ /** The controller operation owns native HTTP method negotiation (legacy or TC39 decorators). */
34
+ declare function MethodlessTransport(): any;
35
+ declare function isMethodlessTransport(route: CompiledRoute): boolean;
32
36
  interface ControllerDispatcherOptions {
33
- /** The initialized TruxieApplication instance */
34
- app: TruxieApplication;
37
+ /** An initialized application, or a lazy resolver (e.g. Nitro's boot plugin). */
38
+ app: TruxieApplication | (() => TruxieApplication | Promise<TruxieApplication>);
39
+ /** Disable automatic body parsing when controller operations own native H3 requests. */
40
+ parseBody?: boolean;
41
+ /** Dispatch HEAD to GET without changing the native request method. */
42
+ headFallback?: boolean;
43
+ /** Return 405 for a known path with an unsupported method instead of 404. */
44
+ methodNotAllowed?: boolean;
45
+ /** Disable gateway upgrades on a mount intended only for HTTP. */
46
+ websocket?: boolean;
35
47
  }
48
+ /** Exact method match, optional HEAD fallback, then explicitly methodless POST transports. */
49
+ declare function matchControllerRoute(app: TruxieApplication, method: string, pathname: string, headFallback?: boolean): truxie.RouteMatch | null;
36
50
  /**
37
51
  * Create a Nitro catch-all EventHandler that dispatches HTTP requests
38
52
  * to @Controller methods AND WebSocket upgrades to @WebSocketGateway classes.
@@ -49,4 +63,4 @@ interface ControllerDispatcherOptions {
49
63
  */
50
64
  declare function createControllerDispatcher(options: ControllerDispatcherOptions): EventHandler;
51
65
 
52
- export { type ControllerDispatcherOptions, NitroExecutionContext, type NitroHandlerOptions, createControllerDispatcher, defineHandler, nitroHandler as nitro, nitroHandler };
66
+ export { type ControllerDispatcherOptions, MethodlessTransport, NitroExecutionContext, type NitroHandlerOptions, createControllerDispatcher, defineHandler, isMethodlessTransport, matchControllerRoute, nitroHandler as nitro, nitroHandler };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import {BaseExecutionContext,getRouteParams,applyJsonBody}from'truxie';import {eventHandler}from'h3';var w=Object.defineProperty;var n=(e,t)=>w(e,"name",{value:t,configurable:true});var l=class extends BaseExecutionContext{static{n(this,"NitroExecutionContext");}constructor(t,o,r){let a=b(t),i=t.context.params??{},d=g(t);super(t,o,r,a,i,d),t.context.auth&&this.setAuth(t.context.auth);}};function g(e){let t=new AbortController,o=e.node?.res;if(o){let r=false;o.on("finish",()=>{r=true;}),o.on("close",()=>{r||t.abort("Client disconnected");});}return t}n(g,"createRequestAbortController");function b(e){try{let t=e.node?.req?.url??"",o=t.indexOf("?");if(o===-1)return {};let r=new URLSearchParams(t.slice(o)),a={};return r.forEach((i,d)=>{a[d]=i;}),a}catch{return {}}}n(b,"getQuerySafe");function y(e,t,o){let r=e.getContainer(),a;return async i=>{a||(a=e.createHandler({middlewares:t.middlewares,guards:t.guards,interceptors:t.interceptors,pipes:t.pipes,filters:t.filters,handler:o}));let d=new l(i,o,r);if(t.parseBody!==false)try{let{readBody:p}=await import('h3'),f=await p(i);f!=null&&d.setBody(f);}catch{}return a(d)}}n(y,"nitroHandler");function C(e,t,o){return y(e,typeof t=="function"?{}:t,typeof t=="function"?t:o)}n(C,"defineHandler");function D(e){let{app:t}=e,o=eventHandler(async r=>{let a=r.method.toUpperCase(),d=(r.path??r.node?.req?.url??"").split("?")[0]??"",p=t.matchRoute(a,d);if(!p){let{createError:m}=await import('h3');throw m({statusCode:404,statusMessage:"Not Found"})}let{route:f,params:c}=p;r.context.params={...r.context.params,...c};let s=new l(r,()=>{},t.getContainer());await E(r,s,f.controllerClass,f.methodName);let u=await t.handleRequest(f,s);if(u.isRedirect){let{sendRedirect:m}=await import('h3');return m(r,u.redirectUrl,u.redirectStatus)}if(u.value instanceof Response)return u.value;let h=s.getData("__statusCode");if(h!==void 0){let{setResponseStatus:m}=await import('h3');m(r,h);}return u.value});return t.hasGateways()&&t.createWebSocketHooks({adaptPeer:q,adaptMessage:N,getUrl:n(r=>r.request?.url??r.context._url??"/","getUrl"),getPeers:n(r=>r.peers,"getPeers")}).then(r=>{o.__websocket__=r;}),o}n(D,"createControllerDispatcher");async function E(e,t,o,r){if(e.method.toUpperCase()==="GET")return;let a=getRouteParams(o,r),i=e.node?.req?.headers?.["content-type"]??"",d=a?.some(c=>c.type==="rawBody")??false,p=a?.some(c=>c.type==="formData")??false,f=a?.some(c=>c.type==="body")??false;try{if(p&&i.includes("multipart/")){let{readMultipartFormData:c}=await import('h3'),s=await c(e);s&&t.setFormData(s.map(u=>({name:u.name??"",filename:u.filename,type:u.type,data:Buffer.from(u.data)})));}else if(d){let{readRawBody:c}=await import('h3'),s=await c(e);s!=null&&(t.setRawBody(s),f&&typeof s=="string"&&applyJsonBody(t,s,i));}else if(!i.includes("multipart/")){let{readBody:c}=await import('h3');try{let s=await c(e);s!=null&&t.setBody(s);}catch(s){t.setBodyParseError(s instanceof Error?s:new Error(String(s)));}}}catch{}}n(E,"parseBody");function q(e){return {get id(){return e.id},get remoteAddress(){return e.remoteAddress},get context(){return e.context},send(t,o){e.send(typeof t=="string"?t:JSON.stringify(t),o);},publish(t,o,r){e.publish(t,typeof o=="string"?o:JSON.stringify(o),r);},subscribe:n(t=>e.subscribe(t),"subscribe"),unsubscribe:n(t=>e.unsubscribe(t),"unsubscribe"),close:n((t,o)=>e.close(t,o),"close"),terminate:n(()=>e.terminate?.()??e.close(),"terminate"),get peers(){return e.peers??new Set},get topics(){return e.topics??new Set}}}n(q,"adaptCrosswsPeer");function N(e){return {get rawData(){return e.rawData??e},text(){return typeof e.text=="function"?e.text():typeof e=="string"?e:String(e)},json(){if(typeof e.json=="function")return e.json();let t=typeof e.text=="function"?e.text():String(e);return JSON.parse(t)}}}n(N,"adaptCrosswsMessage");export{l as NitroExecutionContext,D as createControllerDispatcher,C as defineHandler,y as nitro,y as nitroHandler};
1
+ import {BaseExecutionContext,getRouteParams,applyJsonBody}from'truxie';import {eventHandler}from'h3';var E=Object.defineProperty;var a=(t,e)=>E(t,"name",{value:e,configurable:true});var p=class extends BaseExecutionContext{static{a(this,"NitroExecutionContext");}constructor(e,n,r){let s=P(e),o=e.context.params??{},c=D(e);super(e,n,r,s,o,c),e.context.auth&&this.setAuth(e.context.auth);}};function D(t){let e=new AbortController,n=t.node?.res;if(n){let r=false;n.on("finish",()=>{r=true;}),n.on("close",()=>{r||e.abort("Client disconnected");});}return e}a(D,"createRequestAbortController");function P(t){try{let e=t.node?.req?.url??"",n=e.indexOf("?");if(n===-1)return {};let r=new URLSearchParams(e.slice(n)),s={};return r.forEach((o,c)=>{s[c]=o;}),s}catch{return {}}}a(P,"getQuerySafe");function w(t,e,n){let r=t.getContainer(),s;return async o=>{s||(s=t.createHandler({middlewares:e.middlewares,guards:e.guards,interceptors:e.interceptors,pipes:e.pipes,filters:e.filters,handler:n}));let c=new p(o,n,r);if(e.parseBody!==false)try{let{readBody:f}=await import('h3'),l=await f(o);l!=null&&c.setBody(l);}catch{}return s(c)}}a(w,"nitroHandler");function M(t,e,n){return w(t,typeof e=="function"?{}:e,typeof e=="function"?e:n)}a(M,"defineHandler");var g=Symbol.for("truxie:nitro:methodless");function H(){return (t,e,n)=>{let r=n?.value??t;return typeof r=="function"&&Object.defineProperty(r,g,{value:true}),n??t}}a(H,"MethodlessTransport");function C(t){return t.controllerClass.prototype[t.methodName]?.[g]===true}a(C,"isMethodlessTransport");function A(t,e,n,r=false){let s=t.matchRoute(e,n)??(r&&e.toUpperCase()==="HEAD"?t.matchRoute("GET",n):null);if(s)return s;let o=t.matchRoute("POST",n);return o&&C(o.route)?o:null}a(A,"matchControllerRoute");function _(t){let e=a(async()=>typeof t.app=="function"?t.app():t.app,"resolveApp"),n=eventHandler(async r=>{let s=await e(),o=r.method.toUpperCase(),f=(r.path??r.node?.req?.url??"").split("?")[0]??"",l=A(s,o,f,t.headFallback);if(!l){let{createError:y}=await import('h3'),R=t.methodNotAllowed&&["GET","POST","PUT","PATCH","DELETE"].some(S=>s.matchRoute(S,f));throw y(R?{statusCode:405,statusMessage:"Method Not Allowed"}:{statusCode:404,statusMessage:"Not Found"})}let{route:i,params:u}=l;r.context.params=u;let d=new p(r,()=>{},s.getContainer());t.parseBody!==false&&await G(r,d,i.controllerClass,i.methodName);let m=await s.handleRequest(i,d);if(m.isRedirect){let{sendRedirect:y}=await import('h3');return y(r,m.redirectUrl,m.redirectStatus)}if(m.value instanceof Response)return m.value;let h=d.getData("__statusCode");if(h!==void 0){let{setResponseStatus:y}=await import('h3');y(r,h);}return m.value});if(t.websocket!==false&&(typeof t.app=="function"||t.app.hasGateways())){let r,s=a(()=>r??=e().then(o=>o.createWebSocketHooks({adaptPeer:B,adaptMessage:L,getUrl:a(c=>{let f=c.request?.url??c.context._url??"/";return f.startsWith("/")?f:new URL(f).pathname},"getUrl"),getPeers:a(c=>c.peers,"getPeers")})).catch(o=>{throw r=void 0,o}),"hooks");n.__websocket__={async upgrade(o){let c=await e();await s();let f=o.url.startsWith("/")?o.url:new URL(o.url).pathname;if(!c.hasGateways()||typeof c.hasWebSocketGateway=="function"&&!await c.hasWebSocketGateway(f))return new Response(null,{status:404})},async open(o){await(await s()).open(o);},async message(o,c){await(await s()).message(o,c);},async close(o,c){await(await s()).close(o,c);},async error(o,c){await(await s()).error(o,c);}};}return n}a(_,"createControllerDispatcher");async function G(t,e,n,r){if(t.method.toUpperCase()==="GET")return;let s=getRouteParams(n,r),o=t.node?.req?.headers?.["content-type"]??"",c=s?.some(i=>i.type==="rawBody")??false,f=s?.some(i=>i.type==="formData")??false,l=s?.some(i=>i.type==="body")??false;try{if(f&&o.includes("multipart/")){let{readMultipartFormData:i}=await import('h3'),u=await i(t);u&&e.setFormData(u.map(d=>({name:d.name??"",filename:d.filename,type:d.type,data:Buffer.from(d.data)})));}else if(c){let{readRawBody:i}=await import('h3'),u=await i(t);u!=null&&(e.setRawBody(u),l&&typeof u=="string"&&applyJsonBody(e,u,o));}else if(!o.includes("multipart/")){let{readBody:i}=await import('h3');try{let u=await i(t);u!=null&&e.setBody(u);}catch(u){e.setBodyParseError(u instanceof Error?u:new Error(String(u)));}}}catch{}}a(G,"parseBody");function x(t){return typeof t=="string"||t instanceof ArrayBuffer||ArrayBuffer.isView(t)?t:JSON.stringify(t)}a(x,"wireData");var b=new WeakMap;function B(t){let e=b.get(t);if(e)return e;let n={get id(){return t.id},get remoteAddress(){return t.remoteAddress},get context(){return t.context},bufferedAmount:a(()=>Number(t.websocket?.bufferedAmount??0),"bufferedAmount"),send(r,s){t.send(x(r),s);},publish(r,s,o){t.publish(r,x(s),o);},subscribe:a(r=>t.subscribe(r),"subscribe"),unsubscribe:a(r=>t.unsubscribe(r),"unsubscribe"),close:a((r,s)=>t.close(r,s),"close"),terminate:a(()=>t.terminate?.()??t.close(),"terminate"),get peers(){return new Set(Array.from(t.peers??[],B))},get topics(){return t.topics??new Set}};return b.set(t,n),n}a(B,"adaptCrosswsPeer");function L(t){return {get rawData(){return t.rawData??t},bytes(){if(t.uint8Array)return t.uint8Array();let e=t.rawData;return e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new TextEncoder().encode(typeof e=="string"?e:t.text())},text(){return typeof t.text=="function"?t.text():typeof t=="string"?t:String(t)},json(){if(typeof t.json=="function")return t.json();let e=typeof t.text=="function"?t.text():String(t);return JSON.parse(e)}}}a(L,"adaptCrosswsMessage");export{H as MethodlessTransport,p as NitroExecutionContext,_ as createControllerDispatcher,M as defineHandler,C as isMethodlessTransport,A as matchControllerRoute,w as nitro,w as nitroHandler};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@truxie/nitro",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Nitro adapter for truxie — controller dispatcher and handler utilities",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -27,7 +27,7 @@
27
27
  "test": "vitest run"
28
28
  },
29
29
  "peerDependencies": {
30
- "truxie": "^0.1.1",
30
+ "truxie": "^0.1.1 || ^0.2.0 || ^0.3.0",
31
31
  "h3": ">=1.0.0"
32
32
  },
33
33
  "devDependencies": {