Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

elysia

Package Overview
Dependencies
Maintainers
1
Versions
442
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.3.0-exp-240224.141 to 0.3.0-exp-240225.2119

dist/custom-types.d.ts

2

dist/fn.js

@@ -1,1 +0,1 @@

import{EXPOSED as e}from"./utils";import{serialize as n}from"superjson";export const permission=({value:n,allow:r,deny:i,check:t=!0})=>({[e]:!0,value:n,check:t,allow:r,deny:i});export const runFn=(r,i)=>{let t=[],o=r.body;e:for(let n=0;n<o.length;n++){let c=o[n],l=i,u=c.n;if(!Array.isArray(c.n)){t.push(Error("Invalid procedure"));continue e}let s=u[u.length-1];if(1===u.length){if(s in l&&e in l[s]){if(!1==l[s].check){t.push(Error("Forbidden"));continue e}if(!0!==l[s].check){try{let e=l[s].check({...r,key:s,params:c.p??null,match(e){}});if(e instanceof Error){t.push(e);continue e}}catch(e){t.push(e);continue e}l=l[s],s="value"}}}else for(let n=0;n<u.length-1;n++){if(!(l=l[u[n]])){t.push(Error("Invalid procedure"));continue e}if(e in l){let e=u.slice(n+1).join("."),i="function"==typeof l.check;if(!0===l.allow?.includes(e)&&!i){l=l.value;continue}if(!1!=l.check&&!0!==l.deny?.includes(e)&&(!1!==l.allow?.includes(e)||l.deny||i)){if(!0!==l.check)try{let n;let i=l.check({...r,key:e,params:c.p??null,match(e){n=e}});if(n)try{let r=(n[e]??n.default)?.(c.p??null);if(r instanceof Error)throw r}catch(r){if(!(e in n)&&l.allow?.includes(e)){l=l.value;continue}t.push(r);continue e}if(i instanceof Error){t.push(i);continue e}}catch(e){t.push(e);continue e}}else{t.push(Error("Forbidden"));continue e}l=l.value}}"function"!=typeof l[s]?t.push(Error("Invalid procedure")):void 0===c.p?t.push(l[s]()):1===c.p.length?t.push(l[s](c.p[0])):t.push(l[s](...c.p))}return Promise.all(t).then(n)};
import{EXPOSED as e}from"./utils";import{serialize as n}from"superjson";export const permission=({value:n,allow:r,deny:i,check:t=!0})=>({[e]:!0,value:n,check:t,allow:r,deny:i});export const runFn=(r,i)=>{let t=[],o=r.body;e:for(let n=0;n<o.length;n++){let c=o[n],l=i,u=c.n;if(!Array.isArray(c.n)){t.push(Error("Invalid procedure"));continue e}let s=u[u.length-1];if(1===u.length){if(s in l&&e in l[s]){if(!1==l[s].check){t.push(Error("Forbidden"));continue e}if(!0!==l[s].check){try{let e=l[s].check({...r,key:s,params:c.p??null,match(e){}});if(e instanceof Error){t.push(e);continue e}}catch(e){t.push(e);continue e}l=l[s],s="value"}}}else for(let n=0;n<u.length-1;n++){if(!(l=l[u[n]])){t.push(Error("Invalid procedure"));continue e}if(e in l){let e=u.slice(n+1).join("."),i="function"==typeof l.check;if(!0===l.allow?.includes(e)&&!i){l=l.value;continue}if(!1!=l.check&&!0!==l.deny?.includes(e)&&(!1!==l.allow?.includes(e)||l.deny||i)){if(!0!==l.check)try{let n;let i=l.check({...r,key:e,params:c.p??null,match(e){n=e}});if(n)try{let r=(n[e]??n.default)?.(c.p??null);if(r instanceof Error)throw r}catch(r){if(!(e in n)&&l.allow?.includes(e)){l=l.value;continue}t.push(r);continue e}if(i instanceof Error){t.push(i);continue e}}catch(e){t.push(e);continue e}}else{t.push(Error("Forbidden"));continue e}l=l.value}}try{"function"!=typeof l[s]?t.push(Error("Invalid procedure")):void 0===c.p?t.push(l[s]()):1===c.p.length?t.push(l[s](c.p[0])):t.push(l[s](...c.p))}catch(e){t.push(e)}}return Promise.all(t).then(n)};

@@ -1,1 +0,1 @@

