Socket
Socket
Sign inDemoInstall

elysia

Package Overview
Dependencies
Maintainers
1
Versions
410
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

elysia - npm Package Compare versions

Comparing version 0.5.0 to 0.5.1

9

dist/cjs/compose.js

@@ -87,3 +87,3 @@ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),function(e,r){for(var t in r)Object.defineProperty(e,t,{enumerable:!0,get:r[t]})}(exports,{hasReturn:function(){return i},isFnUse:function(){return l},findElysiaMeta:function(){return u},composeHandler:function(){return d},composeGeneralHandler:function(){return f},composeErrorHandler:function(){return p}});const e=require("fast-querystring"),r=require("./handler"),t=require("./utils"),n=require("./error"),o="AsyncFunction",s=e=>e.constructor.name===o,a=new Headers,c=RegExp(" (\\w+) = context","g"),i=e=>{let r=e.indexOf(")");return 61===e.charCodeAt(r+2)&&123!==e.charCodeAt(r+5)||e.includes("return")},l=(e,r)=>{let t=r.slice(r.indexOf("(")+1,r.indexOf(")"));if(""===t)return!1;if(123===t.charCodeAt(0))return!!(t.includes(`{ ${e}`)||t.includes(`, ${e}`));if(r.match(RegExp(`${t}(.${e}|\\["${e}"\\])`)))return!0;let n=[t];for(let e of r.matchAll(c))n.push(e[1]);let o=RegExp(`{.*?} = (${n.join("|")})`,"g");for(let[t]of r.matchAll(o))if(t.includes(`{ ${e}`)||t.includes(`, ${e}`))return!0;return!1},u=(e,r,t=[],n="")=>{if("object"===r.type){let o=r.properties;for(let r in o){let s=o[r],a=n?n+"."+r:r;if("object"===s.type){u(e,s,t,a);continue}if(s.anyOf){for(let r of s.anyOf)u(e,r,t,a);continue}s.elysiaMeta===e&&t.push(a)}return 0===t.length?null:t}return r?.elysiaMeta===e?(n&&t.push(n),"root"):null},d=({path:c,method:d,hooks:f,validator:p,handler:y,handleError:h,meta:m})=>{let $="try {\n",b="string"==typeof f.type,E=p||"GET"!==d?[y,...f.transform,...f.beforeHandle,...f.afterHandle].map(e=>e.toString()):[],w="GET"!==d&&(p.body||b||E.some(e=>l("body",e))),q=p.headers||E.some(e=>l("headers",e));q&&($+=a.toJSON?`c.headers = c.request.headers.toJSON()

}
`}$+="\n"}if(p.params){let e=u("Numeric",p.params.schema);if(e){if("object"==typeof e)for(let r of e)$+=`c.params.${r} = +c.params.${r}`;$+="\n"}}if(p.query){let e=u("Numeric",p.query.schema);if(e){if("object"==typeof e)for(let r of e)$+=`c.query.${r} = +c.query.${r}`;$+="\n"}}if(p.headers){let e=u("Numeric",p.headers.schema);if(e){if("object"==typeof e)for(let r of e)$+=`c.headers.${r} = +c.headers.${r}`;$+="\n"}}if(p.body){let e=u("Numeric",p.body.schema);if(e){switch(typeof e){case"string":$+="c.body = +c.body";break;case"object":for(let r of e)$+=`c.body.${r} = +c.body.${r}`}$+="\n"}}if(f?.transform)for(let e=0;e<f.transform.length;e++){let r=f.transform[e];"derive"===r.$elysia?$+=f.transform[e].constructor.name===o?`Object.assign(c, await transform[${e}](c));`:`Object.assign(c, transform[${e}](c));`:$+=f.transform[e].constructor.name===o?`await transform[${e}](c);`:`transform[${e}](c);`}if(p&&(p.headers&&($+=`
`}$+="\n"}if(p.params){let e=u("Numeric",p.params.schema);if(e){if("object"==typeof e)for(let r of e)$+=`c.params.${r} = +c.params.${r};`;$+="\n"}}if(p.query){let e=u("Numeric",p.query.schema);if(e){if("object"==typeof e)for(let r of e)$+=`c.query.${r} = +c.query.${r};`;$+="\n"}}if(p.headers){let e=u("Numeric",p.headers.schema);if(e){if("object"==typeof e)for(let r of e)$+=`c.headers.${r} = +c.headers.${r};`;$+="\n"}}if(p.body){let e=u("Numeric",p.body.schema);if(e){switch(typeof e){case"string":$+="c.body = +c.body;";break;case"object":for(let r of e)$+=`c.body.${r} = +c.body.${r};`}$+="\n"}}if(f?.transform)for(let e=0;e<f.transform.length;e++){let r=f.transform[e];"derive"===r.$elysia?$+=f.transform[e].constructor.name===o?`Object.assign(c, await transform[${e}](c));`:`Object.assign(c, transform[${e}](c));`:$+=f.transform[e].constructor.name===o?`await transform[${e}](c);`:`transform[${e}](c);`}if(p&&(p.headers&&($+=`
if (headers.Check(c.headers) === false) {

@@ -199,5 +199,6 @@ throw new ValidationError(

${$}
}`;let x=Function("hooks",$);return x({handler:y,hooks:f,validator:p,handleError:h,utils:{mapResponse:r.mapResponse,mapEarlyResponse:r.mapEarlyResponse,parseQuery:e.parse},error:{ParseError:n.ParseError,NotFoundError:n.NotFoundError,ValidationError:n.ValidationError,InternalServerError:n.InternalServerError},meta:m,SCHEMA:m?t.SCHEMA:void 0,DEFS:m?t.DEFS:void 0})},f=e=>{let t="";for(let r of Object.keys(e.decorators))t+=`,${r}: app.decorators.${r}`;let o=e.staticRouter,s="";for(let[e,r]of Object.entries(o.map))s+=`case '${e}':
}`;let x=Function("hooks",$);return x({handler:y,hooks:f,validator:p,handleError:h,utils:{mapResponse:r.mapResponse,mapEarlyResponse:r.mapEarlyResponse,parseQuery:e.parse},error:{ParseError:n.ParseError,NotFoundError:n.NotFoundError,ValidationError:n.ValidationError,InternalServerError:n.InternalServerError},meta:m,SCHEMA:m?t.SCHEMA:void 0,DEFS:m?t.DEFS:void 0})},f=e=>{let t="";for(let r of Object.keys(e.decorators))t+=`,${r}: app.decorators.${r}`;let o=e.staticRouter,s="";for(let[e,{code:r,all:t}]of Object.entries(o.map))s+=`case '${e}':
switch(method) {
${r}}
${r}
${t}}

@@ -245,3 +246,3 @@ `;let a=`const {

switch(path) {
map: switch(path) {
${s}

@@ -248,0 +249,0 @@ }

@@ -1,5 +0,4 @@

function e(t){if("function"!=typeof WeakMap)return null;var r=new WeakMap,s=new WeakMap;return(e=function(e){return e?s:r})(t)}"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(exports,{default:function(){return h},Elysia:function(){return h},t:function(){return i.t},ws:function(){return a.ws},SCHEMA:function(){return r.SCHEMA},DEFS:function(){return r.DEFS},EXPOSED:function(){return r.EXPOSED},getSchemaValidator:function(){return r.getSchemaValidator},mergeDeep:function(){return r.mergeDeep},mergeHook:function(){return r.mergeHook},mergeObjectArray:function(){return r.mergeObjectArray},getResponseSchemaValidator:function(){return r.getResponseSchemaValidator},ParseError:function(){return n.ParseError},NotFoundError:function(){return n.NotFoundError},ValidationError:function(){return n.ValidationError},InternalServerError:function(){return n.InternalServerError}});const t=require("memoirist"),r=require("./utils"),s=require("./schema"),o=require("./compose"),a=require("./ws"),i=require("./custom-types"),n=require("./error");class h{config;store={};meta={[r.SCHEMA]:Object.create(null),[r.DEFS]:Object.create(null),[r.EXPOSED]:Object.create(null)};decorators={};event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],error:[],stop:[]};server=null;$schema=null;router=new t.Memoirist;routes=[];staticRouter={handlers:[],variables:"",map:{}};wsRouter;lazyLoadModules=[];constructor(e){this.config={fn:"/~fn",...e}}_addHandler(e,t,a,i,{allowMeta:n=!1}={allowMeta:!1}){t=""===t?t:47===t.charCodeAt(0)?t:`/${t}`,this.routes.push({method:e,path:t,handler:a,hooks:(0,r.mergeHook)({...this.event},i)});let h=this.meta[r.DEFS];if(i?.type)switch(i.type){case"text":i.type="text/plain";break;case"json":i.type="application/json";break;case"formdata":i.type="multipart/form-data";break;case"urlencoded":i.type="application/x-www-form-urlencoded"}(0,s.registerSchemaPath)({schema:this.meta[r.SCHEMA],contentType:i?.type,hook:i,method:e,path:t,models:this.meta[r.DEFS]});let u={body:(0,r.getSchemaValidator)(i?.body??this.$schema?.body,h),headers:(0,r.getSchemaValidator)(i?.headers??this.$schema?.headers,h,!0),params:(0,r.getSchemaValidator)(i?.params??this.$schema?.params,h),query:(0,r.getSchemaValidator)(i?.query??this.$schema?.query,h),response:(0,r.getResponseSchemaValidator)(i?.response??this.$schema?.response,h)},d=(0,r.mergeHook)(this.event,i),l=(0,o.composeHandler)({path:t,method:e,hooks:d,validator:u,handler:a,handleError:this.handleError,meta:n?this.meta:void 0});if(-1===t.indexOf(":")&&-1===t.indexOf("*")){let r=this.staticRouter.handlers.length;this.staticRouter.handlers.push(l),this.staticRouter.variables+=`const st${r} = staticRouter.handlers[${r}]
`,this.staticRouter.map[t]||(this.staticRouter.map[t]=""),this.staticRouter.map[t]+="ALL"===e?`default:
`:`case '${e}':
`,this.staticRouter.map[t]+=`return st${r}(ctx)
`}else this.router.add(e,t,l)}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,s){let o=new h;o.store=this.store,this.wsRouter&&o.use((0,a.ws)());let i="object"==typeof t,n=(i?s:t)(o);return this.decorators=(0,r.mergeDeep)(this.decorators,o.decorators),n.event.request.length&&(this.event.request=[...this.event.request,...n.event.request]),this.model(n.meta[r.DEFS]),Object.values(o.routes).forEach(({method:s,path:a,handler:h,hooks:u})=>{if(i){let i=`${e}${a}`,d=o.wsRouter?.find("subscribe",i);if(d){let e=o.wsRouter.history.find(([e,t])=>i===t);if(!e)return;return this.ws(i,e[2])}this._addHandler(s,i,h,(0,r.mergeHook)(t,{...u,error:u.error?Array.isArray(u.error)?[...u.error,...n.event.error]:[u.error,...n.event.error]:n.event.error}))}else{let t=`${e}${a}`,i=o.wsRouter?.find("subscribe",t);if(i){let e=o.wsRouter.history.find(([e,t])=>a===t);if(!e)return;return this.ws(t,e[2])}this._addHandler(s,t,h,(0,r.mergeHook)(u,{error:n.event.error}))}}),o.wsRouter&&this.wsRouter&&o.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 s=new h;s.store=this.store,this.wsRouter&&s.use((0,a.ws)());let o=t(s);return this.decorators=(0,r.mergeDeep)(this.decorators,s.decorators),o.event.request.length&&(this.event.request=[...this.event.request,...o.event.request]),this.model(o.meta[r.DEFS]),Object.values(s.routes).forEach(({method:t,path:a,handler:i,hooks:n})=>{let h=s.wsRouter?.find("subscribe",a);if(h){let e=s.wsRouter.history.find(([e,t])=>a===t);if(!e)return;return this.ws(a,e[2])}this._addHandler(t,a,i,(0,r.mergeHook)(e,{...n,error:n.error?Array.isArray(n.error)?[...n.error,...o.event.error]:[n.error,...o.event.error]:o.event.error}))}),s.wsRouter&&this.wsRouter&&s.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)).then(e=>e.compile())),this;let t=e(this);return t instanceof Promise?(this.lazyLoadModules.push(t.then(e=>e.compile())),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(e,t){if(!this.wsRouter)throw Error("Can't find WebSocket. Please register WebSocket plugin first by importing 'elysia/ws'");return this.wsRouter.add("subscribe",e,t),this.get(e,e=>{if(!this.server?.upgrade(e.request,{headers:"function"==typeof t.upgrade?t.upgrade(e):t.upgrade,data:{...e,id:Date.now(),message:(0,r.getSchemaValidator)(t?.body,this.meta[r.DEFS]),transformMessage:t.transform?Array.isArray(t.transformMessage)?t.transformMessage:[t.transformMessage]:[]}}))return e.set.status=400,"Expected a websocket connection"},{beforeHandle:t.beforeHandle,transform:t.transform,headers:t?.headers,params:t?.params,query:t?.query}),this}route(e,t,r,{config:s,...o}={config:{allowMeta:!1}}){return this._addHandler(e,t,r,o,s),this}state(e,t){return"object"==typeof e?(this.store=(0,r.mergeDeep)(this.store,e),this):(e in this.store||(this.store[e]=t),this)}decorate(e,t){return"object"==typeof e?(this.decorators=(0,r.mergeDeep)(this.decorators,e),this):(e in this.decorators||(this.decorators[e]=t),this)}derive(e){return e.$elysia="derive",this.onTransform(e)}fn(t){return this.use(async r=>{let{fn:s}=await Promise.resolve().then(()=>(function(t,r){if(!r&&t&&t.__esModule)return t;if(null===t||"object"!=typeof t&&"function"!=typeof t)return{default:t};var s=e(r);if(s&&s.has(t))return s.get(t);var o={},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var i in t)if("default"!==i&&Object.prototype.hasOwnProperty.call(t,i)){var n=a?Object.getOwnPropertyDescriptor(t,i):null;n&&(n.get||n.set)?Object.defineProperty(o,i,n):o[i]=t[i]}return o.default=t,s&&s.set(t,o),o})(require("@elysiajs/fn")));return s({app:r,value:t,path:r.config.fn})})}schema(e){let t=this.meta[r.DEFS];return this.$schema={body:(0,r.getSchemaValidator)(e.body,t),headers:(0,r.getSchemaValidator)(e?.headers,t,!0),params:(0,r.getSchemaValidator)(e?.params,t),query:(0,r.getSchemaValidator)(e?.query,t),response:(0,r.getSchemaValidator)(e?.response,t)},this}compile(){return this.fetch=(0,o.composeGeneralHandler)(this),this.server&&this.server.reload({...this.server,fetch:this.fetch}),this}handle=async e=>this.fetch(e);fetch=e=>(this.fetch=(0,o.composeGeneralHandler)(this))(e);handleError=async(e,t,r)=>(this.handleError=(0,o.composeErrorHandler)(this))(e,t,r);listen=(e,t)=>{if(!Bun)throw Error("Bun to run");if(this.compile(),"string"==typeof e&&Number.isNaN(e=+e))throw Error("Port must be a numeric value");let r=this.fetch,s=(process.env.ENV??process.env.NODE_ENV)!=="production",o="object"==typeof e?{...this.config.serve,...e,development:s,fetch:r}:{...this.config.serve,port:e,fetch:r};if("production"!==process.env.ENV){let e=`$$Elysia:${o.port}`;globalThis[e]?(this.server=globalThis[e],this.server.reload(o)):globalThis[e]=this.server=Bun.serve(o)}else this.server=Bun.serve(o);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(()=>{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)}model(e,t){return"object"==typeof e?Object.entries(e).forEach(([e,t])=>{e in this.meta[r.DEFS]||(this.meta[r.DEFS][e]=t)}):this.meta[r.DEFS][e]=t,this}}
function e(t){if("function"!=typeof WeakMap)return null;var r=new WeakMap,s=new WeakMap;return(e=function(e){return e?s:r})(t)}"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(exports,{default:function(){return h},Elysia:function(){return h},t:function(){return i.t},ws:function(){return o.ws},SCHEMA:function(){return r.SCHEMA},DEFS:function(){return r.DEFS},EXPOSED:function(){return r.EXPOSED},getSchemaValidator:function(){return r.getSchemaValidator},mergeDeep:function(){return r.mergeDeep},mergeHook:function(){return r.mergeHook},mergeObjectArray:function(){return r.mergeObjectArray},getResponseSchemaValidator:function(){return r.getResponseSchemaValidator},ParseError:function(){return n.ParseError},NotFoundError:function(){return n.NotFoundError},ValidationError:function(){return n.ValidationError},InternalServerError:function(){return n.InternalServerError}});const t=require("memoirist"),r=require("./utils"),s=require("./schema"),a=require("./compose"),o=require("./ws"),i=require("./custom-types"),n=require("./error");class h{config;store={};meta={[r.SCHEMA]:Object.create(null),[r.DEFS]:Object.create(null),[r.EXPOSED]:Object.create(null)};decorators={};event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],error:[],stop:[]};server=null;$schema=null;router=new t.Memoirist;routes=[];staticRouter={handlers:[],variables:"",map:{},all:""};wsRouter;lazyLoadModules=[];constructor(e){this.config={fn:"/~fn",...e}}_addHandler(e,t,o,i,{allowMeta:n=!1}={allowMeta:!1}){t=""===t?t:47===t.charCodeAt(0)?t:`/${t}`,this.routes.push({method:e,path:t,handler:o,hooks:(0,r.mergeHook)({...this.event},i)});let h=this.meta[r.DEFS];if(i?.type)switch(i.type){case"text":i.type="text/plain";break;case"json":i.type="application/json";break;case"formdata":i.type="multipart/form-data";break;case"urlencoded":i.type="application/x-www-form-urlencoded"}(0,s.registerSchemaPath)({schema:this.meta[r.SCHEMA],contentType:i?.type,hook:i,method:e,path:t,models:this.meta[r.DEFS]});let u={body:(0,r.getSchemaValidator)(i?.body??this.$schema?.body,h),headers:(0,r.getSchemaValidator)(i?.headers??this.$schema?.headers,h,!0),params:(0,r.getSchemaValidator)(i?.params??this.$schema?.params,h),query:(0,r.getSchemaValidator)(i?.query??this.$schema?.query,h),response:(0,r.getResponseSchemaValidator)(i?.response??this.$schema?.response,h)},l=(0,r.mergeHook)(this.event,i),d=(0,a.composeHandler)({path:t,method:e,hooks:l,validator:u,handler:o,handleError:this.handleError,meta:n?this.meta:void 0});if(-1===t.indexOf(":")&&-1===t.indexOf("*")){let r=this.staticRouter.handlers.length;this.staticRouter.handlers.push(d),this.staticRouter.variables+=`const st${r} = staticRouter.handlers[${r}]
`,this.staticRouter.map[t]||(this.staticRouter.map[t]={code:"",all:"default: break map\n"}),"ALL"===e?this.staticRouter.map[t].all=`default: return st${r}(ctx)
`:this.staticRouter.map[t].code+=`case '${e}': return st${r}(ctx)
`}else this.router.add(e,t,d)}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,s){let a=new h;a.store=this.store,this.wsRouter&&a.use((0,o.ws)());let i="object"==typeof t,n=(i?s:t)(a);return this.decorators=(0,r.mergeDeep)(this.decorators,a.decorators),n.event.request.length&&(this.event.request=[...this.event.request,...n.event.request]),this.model(n.meta[r.DEFS]),Object.values(a.routes).forEach(({method:s,path:o,handler:h,hooks:u})=>{if(i){let i=`${e}${o}`,l=a.wsRouter?.find("subscribe",i);if(l){let e=a.wsRouter.history.find(([e,t])=>i===t);if(!e)return;return this.ws(i,e[2])}this._addHandler(s,i,h,(0,r.mergeHook)(t,{...u,error:u.error?Array.isArray(u.error)?[...u.error,...n.event.error]:[u.error,...n.event.error]:n.event.error}))}else{let t=`${e}${o}`,i=a.wsRouter?.find("subscribe",t);if(i){let e=a.wsRouter.history.find(([e,t])=>o===t);if(!e)return;return this.ws(t,e[2])}this._addHandler(s,t,h,(0,r.mergeHook)(u,{error:n.event.error}))}}),a.wsRouter&&this.wsRouter&&a.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 s=new h;s.store=this.store,this.wsRouter&&s.use((0,o.ws)());let a=t(s);return this.decorators=(0,r.mergeDeep)(this.decorators,s.decorators),a.event.request.length&&(this.event.request=[...this.event.request,...a.event.request]),this.model(a.meta[r.DEFS]),Object.values(s.routes).forEach(({method:t,path:o,handler:i,hooks:n})=>{let h=s.wsRouter?.find("subscribe",o);if(h){let e=s.wsRouter.history.find(([e,t])=>o===t);if(!e)return;return this.ws(o,e[2])}this._addHandler(t,o,i,(0,r.mergeHook)(e,{...n,error:n.error?Array.isArray(n.error)?[...n.error,...a.event.error]:[n.error,...a.event.error]:a.event.error}))}),s.wsRouter&&this.wsRouter&&s.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)).then(e=>e.compile())),this;let t=e(this);return t instanceof Promise?(this.lazyLoadModules.push(t.then(e=>e.compile())),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(e,t){if(!this.wsRouter)throw Error("Can't find WebSocket. Please register WebSocket plugin first by importing 'elysia/ws'");return this.wsRouter.add("subscribe",e,t),this.get(e,e=>{if(!this.server?.upgrade(e.request,{headers:"function"==typeof t.upgrade?t.upgrade(e):t.upgrade,data:{...e,id:Date.now(),message:(0,r.getSchemaValidator)(t?.body,this.meta[r.DEFS]),transformMessage:t.transform?Array.isArray(t.transformMessage)?t.transformMessage:[t.transformMessage]:[]}}))return e.set.status=400,"Expected a websocket connection"},{beforeHandle:t.beforeHandle,transform:t.transform,headers:t?.headers,params:t?.params,query:t?.query}),this}route(e,t,r,{config:s,...a}={config:{allowMeta:!1}}){return this._addHandler(e,t,r,a,s),this}state(e,t){return"object"==typeof e?(this.store=(0,r.mergeDeep)(this.store,e),this):(e in this.store||(this.store[e]=t),this)}decorate(e,t){return"object"==typeof e?(this.decorators=(0,r.mergeDeep)(this.decorators,e),this):(e in this.decorators||(this.decorators[e]=t),this)}derive(e){return e.$elysia="derive",this.onTransform(e)}fn(t){return this.use(async r=>{let{fn:s}=await Promise.resolve().then(()=>(function(t,r){if(!r&&t&&t.__esModule)return t;if(null===t||"object"!=typeof t&&"function"!=typeof t)return{default:t};var s=e(r);if(s&&s.has(t))return s.get(t);var a={},o=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var i in t)if("default"!==i&&Object.prototype.hasOwnProperty.call(t,i)){var n=o?Object.getOwnPropertyDescriptor(t,i):null;n&&(n.get||n.set)?Object.defineProperty(a,i,n):a[i]=t[i]}return a.default=t,s&&s.set(t,a),a})(require("@elysiajs/fn")));return s({app:r,value:t,path:r.config.fn})})}schema(e){let t=this.meta[r.DEFS];return this.$schema={body:(0,r.getSchemaValidator)(e.body,t),headers:(0,r.getSchemaValidator)(e?.headers,t,!0),params:(0,r.getSchemaValidator)(e?.params,t),query:(0,r.getSchemaValidator)(e?.query,t),response:(0,r.getSchemaValidator)(e?.response,t)},this}compile(){return this.fetch=(0,a.composeGeneralHandler)(this),this.server&&this.server.reload({...this.server,fetch:this.fetch}),this}handle=async e=>this.fetch(e);fetch=e=>(this.fetch=(0,a.composeGeneralHandler)(this))(e);handleError=async(e,t,r)=>(this.handleError=(0,a.composeErrorHandler)(this))(e,t,r);listen=(e,t)=>{if(!Bun)throw Error("Bun to run");if(this.compile(),"string"==typeof e&&Number.isNaN(e=+e))throw Error("Port must be a numeric value");let r=this.fetch,s=(process.env.ENV??process.env.NODE_ENV)!=="production",a="object"==typeof e?{...this.config.serve,...e,development:s,fetch:r}:{...this.config.serve,port:e,fetch:r};if("production"!==process.env.ENV){let e=`$$Elysia:${a.port}`;globalThis[e]?(this.server=globalThis[e],this.server.reload(a)):globalThis[e]=this.server=Bun.serve(a)}else this.server=Bun.serve(a);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(()=>{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)}model(e,t){return"object"==typeof e?Object.entries(e).forEach(([e,t])=>{e in this.meta[r.DEFS]||(this.meta[r.DEFS][e]=t)}):this.meta[r.DEFS][e]=t,this}}

@@ -87,3 +87,3 @@ import{parse as e}from"fast-querystring";import{mapEarlyResponse as r,mapResponse as t}from"./handler";import{SCHEMA as n,DEFS as s}from"./utils";import{ParseError as o,NotFoundError as a,ValidationError as c,InternalServerError as i}from"./error";let l="AsyncFunction",f=e=>e.constructor.name===l,d=new Headers,u=RegExp(" (\\w+) = context","g");export const hasReturn=e=>{let r=e.indexOf(")");return 61===e.charCodeAt(r+2)&&123!==e.charCodeAt(r+5)||e.includes("return")};export const isFnUse=(e,r)=>{let t=r.slice(r.indexOf("(")+1,r.indexOf(")"));if(""===t)return!1;if(123===t.charCodeAt(0))return!!(t.includes(`{ ${e}`)||t.includes(`, ${e}`));if(r.match(RegExp(`${t}(.${e}|\\["${e}"\\])`)))return!0;let n=[t];for(let e of r.matchAll(u))n.push(e[1]);let s=RegExp(`{.*?} = (${n.join("|")})`,"g");for(let[t]of r.matchAll(s))if(t.includes(`{ ${e}`)||t.includes(`, ${e}`))return!0;return!1};export const findElysiaMeta=(e,r,t=[],n="")=>{if("object"===r.type){let s=r.properties;for(let r in s){let o=s[r],a=n?n+"."+r:r;if("object"===o.type){findElysiaMeta(e,o,t,a);continue}if(o.anyOf){for(let r of o.anyOf)findElysiaMeta(e,r,t,a);continue}o.elysiaMeta===e&&t.push(a)}return 0===t.length?null:t}return r?.elysiaMeta===e?(n&&t.push(n),"root"):null};export const composeHandler=({path:u,method:p,hooks:y,validator:h,handler:m,handleError:$,meta:b})=>{let E="try {\n",w="string"==typeof y.type,q=h||"GET"!==p?[m,...y.transform,...y.beforeHandle,...y.afterHandle].map(e=>e.toString()):[],g="GET"!==p&&(h.body||w||q.some(e=>isFnUse("body",e))),x=h.headers||q.some(e=>isFnUse("headers",e));x&&(E+=d.toJSON?`c.headers = c.request.headers.toJSON()

}
`}E+="\n"}if(h.params){let e=findElysiaMeta("Numeric",h.params.schema);if(e){if("object"==typeof e)for(let r of e)E+=`c.params.${r} = +c.params.${r}`;E+="\n"}}if(h.query){let e=findElysiaMeta("Numeric",h.query.schema);if(e){if("object"==typeof e)for(let r of e)E+=`c.query.${r} = +c.query.${r}`;E+="\n"}}if(h.headers){let e=findElysiaMeta("Numeric",h.headers.schema);if(e){if("object"==typeof e)for(let r of e)E+=`c.headers.${r} = +c.headers.${r}`;E+="\n"}}if(h.body){let e=findElysiaMeta("Numeric",h.body.schema);if(e){switch(typeof e){case"string":E+="c.body = +c.body";break;case"object":for(let r of e)E+=`c.body.${r} = +c.body.${r}`}E+="\n"}}if(y?.transform)for(let e=0;e<y.transform.length;e++){let r=y.transform[e];"derive"===r.$elysia?E+=y.transform[e].constructor.name===l?`Object.assign(c, await transform[${e}](c));`:`Object.assign(c, transform[${e}](c));`:E+=y.transform[e].constructor.name===l?`await transform[${e}](c);`:`transform[${e}](c);`}if(h&&(h.headers&&(E+=`
`}E+="\n"}if(h.params){let e=findElysiaMeta("Numeric",h.params.schema);if(e){if("object"==typeof e)for(let r of e)E+=`c.params.${r} = +c.params.${r};`;E+="\n"}}if(h.query){let e=findElysiaMeta("Numeric",h.query.schema);if(e){if("object"==typeof e)for(let r of e)E+=`c.query.${r} = +c.query.${r};`;E+="\n"}}if(h.headers){let e=findElysiaMeta("Numeric",h.headers.schema);if(e){if("object"==typeof e)for(let r of e)E+=`c.headers.${r} = +c.headers.${r};`;E+="\n"}}if(h.body){let e=findElysiaMeta("Numeric",h.body.schema);if(e){switch(typeof e){case"string":E+="c.body = +c.body;";break;case"object":for(let r of e)E+=`c.body.${r} = +c.body.${r};`}E+="\n"}}if(y?.transform)for(let e=0;e<y.transform.length;e++){let r=y.transform[e];"derive"===r.$elysia?E+=y.transform[e].constructor.name===l?`Object.assign(c, await transform[${e}](c));`:`Object.assign(c, transform[${e}](c));`:E+=y.transform[e].constructor.name===l?`await transform[${e}](c);`:`transform[${e}](c);`}if(h&&(h.headers&&(E+=`
if (headers.Check(c.headers) === false) {

@@ -199,5 +199,6 @@ throw new ValidationError(

${E}
}`;let v=Function("hooks",E);return v({handler:m,hooks:y,validator:h,handleError:$,utils:{mapResponse:t,mapEarlyResponse:r,parseQuery:e},error:{ParseError:o,NotFoundError:a,ValidationError:c,InternalServerError:i},meta:b,SCHEMA:b?n:void 0,DEFS:b?s:void 0})};export const composeGeneralHandler=e=>{let t="";for(let r of Object.keys(e.decorators))t+=`,${r}: app.decorators.${r}`;let n=e.staticRouter,s="";for(let[e,r]of Object.entries(n.map))s+=`case '${e}':
}`;let v=Function("hooks",E);return v({handler:m,hooks:y,validator:h,handleError:$,utils:{mapResponse:t,mapEarlyResponse:r,parseQuery:e},error:{ParseError:o,NotFoundError:a,ValidationError:c,InternalServerError:i},meta:b,SCHEMA:b?n:void 0,DEFS:b?s:void 0})};export const composeGeneralHandler=e=>{let t="";for(let r of Object.keys(e.decorators))t+=`,${r}: app.decorators.${r}`;let n=e.staticRouter,s="";for(let[e,{code:r,all:t}]of Object.entries(n.map))s+=`case '${e}':
switch(method) {
${r}}
${r}
${t}}

@@ -245,3 +246,3 @@ `;let o=`const {

switch(path) {
map: switch(path) {
${s}

@@ -248,0 +249,0 @@ }

@@ -1,5 +0,4 @@

import{Memoirist as e}from"memoirist";import{SCHEMA as t,EXPOSED as r,DEFS as s,mergeHook as o,getSchemaValidator as a,getResponseSchemaValidator as i,mergeDeep as h}from"./utils";import{registerSchemaPath as n}from"./schema";import{composeErrorHandler as u,composeGeneralHandler as d,composeHandler as l}from"./compose";import{ws as c}from"./ws";export default class p{config;store={};meta={[t]:Object.create(null),[s]:Object.create(null),[r]:Object.create(null)};decorators={};event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],error:[],stop:[]};server=null;$schema=null;router=new e;routes=[];staticRouter={handlers:[],variables:"",map:{}};wsRouter;lazyLoadModules=[];constructor(e){this.config={fn:"/~fn",...e}}_addHandler(e,r,h,u,{allowMeta:d=!1}={allowMeta:!1}){r=""===r?r:47===r.charCodeAt(0)?r:`/${r}`,this.routes.push({method:e,path:r,handler:h,hooks:o({...this.event},u)});let c=this.meta[s];if(u?.type)switch(u.type){case"text":u.type="text/plain";break;case"json":u.type="application/json";break;case"formdata":u.type="multipart/form-data";break;case"urlencoded":u.type="application/x-www-form-urlencoded"}n({schema:this.meta[t],contentType:u?.type,hook:u,method:e,path:r,models:this.meta[s]});let p={body:a(u?.body??this.$schema?.body,c),headers:a(u?.headers??this.$schema?.headers,c,!0),params:a(u?.params??this.$schema?.params,c),query:a(u?.query??this.$schema?.query,c),response:i(u?.response??this.$schema?.response,c)},f=o(this.event,u),m=l({path:r,method:e,hooks:f,validator:p,handler:h,handleError:this.handleError,meta:d?this.meta:void 0});if(-1===r.indexOf(":")&&-1===r.indexOf("*")){let t=this.staticRouter.handlers.length;this.staticRouter.handlers.push(m),this.staticRouter.variables+=`const st${t} = staticRouter.handlers[${t}]
`,this.staticRouter.map[r]||(this.staticRouter.map[r]=""),this.staticRouter.map[r]+="ALL"===e?`default:
`:`case '${e}':
`,this.staticRouter.map[r]+=`return st${t}(ctx)
import{Memoirist as e}from"memoirist";import{SCHEMA as t,EXPOSED as r,DEFS as s,mergeHook as o,getSchemaValidator as a,getResponseSchemaValidator as i,mergeDeep as h}from"./utils";import{registerSchemaPath as n}from"./schema";import{composeErrorHandler as u,composeGeneralHandler as d,composeHandler as l}from"./compose";import{ws as c}from"./ws";export default class p{config;store={};meta={[t]:Object.create(null),[s]:Object.create(null),[r]:Object.create(null)};decorators={};event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],error:[],stop:[]};server=null;$schema=null;router=new e;routes=[];staticRouter={handlers:[],variables:"",map:{},all:""};wsRouter;lazyLoadModules=[];constructor(e){this.config={fn:"/~fn",...e}}_addHandler(e,r,h,u,{allowMeta:d=!1}={allowMeta:!1}){r=""===r?r:47===r.charCodeAt(0)?r:`/${r}`,this.routes.push({method:e,path:r,handler:h,hooks:o({...this.event},u)});let c=this.meta[s];if(u?.type)switch(u.type){case"text":u.type="text/plain";break;case"json":u.type="application/json";break;case"formdata":u.type="multipart/form-data";break;case"urlencoded":u.type="application/x-www-form-urlencoded"}n({schema:this.meta[t],contentType:u?.type,hook:u,method:e,path:r,models:this.meta[s]});let p={body:a(u?.body??this.$schema?.body,c),headers:a(u?.headers??this.$schema?.headers,c,!0),params:a(u?.params??this.$schema?.params,c),query:a(u?.query??this.$schema?.query,c),response:i(u?.response??this.$schema?.response,c)},f=o(this.event,u),m=l({path:r,method:e,hooks:f,validator:p,handler:h,handleError:this.handleError,meta:d?this.meta:void 0});if(-1===r.indexOf(":")&&-1===r.indexOf("*")){let t=this.staticRouter.handlers.length;this.staticRouter.handlers.push(m),this.staticRouter.variables+=`const st${t} = staticRouter.handlers[${t}]
`,this.staticRouter.map[r]||(this.staticRouter.map[r]={code:"",all:"default: break map\n"}),"ALL"===e?this.staticRouter.map[r].all=`default: return st${t}(ctx)
`:this.staticRouter.map[r].code+=`case '${e}': return st${t}(ctx)
`}else this.router.add(e,r,m)}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,r){let a=new p;a.store=this.store,this.wsRouter&&a.use(c());let i="object"==typeof t,n=(i?r:t)(a);return this.decorators=h(this.decorators,a.decorators),n.event.request.length&&(this.event.request=[...this.event.request,...n.event.request]),this.model(n.meta[s]),Object.values(a.routes).forEach(({method:r,path:s,handler:h,hooks:u})=>{if(i){let i=`${e}${s}`,d=a.wsRouter?.find("subscribe",i);if(d){let e=a.wsRouter.history.find(([e,t])=>i===t);if(!e)return;return this.ws(i,e[2])}this._addHandler(r,i,h,o(t,{...u,error:u.error?Array.isArray(u.error)?[...u.error,...n.event.error]:[u.error,...n.event.error]:n.event.error}))}else{let t=`${e}${s}`,i=a.wsRouter?.find("subscribe",t);if(i){let e=a.wsRouter.history.find(([e,t])=>s===t);if(!e)return;return this.ws(t,e[2])}this._addHandler(r,t,h,o(u,{error:n.event.error}))}}),a.wsRouter&&this.wsRouter&&a.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 p;r.store=this.store,this.wsRouter&&r.use(c());let a=t(r);return this.decorators=h(this.decorators,r.decorators),a.event.request.length&&(this.event.request=[...this.event.request,...a.event.request]),this.model(a.meta[s]),Object.values(r.routes).forEach(({method:t,path:s,handler:i,hooks:h})=>{let n=r.wsRouter?.find("subscribe",s);if(n){let e=r.wsRouter.history.find(([e,t])=>s===t);if(!e)return;return this.ws(s,e[2])}this._addHandler(t,s,i,o(e,{...h,error:h.error?Array.isArray(h.error)?[...h.error,...a.event.error]:[h.error,...a.event.error]:a.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)).then(e=>e.compile())),this;let t=e(this);return t instanceof Promise?(this.lazyLoadModules.push(t.then(e=>e.compile())),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(e,t){if(!this.wsRouter)throw Error("Can't find WebSocket. Please register WebSocket plugin first by importing 'elysia/ws'");return this.wsRouter.add("subscribe",e,t),this.get(e,e=>{if(!this.server?.upgrade(e.request,{headers:"function"==typeof t.upgrade?t.upgrade(e):t.upgrade,data:{...e,id:Date.now(),message:a(t?.body,this.meta[s]),transformMessage:t.transform?Array.isArray(t.transformMessage)?t.transformMessage:[t.transformMessage]:[]}}))return e.set.status=400,"Expected a websocket connection"},{beforeHandle:t.beforeHandle,transform:t.transform,headers:t?.headers,params:t?.params,query:t?.query}),this}route(e,t,r,{config:s,...o}={config:{allowMeta:!1}}){return this._addHandler(e,t,r,o,s),this}state(e,t){return"object"==typeof e?(this.store=h(this.store,e),this):(e in this.store||(this.store[e]=t),this)}decorate(e,t){return"object"==typeof e?(this.decorators=h(this.decorators,e),this):(e in this.decorators||(this.decorators[e]=t),this)}derive(e){return e.$elysia="derive",this.onTransform(e)}fn(e){return this.use(async t=>{let{fn:r}=await import("@elysiajs/fn");return r({app:t,value:e,path:t.config.fn})})}schema(e){let t=this.meta[s];return this.$schema={body:a(e.body,t),headers:a(e?.headers,t,!0),params:a(e?.params,t),query:a(e?.query,t),response:a(e?.response,t)},this}compile(){return this.fetch=d(this),this.server&&this.server.reload({...this.server,fetch:this.fetch}),this}handle=async e=>this.fetch(e);fetch=e=>(this.fetch=d(this))(e);handleError=async(e,t,r)=>(this.handleError=u(this))(e,t,r);listen=(e,t)=>{if(!Bun)throw Error("Bun to run");if(this.compile(),"string"==typeof e&&Number.isNaN(e=+e))throw Error("Port must be a numeric value");let r=this.fetch,s=(process.env.ENV??process.env.NODE_ENV)!=="production",o="object"==typeof e?{...this.config.serve,...e,development:s,fetch:r}:{...this.config.serve,port:e,fetch:r};if("production"!==process.env.ENV){let e=`$$Elysia:${o.port}`;globalThis[e]?(this.server=globalThis[e],this.server.reload(o)):globalThis[e]=this.server=Bun.serve(o)}else this.server=Bun.serve(o);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(()=>{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)}model(e,t){return"object"==typeof e?Object.entries(e).forEach(([e,t])=>{e in this.meta[s]||(this.meta[s][e]=t)}):this.meta[s][e]=t,this}}export{t}from"./custom-types";export{ws}from"./ws";export{SCHEMA,DEFS,EXPOSED,getSchemaValidator,mergeDeep,mergeHook,mergeObjectArray,getResponseSchemaValidator}from"./utils";export{ParseError,NotFoundError,ValidationError,InternalServerError}from"./error";export{p as Elysia};
{
"name": "elysia",
"description": "Fast, and friendly Bun web framework",
"version": "0.5.0",
"version": "0.5.1",
"author": {

@@ -6,0 +6,0 @@ "name": "saltyAom",

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc