elysia 0.4.8 → 0.4.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/ws/types.d.ts +2 -1
- package/package.json +1 -1
- package/src/index.ts +9 -1
- package/src/ws/types.ts +3 -1
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{nanoid as e}from"nanoid";import{Raikiri as t}from"raikiri";import{parse as r}from"fast-querystring";import{mapResponse as s,mapEarlyResponse as a}from"./handler";import{SCHEMA as i,EXPOSED as o,DEFS as
|
|
1
|
+
import{nanoid as e}from"nanoid";import{Raikiri as t}from"raikiri";import{parse as r}from"fast-querystring";import{mapResponse as s,mapEarlyResponse as a}from"./handler";import{SCHEMA as i,EXPOSED as o,DEFS as n,clone as h,mergeHook as u,getSchemaValidator as d,getResponseSchemaValidator as l,mapPathnameAndQueryRegEx as c,mergeDeep as m}from"./utils";import{registerSchemaPath as p}from"./schema";import{mapErrorCode as f,mapErrorStatus as v}from"./error";import{composeHandler as y}from"./compose";import{ws as g}from"./ws";export default class b{config;store={};meta={[i]:Object.create(null),[n]:Object.create(null),[o]:Object.create(null)};decorators={[i]:this.meta[i],[n]:this.meta[n],store:this.store};event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],error:[],stop:[]};server=null;$schema=null;router=new t;routes=[];_s=new Map;wsRouter;lazyLoadModules=[];constructor(e){this.config={fn:"/~fn",...e}}_addHandler(e,t,r,s){t=t.startsWith("/")?t:`/${t}`,this.routes.push({method:e,path:t,handler:r,hooks:u({...this.event},s)});let a=this.meta[n],o=d(s?.schema?.body??this.$schema?.body,a),c=d(s?.schema?.headers??this.$schema?.headers,a,!0),m=d(s?.schema?.params??this.$schema?.params,a),f=d(s?.schema?.query??this.$schema?.query,a),v=l(s?.schema?.response??this.$schema?.response,a);p({schema:this.meta[i],contentType:s?.schema?.contentType,hook:s,method:e,path:t,models:this.meta[n]});let g=u(h(this.event),s),b=y({method:e,hooks:g,validator:{body:o,headers:c,params:m,query:f,response:v},handler:r,handleError:this.handleError});t.includes("/:")||t.includes("/*")||this._s.set(e+t,b),this.router.add(e,t,b)}onStart(e){return this.event.start.push(e),this}onRequest(e){return this.event.request.push(e),this}onParse(e){return this.event.parse.splice(this.event.parse.length-1,0,e),this}onTransform(e){return this.event.transform.push(e),this}onBeforeHandle(e){return this.event.beforeHandle.push(e),this}onAfterHandle(e){return this.event.afterHandle.push(e),this}onError(e){return this.event.error.push(e),this}onStop(e){return this.event.stop.push(e),this}on(e,t){switch(e){case"start":this.event.start.push(t);break;case"request":this.event.request.push(t);break;case"parse":this.event.parse.push(t);break;case"transform":this.event.transform.push(t);break;case"beforeHandle":this.event.beforeHandle.push(t);break;case"afterHandle":this.event.afterHandle.push(t);break;case"error":this.event.error.push(t);break;case"stop":this.event.stop.push(t)}return this}group(e,t){let r=new b;r.store=this.store,this.wsRouter&&r.use(g());let s=t(r);return this.decorators=m(this.decorators,r.decorators),s.event.request.length&&(this.event.request=[...this.event.request,...s.event.request]),this.setModel(s.meta[n]),Object.values(r.routes).forEach(({method:t,path:a,handler:i,hooks:o})=>{let n="/"===a?e:`${e}${a}`,h=r.wsRouter?.match("subscribe",n);if(h){let e=r.wsRouter.history.find(([e,t])=>a===t);if(!e)return;return this.ws(n,e[2])}this._addHandler(t,n,i,u(o,{error:s.event.error}))}),r.wsRouter&&this.wsRouter&&r.wsRouter.history.forEach(([t,r,s])=>{"/"===r?this.wsRouter?.add(t,e,s):this.wsRouter?.add(t,`${e}${r}`,s)}),this}guard(e,t){let r=new b;r.store=this.store,this.wsRouter&&r.use(g());let s=t(r);return this.decorators=m(this.decorators,r.decorators),s.event.request.length&&(this.event.request=[...this.event.request,...s.event.request]),this.setModel(s.meta[n]),Object.values(r.routes).forEach(({method:t,path:a,handler:i,hooks:o})=>{let n=r.wsRouter?.match("subscribe",a);if(n){let e=r.wsRouter.history.find(([e,t])=>a===t);if(!e)return;return this.ws(a,e[2])}this._addHandler(t,a,i,u(e,{...o,error:o.error?Array.isArray(o.error)?[...o.error,...s.event.error]:[o.error,...s.event.error]:s.event.error}))}),r.wsRouter&&this.wsRouter&&r.wsRouter.history.forEach(([e,t,r])=>{this.wsRouter?.add(e,t,r)}),this}use(e){if(e instanceof Promise)return this.lazyLoadModules.push(e.then(e=>"function"==typeof e?e(this):e.default(this))),this;let t=e(this);return t instanceof Promise?(this.lazyLoadModules.push(t),this):t}if(e,t){return e?this.use(t):this}get(e,t,r){return this._addHandler("GET",e,t,r),this}post(e,t,r){return this._addHandler("POST",e,t,r),this}put(e,t,r){return this._addHandler("PUT",e,t,r),this}patch(e,t,r){return this._addHandler("PATCH",e,t,r),this}delete(e,t,r){return this._addHandler("DELETE",e,t,r),this}options(e,t,r){return this._addHandler("OPTIONS",e,t,r),this}all(e,t,r){return this._addHandler("ALL",e,t,r),this}head(e,t,r){return this._addHandler("HEAD",e,t,r),this}trace(e,t,r){return this._addHandler("TRACE",e,t,r),this}connect(e,t,r){return this._addHandler("CONNECT",e,t,r),this}ws(t,r){if(!this.wsRouter)throw Error("Can't find WebSocket. Please register WebSocket plugin first by importing 'elysia/ws'");return this.wsRouter.add("subscribe",t,r),this.get(t,t=>{if(!this.server?.upgrade(t.request,{headers:"function"==typeof r.headers?r.headers(t):r.headers,data:{...t,id:e(),message:d(r.schema?.body,this.meta[n]),transformMessage:r.transform?Array.isArray(r.transformMessage)?r.transformMessage:[r.transformMessage]:[]}}))return t.set.status=400,"Expected a websocket connection"},{parse:r.parse,beforeHandle:r.beforeHandle,transform:r.transform,schema:{headers:r.schema?.headers,params:r.schema?.params,query:r.schema?.query}}),this}route(e,t,r,s){return this._addHandler(e,t,r,s),this}state(e,t){return e in this.store||(this.store[e]=t),this}decorate(e,t){return e in this.decorators||(this.decorators[e]=t),this}derive(e){return"AsyncFunction"===e.constructor.name?this.onTransform(async t=>{Object.assign(t,await e(t))}):this.onTransform(t=>{Object.assign(t,e(t))})}fn(e){return this.use(async()=>{let{fn:t}=await import("@elysiajs/fn");return t({app:this,value:e,path:this.config.fn})})}schema(e){let t=this.meta[n];return this.$schema={body:d(e.body,t),headers:d(e?.headers,t,!0),params:d(e?.params,t),query:d(e?.query,t),response:d(e?.response,t)},this}handle=async e=>this.innerHandle(e);innerHandle=e=>{let t=this.decorators;if(t.request=e,t.set={headers:{},status:200},this.event.request.length)try{for(let e=0;e<this.event.request.length;e++){let r=a(this.event.request[e](t),t.set);if(r)return r}}catch(r){return this.handleError(e,r,t.set)}let s=c.exec(e.url);s[2]?t.query=r(s[2]):t.query={};let i=this._s.get(e.method+s[1]);if(i)return t.params={},i(t);{let r=this.router._m(e.method,s[1])??this.router._m("ALL",s[1]);return r?(t.params=r.params,r.store(t)):this.handleError(e,Error("NOT_FOUND"),t.set)}};handleError=async(e,t,r={headers:{}})=>{for(let a=0;a<this.event.error.length;a++){let i=this.event.error[a]({request:e,code:f(t.message),error:t,set:r});if(i instanceof Promise&&(i=await i),null!=i)return s(i,r)}return new Response("string"==typeof t.cause?t.cause:t.message,{headers:r.headers,status:v(f(t.message))})};listen=(e,t)=>{if(!Bun)throw Error("Bun to run");if("string"==typeof e&&Number.isNaN(e=+e))throw Error("Port must be a numeric value");let r=this.innerHandle,s="object"==typeof e?{...this.config.serve,...e,fetch:r}:{...this.config.serve,port:e,fetch:r},a=`$$Elysia:${s.port}`;globalThis[a]?(this.server=globalThis[a],this.server.reload(s)):globalThis[a]=this.server=Bun.serve(s);for(let e=0;e<this.event.start.length;e++)this.event.start[e](this);return t&&t(this.server),Promise.all(this.lazyLoadModules).then(()=>{this.server.pendingRequests||Bun.gc(!0)}),this};stop=async()=>{if(!this.server)throw Error("Elysia isn't running. Call `app.listen` to start the server.");this.server.stop();for(let e=0;e<this.event.stop.length;e++)await this.event.stop[e](this)};get modules(){return Promise.all(this.lazyLoadModules)}setModel(e){return Object.entries(e).forEach(([e,t])=>{e in this.meta[n]||(this.meta[n][e]=t)}),this}}export{t}from"./custom-types";export{ws}from"./ws";export{SCHEMA,DEFS,EXPOSED,createValidationError,getSchemaValidator,mergeDeep,mergeHook,mergeObjectArray,mapPathnameAndQueryRegEx}from"./utils";export{ElysiaError,ValidationError}from"./validation";export{b as Elysia};
|
package/dist/ws/types.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type { TypeCheck } from '@sinclair/typebox/compiler';
|
|
|
4
4
|
import type { ElysiaWS } from '.';
|
|
5
5
|
import type { Context } from '../context';
|
|
6
6
|
import type { DEFS } from '../utils';
|
|
7
|
-
import type { ElysiaInstance, UnwrapSchema, TypedSchema, ExtractPath, WithArray, NoReturnHandler, HookHandler } from '../types';
|
|
7
|
+
import type { ElysiaInstance, UnwrapSchema, TypedSchema, ExtractPath, WithArray, NoReturnHandler, HookHandler, BodyParser } from '../types';
|
|
8
8
|
export type WSTypedSchema<ModelName extends string = string> = Omit<TypedSchema<ModelName>, 'response'> & {
|
|
9
9
|
response?: TypedSchema<ModelName>['body'];
|
|
10
10
|
};
|
|
@@ -40,6 +40,7 @@ export type WebSocketHeaderHandler<Schema extends WSTypedSchema = WSTypedSchema,
|
|
|
40
40
|
type PartialWebSocketHandler = Omit<Partial<WebSocketHandler<Context>>, 'open' | 'message' | 'close' | 'drain' | 'publish' | 'publishToSelf'>;
|
|
41
41
|
export type ElysiaWSOptions<Path extends string = '', Schema extends WSTypedSchema = {}, Definitions extends ElysiaInstance['meta'][typeof DEFS] = {}> = PartialWebSocketHandler & ElysiaWS<ElysiaWSContext<Schema, Path>, Schema, Definitions> extends infer WS ? {
|
|
42
42
|
schema?: Schema;
|
|
43
|
+
parse?: WithArray<BodyParser[]>;
|
|
43
44
|
beforeHandle?: WithArray<HookHandler<Schema>>;
|
|
44
45
|
transform?: WithArray<NoReturnHandler<TypedWSSchemaToRoute<Schema>>>;
|
|
45
46
|
transformMessage?: WithArray<TransformMessageHandler<Schema['body']>>;
|
package/package.json
CHANGED
package/src/index.ts
CHANGED
|
@@ -608,7 +608,14 @@ export default class Elysia<Instance extends ElysiaInstance = ElysiaInstance> {
|
|
|
608
608
|
method,
|
|
609
609
|
path,
|
|
610
610
|
handler,
|
|
611
|
-
mergeHook(hook as LocalHook<any>,
|
|
611
|
+
mergeHook(hook as LocalHook<any>, {
|
|
612
|
+
...localHook,
|
|
613
|
+
error: !localHook.error
|
|
614
|
+
? sandbox.event.error
|
|
615
|
+
: Array.isArray(localHook.error)
|
|
616
|
+
? [...localHook.error, ...sandbox.event.error]
|
|
617
|
+
: [localHook.error, ...sandbox.event.error]
|
|
618
|
+
})
|
|
612
619
|
)
|
|
613
620
|
}
|
|
614
621
|
)
|
|
@@ -1851,6 +1858,7 @@ export default class Elysia<Instance extends ElysiaInstance = ElysiaInstance> {
|
|
|
1851
1858
|
return 'Expected a websocket connection'
|
|
1852
1859
|
},
|
|
1853
1860
|
{
|
|
1861
|
+
parse: options.parse,
|
|
1854
1862
|
beforeHandle: options.beforeHandle,
|
|
1855
1863
|
transform: options.transform,
|
|
1856
1864
|
schema: {
|
package/src/ws/types.ts
CHANGED
|
@@ -11,7 +11,8 @@ import type {
|
|
|
11
11
|
ExtractPath,
|
|
12
12
|
WithArray,
|
|
13
13
|
NoReturnHandler,
|
|
14
|
-
HookHandler
|
|
14
|
+
HookHandler,
|
|
15
|
+
BodyParser
|
|
15
16
|
} from '../types'
|
|
16
17
|
|
|
17
18
|
export type WSTypedSchema<ModelName extends string = string> = Omit<
|
|
@@ -144,6 +145,7 @@ export type ElysiaWSOptions<
|
|
|
144
145
|
> extends infer WS
|
|
145
146
|
? {
|
|
146
147
|
schema?: Schema
|
|
148
|
+
parse?: WithArray<BodyParser[]>
|
|
147
149
|
beforeHandle?: WithArray<HookHandler<Schema>>
|
|
148
150
|
transform?: WithArray<NoReturnHandler<TypedWSSchemaToRoute<Schema>>>
|
|
149
151
|
transformMessage?: WithArray<
|