export const isNotEmpty=e=>{for(let s in e)return!0;return!1};let e=(e,s)=>{if(Array.isArray(s)){e.delete("Set-Cookie");for(let r=0;r<s.length;r++){let t=s[r].indexOf("=");e.append("Set-Cookie",`${s[r].slice(0,t)}=${s[r].slice(t+1)}`)}}return e};export const mapEarlyResponse=(s,r)=>{if(r.headers?.["Set-Cookie"]&&(r.headers=e(new Headers(r.headers),r.headers["Set-Cookie"])),r.redirect)return Response.redirect(r.redirect,{headers:r.headers});if(isNotEmpty(r.headers)||200!==r.status)switch(typeof s){case"string":return new Response(s,{status:r.status,headers:r.headers});case"object":if(s instanceof Error)return errorToResponse(s,r.headers);if(s instanceof Response){for(let e in r.headers)s.headers.append(e,r.headers[e]);return s}if(s instanceof Blob)return new Response(s,{status:r.status,headers:r.headers});return r.headers["Content-Type"]||(r.headers["Content-Type"]="application/json"),new Response(JSON.stringify(s),{status:r.status,headers:r.headers});case"function":if(s instanceof Blob)return new Response(s,{status:r.status,headers:r.headers});for(let e in r.headers)s.headers.append(e,r.headers[e]);return s;case"number":case"boolean":return new Response(s.toString(),{status:r.status,headers:r.headers})}else switch(typeof s){case"string":return new Response(s);case"object":if(s instanceof Response)return s;if(s instanceof Error)return errorToResponse(s,r.headers);if(s instanceof Blob)return new Response(s);return new Response(JSON.stringify(s),{headers:{"content-type":"application/json"}});case"function":if(s instanceof Blob)return new Response(s);return s;case"number":case"boolean":return new Response(s.toString())}};export const mapResponse=(s,r)=>{if(r.headers?.["Set-Cookie"]){if(r.headers=e(new Headers(r.headers),r.headers["Set-Cookie"]),r.redirect)return Response.redirect(r.redirect,{headers:r.headers});switch(typeof s){case"string":return new Response(s,{status:r.status,headers:r.headers});case"object":switch(s.constructor){case Error:return errorToResponse(s,r.headers);case Response:for(let e in r.headers)s.headers.append(e,r.headers[e]);return s;case Blob:return new Response(s,{status:r.status,headers:r.headers});default:return r.headers["Content-Type"]||(r.headers["Content-Type"]="application/json"),new Response(JSON.stringify(s),{status:r.status,headers:r.headers})}case"function":if(s instanceof Blob)return new Response(s,{status:r.status,headers:r.headers});return s();case"number":case"boolean":return new Response(s.toString(),{status:r.status,headers:r.headers});case"undefined":return new Response("",{status:r.status,headers:r.headers});default:return new Response(s,{status:r.status,headers:r.headers})}}if(r.redirect)return Response.redirect(r.redirect,{headers:r.headers});if(Object.keys(r.headers).length||200!==r.status)switch(typeof s){case"string":return new Response(s,{status:r.status,headers:r.headers});case"object":switch(s?.constructor){case Error:return errorToResponse(s,r.headers);case Response:for(let e in r.headers)s.headers.append(e,r.headers[e]);return s;case Blob:return new Response(s,{status:r.status,headers:r.headers});default:return r.headers["Content-Type"]||(r.headers["Content-Type"]="application/json"),new Response(JSON.stringify(s),{status:r.status,headers:r.headers})}case"function":if(s instanceof Blob)return new Response(s,{status:r.status,headers:r.headers});return s();case"number":case"boolean":return new Response(s.toString(),{status:r.status,headers:r.headers});case"undefined":return new Response("",{status:r.status,headers:r.headers});default:return new Response(s,{status:r.status,headers:r.headers})}else switch(typeof s){case"string":default:return new Response(s);case"object":if(s instanceof Response)return s;if(s instanceof Error)return errorToResponse(s,r.headers);if(s instanceof Blob)return new Response(s);return new Response(JSON.stringify(s),{headers:{"content-type":"application/json"}});case"function":if(s instanceof Blob)return new Response(s);return s();case"number":case"boolean":return new Response(s.toString());case"undefined":return new Response("")}};export const errorToResponse=(e,s)=>new Response(JSON.stringify({name:e?.name,message:e?.message,cause:e?.cause}),{status:500,headers:s});
export const isNotEmpty=e=>{for(let s in e)return!0;return!1};let e=(e,s)=>{if(Array.isArray(s)){e.delete("Set-Cookie");for(let r=0;r<s.length;r++){let t=s[r].indexOf("=");e.append("Set-Cookie",`${s[r].slice(0,t)}=${s[r].slice(t+1)}`)}}return e};export const mapEarlyResponse=(s,r)=>{if(r.redirect&&(r.headers.Location=r.redirect,r.status=302),r.headers["Set-Cookie"]&&(r.headers=e(new Headers(r.headers),r.headers["Set-Cookie"])),isNotEmpty(r.headers)||200!==r.status)switch(typeof s){case"string":return new Response(s,{status:r.status,headers:r.headers});case"object":if(s instanceof Error)return errorToResponse(s,r.headers);if(s instanceof Response){for(let e in r.headers)s.headers.append(e,r.headers[e]);return s}if(s instanceof Blob)return new Response(s,{status:r.status,headers:r.headers});return r.headers["Content-Type"]||(r.headers["Content-Type"]="application/json"),new Response(JSON.stringify(s),{status:r.status,headers:r.headers});case"function":if(s instanceof Blob)return new Response(s,{status:r.status,headers:r.headers});for(let e in r.headers)s.headers.append(e,r.headers[e]);return s;case"number":case"boolean":return new Response(s.toString(),{status:r.status,headers:r.headers})}else switch(typeof s){case"string":return new Response(s);case"object":if(s instanceof Response)return s;if(s instanceof Error)return errorToResponse(s,r.headers);if(s instanceof Blob)return new Response(s);return new Response(JSON.stringify(s),{headers:{"content-type":"application/json"}});case"function":if(s instanceof Blob)return new Response(s);return s;case"number":case"boolean":return new Response(s.toString())}};export const mapResponse=(s,r)=>{if(r.redirect&&(r.headers.Location=r.redirect,r.status=302),r.headers?.["Set-Cookie"])switch(r.headers=e(new Headers(r.headers),r.headers["Set-Cookie"]),typeof s){case"string":return new Response(s,{status:r.status,headers:r.headers});case"object":switch(s.constructor){case Error:return errorToResponse(s,r.headers);case Response:for(let e in r.headers)s.headers.append(e,r.headers[e]);return s;case Blob:return new Response(s,{status:r.status,headers:r.headers});default:return r.headers["Content-Type"]||(r.headers["Content-Type"]="application/json"),new Response(JSON.stringify(s),{status:r.status,headers:r.headers})}case"function":if(s instanceof Blob)return new Response(s,{status:r.status,headers:r.headers});return s();case"number":case"boolean":return new Response(s.toString(),{status:r.status,headers:r.headers});case"undefined":return new Response("",{status:r.status,headers:r.headers});default:return new Response(s,{status:r.status,headers:r.headers})}if(r.redirect)return Response.redirect(r.redirect,{headers:r.headers});if(Object.keys(r.headers).length||200!==r.status)switch(typeof s){case"string":return new Response(s,{status:r.status,headers:r.headers});case"object":switch(s?.constructor){case Error:return errorToResponse(s,r.headers);case Response:for(let e in r.headers)s.headers.append(e,r.headers[e]);return s;case Blob:return new Response(s,{status:r.status,headers:r.headers});default:return r.headers["Content-Type"]||(r.headers["Content-Type"]="application/json"),new Response(JSON.stringify(s),{status:r.status,headers:r.headers})}case"function":if(s instanceof Blob)return new Response(s,{status:r.status,headers:r.headers});return s();case"number":case"boolean":return new Response(s.toString(),{status:r.status,headers:r.headers});case"undefined":return new Response("",{status:r.status,headers:r.headers});default:return new Response(s,{status:r.status,headers:r.headers})}else switch(typeof s){case"string":default:return new Response(s);case"object":if(s instanceof Response)return s;if(s instanceof Error)return errorToResponse(s,r.headers);if(s instanceof Blob)return new Response(s);return new Response(JSON.stringify(s),{headers:{"content-type":"application/json"}});case"function":if(s instanceof Blob)return new Response(s);return s();case"number":case"boolean":return new Response(s.toString());case"undefined":return new Response("")}};export const errorToResponse=(e,s)=>new Response(JSON.stringify({name:e?.name,message:e?.message,cause:e?.cause}),{status:500,headers:s});

@@ -120,5 +120,5 @@ /// <reference types="bun-types" />

export { Elysia, permission };
export { Type as t } from '@sinclair/typebox';
export { t } from './custom-types';
export { SCHEMA, DEFS, EXPOSED, createValidationError, getSchemaValidator, mergeDeep, mergeHook, mergeObjectArray, mapPathnameAndQueryRegEx, mapQuery } from './utils';
export type { Context, PreContext } from './context';
export type { Handler, RegisteredHook, BeforeRequestHandler, TypedRoute, OverwritableTypeRoute, ElysiaInstance, ElysiaConfig, HTTPMethod, ComposedHandler, InternalRoute, BodyParser, ErrorHandler, ErrorCode, TypedSchema, LocalHook, LocalHandler, LifeCycle, LifeCycleEvent, AfterRequestHandler, HookHandler, TypedSchemaToRoute, UnwrapSchema, LifeCycleStore, VoidLifeCycle, SchemaValidator, ElysiaRoute, ExtractPath, IsPathParameter, IsAny, IsNever, UnknownFallback, WithArray, ObjectValues, PickInOrder, MaybePromise, MergeIfNotNull } from './types';

@@ -1,1 +0,1 @@

import{Raikiri as e}from"raikiri";import{mapResponse as t,mapEarlyResponse as r}from"./handler";import{permission as s}from"./fn";import{SCHEMA as a,EXPOSED as i,DEFS as n,mapQuery as o,clone as h,mergeHook as l,mergeDeep as u,createValidationError as d,getSchemaValidator as f,getResponseSchemaValidator as c,mapPathnameAndQueryRegEx as m}from"./utils";import{registerSchemaPath as p}from"./schema";import{mapErrorCode as v,mapErrorStatus as g}from"./error";import{runFn as y}from"./fn";import{deserialize as b}from"superjson";export default class H{store={};meta={[a]:Object.create(null),[n]:Object.create(null),[i]:Object.create(null)};decorators={query:{},set:{status:200,headers:{}},store:this.store,[a]:this.meta[a],[n]:this.meta[n]};event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],error:[],stop:[]};server=null;$schema=null;router=new e;routes=[];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:l(h(this.event),s)});let i=this.meta[n],o=f(s?.schema?.body??this.$schema?.body,i),u=f(s?.schema?.headers??this.$schema?.headers,i,!0),d=f(s?.schema?.params??this.$schema?.params,i),m=f(s?.schema?.query??this.$schema?.query,i),v=c(s?.schema?.response??this.$schema?.response,i);p({schema:this.meta[a],hook:s,method:e,path:t,models:this.meta[n]});let g=l(h(this.event),s);g.schema||g.transform.length||g.beforeHandle.length||g.error.length||g.afterHandle.length||(g=void 0);let y={handle:r,hooks:g,validator:o||u||d||m||v?{body:o,header:u,params:d,query:m,response:v}:void 0};this.router.add(e,t,y)}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 H;r.store=this.store;let s=t(r);return s.event.request.length&&(this.event.request=[...this.event.request,...s.event.request]),Object.values(r.routes).forEach(({method:t,path:r,handler:a,hooks:i})=>{"/"===r?this._addHandler(t,e,a,l(i,{error:s.event.error})):this._addHandler(t,`${e}${r}`,a,l(i,{error:s.event.error}))}),this}guard(e,t){let r=new H;r.store=this.store;let s=t(r);return s.event.request.length&&(this.event.request=[...this.event.request,...s.event.request]),Object.values(r.routes).forEach(({method:t,path:r,handler:s,hooks:a})=>{this._addHandler(t,r,s,l(e,a))}),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}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}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}inject(e){return this.onTransform(t=>{Object.assign(t,e(t))})}fn(e){return 0===Object.keys(this.meta[i]).length&&this.post(this.config.fn??"/~fn",e=>y(e,this.meta[i])),this.meta[i]=u(this.meta[i],"function"==typeof e?e({...this.decorators,store:this.store,permission:s}):e),this}schema(e){let t=this.meta[n];return this.$schema={body:f(e.body,t),headers:f(e?.headers,t,!0),params:f(e?.params,t),query:f(e?.query,t),response:f(e?.response,t)},this}handle=async e=>{let s;let a=h(this.decorators);a.request=e;try{let i;if(this.event.request.length)for(let e=0;e<this.event.request.length;e++){let t=this.event.request[e](a);if(t instanceof Promise&&(t=await t),t=r(t,a.set))return t}let n=e.url.match(m);if(!n)throw Error("NOT_FOUND");let h=this.router.match(e.method,n[1])??this.router.match("ALL",n[1]);if(!h)throw Error("NOT_FOUND");let l=h.store;if("GET"!==e.method){let t=e.headers.get("content-type");if(t){let r=t.indexOf(";");if(-1!==r&&(t=t.slice(0,r)),this.event.parse.length)for(let e=0;e<this.event.parse.length;e++){let r=this.event.parse[e](a,t);if(r instanceof Promise&&(r=await r),void 0!==r){i=r;break}}if(void 0===i)switch(t){case"application/json":i=await e.json();break;case"text/plain":i=await e.text();break;case"application/x-www-form-urlencoded":i=o(await e.text());break;case"elysia/fn":i=b(await e.json())}}}a.body=i,a.params=h.params,n[2]&&(a.query=o(n[2]));let u=l.hooks;if(u?.error&&(s=u?.error),u?.transform.length)for(let e=0;e<u.transform.length;e++){let t=u.transform[e](a);t instanceof Promise&&await t}if(l.validator){let t=l.validator;if(u?.error&&(s=u?.error),t.headers){let r={};for(let t in e.headers)r[t]=e.headers.get(t);if(!1===t.headers.Check(r))throw d("header",t.headers,r)}if(!1===t.params?.Check(a.params))throw d("params",t.params,a.params);if(!1===t.query?.Check(a.query))throw d("query",t.query,a.query);if(!1===t.body?.Check(i))throw d("body",t.body,i)}if(u?.beforeHandle.length)for(let e=0;e<u.beforeHandle.length;e++){let t=u.beforeHandle[e](a);if(t instanceof Promise&&(t=await t),null!=t){for(let e=0;e<u.afterHandle.length;e++){let r=u.afterHandle[e](a,t);r instanceof Promise&&(r=await r),r&&(t=r)}let e=r(t,a.set);if(e)return e}}let f=l.handle(a);if(f instanceof Promise&&(f=await f),!1===l.validator?.response?.Check(f))throw u?.error&&(s=u?.error),d("response",l.validator.response,f);if(u?.afterHandle.length)for(let e=0;e<u.afterHandle.length;e++){let t=u.afterHandle[e](a,f);t instanceof Promise&&(t=await t);let s=r(t,a.set);if(s)return s}return t(f,a.set)}catch(i){let t=a.set;if((!t.status||t.status<300)&&(t.status=500),s){let a=v(i.message);for(let n=0;n<s.length;n++){let o=s[n]({request:e,error:i,set:t,code:a});o instanceof Promise&&(o=await o);let h=r(o,t);if(h)return h}}return this.handleError(e,i,t)}};async handleError(e,r,s={headers:{}}){for(let a=0;a<this.event.error.length;a++){let i=this.event.error[a]({request:e,code:v(r.message),error:r,set:s});if(i instanceof Promise&&(i=await i),null!=i)return t(i,s)}return new Response("string"==typeof r.cause?r.cause:r.message,{headers:s.headers,status:g(v(r.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.handle,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{Type as t}from"@sinclair/typebox";export{SCHEMA,DEFS,EXPOSED,createValidationError,getSchemaValidator,mergeDeep,mergeHook,mergeObjectArray,mapPathnameAndQueryRegEx,mapQuery}from"./utils";export{H as Elysia,s as permission};
import{Raikiri as e}from"raikiri";import{mapResponse as t,mapEarlyResponse as r}from"./handler";import{permission as s}from"./fn";import{SCHEMA as a,EXPOSED as n,DEFS as i,mapQuery as o,clone as h,mergeHook as l,mergeDeep as u,createValidationError as d,getSchemaValidator as f,getResponseSchemaValidator as c,mapPathnameAndQueryRegEx as m}from"./utils";import{registerSchemaPath as p}from"./schema";import{mapErrorCode as v,mapErrorStatus as g}from"./error";import{runFn as y}from"./fn";import{deserialize as b}from"superjson";export default class H{store={};meta={[a]:Object.create(null),[i]:Object.create(null),[n]:Object.create(null)};decorators={query:{},set:{status:200,headers:{}},store:this.store,[a]:this.meta[a],[i]:this.meta[i]};event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],error:[],stop:[]};server=null;$schema=null;router=new e;routes=[];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:l(h(this.event),s)});let n=this.meta[i],o=f(s?.schema?.body??this.$schema?.body,n),u=f(s?.schema?.headers??this.$schema?.headers,n,!0),d=f(s?.schema?.params??this.$schema?.params,n),m=f(s?.schema?.query??this.$schema?.query,n),v=c(s?.schema?.response??this.$schema?.response,n);p({schema:this.meta[a],contentType:s?.schema?.contentType,hook:s,method:e,path:t,models:this.meta[i]});let g=l(h(this.event),s);g.schema||g.transform.length||g.beforeHandle.length||g.error.length||g.afterHandle.length||(g=void 0);let y={handle:r,hooks:g,validator:o||u||d||m||v?{body:o,header:u,params:d,query:m,response:v}:void 0};this.router.add(e,t,y)}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 H;r.store=this.store;let s=t(r);return s.event.request.length&&(this.event.request=[...this.event.request,...s.event.request]),Object.values(r.routes).forEach(({method:t,path:r,handler:a,hooks:n})=>{"/"===r?this._addHandler(t,e,a,l(n,{error:s.event.error})):this._addHandler(t,`${e}${r}`,a,l(n,{error:s.event.error}))}),this}guard(e,t){let r=new H;r.store=this.store;let s=t(r);return s.event.request.length&&(this.event.request=[...this.event.request,...s.event.request]),Object.values(r.routes).forEach(({method:t,path:r,handler:s,hooks:a})=>{this._addHandler(t,r,s,l(e,a))}),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}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}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}inject(e){return this.onTransform(t=>{Object.assign(t,e(t))})}fn(e){return 0===Object.keys(this.meta[n]).length&&this.post(this.config.fn??"/~fn",e=>y(e,this.meta[n])),this.meta[n]=u(this.meta[n],"function"==typeof e?e({...this.decorators,store:this.store,permission:s}):e),this}schema(e){let t=this.meta[i];return this.$schema={body:f(e.body,t),headers:f(e?.headers,t,!0),params:f(e?.params,t),query:f(e?.query,t),response:f(e?.response,t)},this}handle=async e=>{let s;let a=h(this.decorators);a.request=e;try{let n;if(this.event.request.length)for(let e=0;e<this.event.request.length;e++){let t=this.event.request[e](a);if(t instanceof Promise&&(t=await t),t=r(t,a.set))return t}let i=e.url.match(m);if(!i)throw Error("NOT_FOUND");let h=this.router.match(e.method,i[1])??this.router.match("ALL",i[1]);if(!h)throw Error("NOT_FOUND");let l=h.store,u=l.hooks;if(u?.error&&(s=u?.error),"GET"!==e.method){let t=e.headers.get("content-type");if(t){let r=t.indexOf(";");if(-1!==r&&(t=t.slice(0,r)),this.event.parse.length)for(let e=0;e<this.event.parse.length;e++){let r=this.event.parse[e](a,t);if(r instanceof Promise&&(r=await r),void 0!==r){n=r;break}}if(void 0===n)switch(t){case"application/json":n=await e.json();break;case"text/plain":n=await e.text();break;case"application/x-www-form-urlencoded":n=o(await e.text());break;case"multipart/form-data":n={},await e.formData().then(e=>{for(let t of e.keys()){if(t in n)continue;let r=e.getAll(t);1===r.length?n[t]=r[0]:n[t]=r}});break;case"elysia/fn":n=b(await e.json())}}}if(a.body=n,a.params=h.params,i[2]&&(a.query=o(i[2])),u?.transform.length)for(let e=0;e<u.transform.length;e++){let t=u.transform[e](a);t instanceof Promise&&await t}if(l.validator){let t=l.validator;if(u?.error&&(s=u?.error),t.headers){let r={};for(let t in e.headers)r[t]=e.headers.get(t);if(!1===t.headers.Check(r))throw d("header",t.headers,r)}if(!1===t.params?.Check(a.params))throw d("params",t.params,a.params);if(!1===t.query?.Check(a.query))throw d("query",t.query,a.query);if(!1===t.body?.Check(n))throw d("body",t.body,n)}if(u?.beforeHandle.length)for(let e=0;e<u.beforeHandle.length;e++){let t=u.beforeHandle[e](a);if(t instanceof Promise&&(t=await t),null!=t){for(let e=0;e<u.afterHandle.length;e++){let r=u.afterHandle[e](a,t);r instanceof Promise&&(r=await r),r&&(t=r)}let e=r(t,a.set);if(e)return e}}let f=l.handle(a);if(f instanceof Promise&&(f=await f),!1===l.validator?.response?.Check(f))throw u?.error&&(s=u?.error),d("response",l.validator.response,f);if(u?.afterHandle.length)for(let e=0;e<u.afterHandle.length;e++){let t=u.afterHandle[e](a,f);t instanceof Promise&&(t=await t);let s=r(t,a.set);if(s)return s}return t(f,a.set)}catch(n){let t=a.set;if((!t.status||t.status<300)&&(t.status=500),s){let a=v(n.message);for(let i=0;i<s.length;i++){let o=s[i]({request:e,error:n,set:t,code:a});o instanceof Promise&&(o=await o);let h=r(o,t);if(h)return h}}return this.handleError(e,n,t)}};async handleError(e,r,s={headers:{}}){for(let a=0;a<this.event.error.length;a++){let n=this.event.error[a]({request:e,code:v(r.message),error:r,set:s});if(n instanceof Promise&&(n=await n),null!=n)return t(n,s)}return new Response("string"==typeof r.cause?r.cause:r.message,{headers:s.headers,status:g(v(r.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.handle,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[i]||(this.meta[i][e]=t)}),this}}export{t}from"./custom-types";export{SCHEMA,DEFS,EXPOSED,createValidationError,getSchemaValidator,mergeDeep,mergeHook,mergeObjectArray,mapPathnameAndQueryRegEx,mapQuery}from"./utils";export{H as Elysia,s as permission};

@@ -1,8 +0,9 @@

import { TSchema } from '@sinclair/typebox';
import type { OpenAPIV2 } from 'openapi-types';
import { type TSchema } from '@sinclair/typebox';
import type { OpenAPIV3 } from 'openapi-types';
import type { HTTPMethod, LocalHook } from './types';
export declare const toOpenAPIPath: (path: string) => string;
export declare const mapProperties: (name: string, schema: TSchema | string | undefined, models: Record<string, TSchema>) => any[];
export declare const registerSchemaPath: ({ schema, path, method, hook, models }: {
schema: Partial<OpenAPIV2.PathsObject>;
export declare const registerSchemaPath: ({ schema, contentType, path, method, hook, models }: {
schema: Partial<OpenAPIV3.PathsObject>;
contentType?: string | string[] | undefined;
path: string;

@@ -15,4 +16,4 @@ method: HTTPMethod;

meta: Record<typeof import("./utils").SCHEMA, {}> & Record<typeof import("./utils").DEFS, {}> & Record<typeof import("./utils").EXPOSED, {}>;
}>, string, import("./types").MergeSchema<import("./types").TypedSchema<string>, {}>> | undefined;
}>, string, import("./types").MergeSchema<import("./types").TypedSchema<string>, {}>, import("./types").TypedSchema<string>> | undefined;
models: Record<string, TSchema>;
}) => void;

@@ -1,1 +0,1 @@

import{Kind as e}from"@sinclair/typebox";export const toOpenAPIPath=e=>e.split("/").map(e=>e.startsWith(":")?`{${e.slice(1,e.length)}}`:e).join("/");export const mapProperties=(e,t,r)=>{if(void 0===t)return[];if("string"==typeof t){if(t in r)t=r[t];else throw Error(`Can't find model ${t}`)}return Object.entries(t?.properties??[]).map(([r,s])=>({...s,in:e,name:r,type:s?.type,required:t.required?.includes(r)??!1}))};export const registerSchemaPath=({schema:t,path:r,method:s,hook:i,models:o})=>{r=toOpenAPIPath(r);let a=i?.schema?.body,n=i?.schema?.params,p=i?.schema?.headers,m=i?.schema?.query,h=i?.schema?.response;if("object"==typeof h){if(e in h){let{type:e,properties:t,required:r,...s}=h;h={200:{...s,schema:{type:e,properties:t,required:r}}}}else Object.entries(h).forEach(([e,t])=>{if("string"==typeof t){let{type:r,properties:s,required:i,...a}=o[t];h[e]={...a,schema:{$ref:`#/definitions/${t}`}}}else{let{type:r,properties:s,required:i,...o}=t;h[e]={...o,schema:{type:r,properties:s,required:i}}}})}else if("string"==typeof h){let{type:e,properties:t,required:r,...s}=o[h];h={200:{...s,schema:{$ref:`#/definitions/${h}`}}}}let c=[...mapProperties("header",p,o),...mapProperties("path",n,o),...mapProperties("query",m,o)];a&&c.push({in:"body",name:"body",required:!0,schema:"string"==typeof a?{$ref:`#/definitions/${a}`}:a}),t[r]={...t[r]?t[r]:{},[s.toLowerCase()]:{...p||n||m||a?{parameters:c}:{},...h?{responses:h}:{},...i?.schema?.detail}}};
import{Kind as e}from"@sinclair/typebox";export const toOpenAPIPath=e=>e.split("/").map(e=>e.startsWith(":")?`{${e.slice(1,e.length)}}`:e).join("/");export const mapProperties=(e,t,r)=>{if(void 0===t)return[];if("string"==typeof t){if(t in r)t=r[t];else throw Error(`Can't find model ${t}`)}return Object.entries(t?.properties??[]).map(([r,o])=>({...o,in:e,name:r,type:o?.type,required:t.required?.includes(r)??!1}))};let t=(e,t)=>{let r={};for(let o of e)r[o]={schema:"string"==typeof t?{$ref:`#/components/schemas/${t}`}:{...t}};return r};export const registerSchemaPath=({schema:r,contentType:o=["application/json","multipart/form-data","text/plain"],path:s,method:i,hook:n,models:p})=>{s=toOpenAPIPath(s);let a="string"==typeof o?[o]:o??["application/json"],c=n?.schema?.body,l=n?.schema?.params,m=n?.schema?.headers,f=n?.schema?.query,h=n?.schema?.response;if("object"==typeof h){if(e in h){let{type:e,properties:r,required:o,...s}=h;h={200:{...s,description:s.description,content:t(a,"object"===e||"array"===e?{type:e,properties:r,required:o}:h)}}}else Object.entries(h).forEach(([e,r])=>{if("string"==typeof r){let{type:o,properties:s,required:i,...n}=p[r];h[e]={...n,description:n.description,content:t(a,r)}}else{let{type:o,properties:s,required:i,...n}=r;h[e]={...n,description:n.description,content:t(a,{type:o,properties:s,required:i})}}})}else if("string"==typeof h){let{type:e,properties:r,required:o,...s}=p[h];h={200:{...s,content:t(a,h)}}}let d=[...mapProperties("header",m,p),...mapProperties("path",l,p),...mapProperties("query",f,p)];r[s]={...r[s]?r[s]:{},[i.toLowerCase()]:{...m||l||f||c?{parameters:d}:{},...h?{responses:h}:{},...n?.schema?.detail,...c?{requestBody:{content:t(a,"string"==typeof c?{$ref:`#/components/schemas/${c}`}:c)}}:null}}};

@@ -8,3 +8,3 @@ /// <reference types="bun-types" />

import type { SCHEMA, DEFS, EXPOSED } from './utils';
import type { OpenAPIV2 } from 'openapi-types';
import type { OpenAPIV3 } from 'openapi-types';
export type WithArray<T> = T | T[];

@@ -16,3 +16,3 @@ export type ObjectValues<T extends object> = T[keyof T];

schema?: TypedSchema;
meta?: Record<typeof SCHEMA, Partial<OpenAPIV2.PathsObject>> & Record<typeof DEFS, {
meta?: Record<typeof SCHEMA, Partial<OpenAPIV3.PathsObject>> & Record<typeof DEFS, {
[x in string]: TSchema;

@@ -120,5 +120,9 @@ }> & Record<typeof EXPOSED, Record<string, Record<string, unknown>>>;

};
export interface LocalHook<Schema extends TypedSchema = TypedSchema, Instance extends ElysiaInstance<any> = ElysiaInstance, Path extends string = string, FinalSchema extends MergeSchema<Schema, Instance['schema']> = MergeSchema<Schema, Instance['schema']>> {
schema?: Schema & {
detail?: Partial<OpenAPIV2.OperationObject>;
type MaybeArray<T> = T | T[];
type ExtractModelName<Type> = Type extends TypedSchema<infer X> ? X : never;
type ContentType = MaybeArray<(string & {}) | 'text/plain' | 'application/json' | 'multipart/form-data' | 'application/x-www-form-urlencoded'>;
export interface LocalHook<Schema extends TypedSchema = TypedSchema, Instance extends ElysiaInstance<any> = ElysiaInstance, Path extends string = string, FinalSchema extends MergeSchema<Schema, Instance['schema']> = MergeSchema<Schema, Instance['schema']>, Models extends TypedSchema = TypedSchema<ExtractModelName<Schema>>> {
schema?: (Models extends Schema ? Models : Models) & {
contentType?: ContentType;
detail?: Partial<OpenAPIV3.OperationObject>;
};

@@ -125,0 +129,0 @@ transform?: WithArray<HookHandler<FinalSchema, Instance, Path>>;

{
"name": "elysia",
"description": "Fast, and friendly Bun web framework",
"version": "0.3.0-exp-240224.141",
"version": "0.3.0-exp-240225.2119",
"author": {

@@ -16,3 +16,3 @@ "name": "saltyAom",

},
"types": "./dist/index.d.ts",
"types": "./src/index.ts",
"repository": {

@@ -32,3 +32,3 @@ "type": "git",

"scripts": {
"test": "bun wiptest",
"test": "bun test",
"dev": "bun run --hot example/http.ts",

@@ -50,3 +50,3 @@ "build": "rimraf dist && swc src -d dist && tsc --project tsconfig.esm.json",

"@typescript-eslint/parser": "^5.48.2",
"bun-types": "^0.5.0",
"bun-types": "^0.5.7",
"eslint": "^8.32.0",

@@ -53,0 +53,0 @@ "rimraf": "^3.0.2",

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