Comparing version 0.5.3 to 0.5.4
import type { Elysia } from '.'; | ||
import { SCHEMA, DEFS } from './utils'; | ||
import type { BeforeRequestHandler, ComposedHandler, HTTPMethod, LocalHandler, RegisteredHook, SchemaValidator } from './types'; | ||
import { TAnySchema } from '@sinclair/typebox'; | ||
import type { ElysiaConfig, BeforeRequestHandler, ComposedHandler, HTTPMethod, LocalHandler, RegisteredHook, SchemaValidator } from './types'; | ||
import type { TAnySchema } from '@sinclair/typebox'; | ||
export declare const hasReturn: (fnLiteral: string) => boolean; | ||
export declare const isFnUse: (keyword: string, fnLiteral: string) => boolean; | ||
export declare const findElysiaMeta: (type: string, schema: TAnySchema, found?: string[], parent?: string) => string[] | "root" | null; | ||
export declare const composeHandler: ({ path, method, hooks, validator, handler, handleError, meta, onRequest }: { | ||
export declare const composeHandler: ({ method, hooks, validator, handler, handleError, meta, onRequest, config }: { | ||
path: string; | ||
@@ -17,4 +17,5 @@ method: HTTPMethod; | ||
onRequest: BeforeRequestHandler<any, any>[]; | ||
config: ElysiaConfig; | ||
}) => ComposedHandler; | ||
export declare const composeGeneralHandler: (app: Elysia<any>) => any; | ||
export declare const composeErrorHandler: (app: Elysia<any>) => any; |
@@ -1,2 +0,18 @@ | ||
"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 f},composeGeneralHandler:function(){return d},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},f=({path:c,method:f,hooks:d,validator:p,handler:y,handleError:h,meta:m,onRequest:$})=>{let b="try {\n",E="string"==typeof d.type,w=p||"GET"!==f?[y,...d.transform,...d.beforeHandle,...d.afterHandle].map(e=>e.toString()):[],q="GET"!==f&&(p.body||E||w.some(e=>l("body",e))),g=p.headers||w.some(e=>l("headers",e));g&&(b+=a.toJSON?`c.headers = c.request.headers.toJSON() | ||
"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 l},isFnUse:function(){return u},findElysiaMeta:function(){return f},composeHandler:function(){return d},composeGeneralHandler:function(){return p},composeErrorHandler:function(){return y}});const e=require("fast-querystring"),r=require("./handler"),t=require("./utils"),n=require("./error"),s="AsyncFunction",o=e=>e.constructor.name===s,a=new Headers,c=RegExp(" (\\w+) = context","g"),l=e=>{let r=e.indexOf(")");return 61===e.charCodeAt(r+2)&&123!==e.charCodeAt(r+5)||e.includes("return")},i=e=>({composeValidation:(r,t=`c.${r}`)=>e?`throw new ValidationError( | ||
'${r}', | ||
${r}, | ||
${t} | ||
)`:`return new ValidationError( | ||
'${r}', | ||
${r}, | ||
${t} | ||
).toResponse(c.set.headers)`,composeResponseValidation:(r="r")=>e?`throw new ValidationError( | ||
'response', | ||
response[c.set.status], | ||
${r} | ||
)`:`return new ValidationError( | ||
'response', | ||
response[c.set.status], | ||
${r} | ||
).toResponse(c.set.headers)`}),u=(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 s=RegExp(`{.*?} = (${n.join("|")})`,"g");for(let[t]of r.matchAll(s))if(t.includes(`{ ${e}`)||t.includes(`, ${e}`))return!0;return!1},f=(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){f(e,o,t,a);continue}if(o.anyOf){for(let r of o.anyOf)f(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},d=({method:c,hooks:d,validator:p,handler:y,handleError:$,meta:h,onRequest:m,config:b})=>{let E=b.forceErrorEncapsulation||d.error.length>0||void 0===Bun,{composeValidation:q,composeResponseValidation:g}=i(E),w=E?"try {\n":"",x="string"==typeof d.type,k=p||"GET"!==c?[y,...d.transform,...d.beforeHandle,...d.afterHandle].map(e=>e.toString()):[],H="GET"!==c&&(p.body||x||k.some(e=>u("body",e))),R=p.headers||k.some(e=>u("headers",e));R&&(w+=a.toJSON?`c.headers = c.request.headers.toJSON() | ||
`:`c.headers = {} | ||
@@ -6,10 +22,5 @@ for (const key of c.request.headers.keys()) | ||
if (headers.Check(h) === false) { | ||
throw throw new ValidationError( | ||
'header', | ||
headers, | ||
h | ||
) | ||
} | ||
`);let k=p.query||w.some(e=>l("query",e));k&&(b+=`const url = c.request.url | ||
if (headers.Check(c.headers) === false) | ||
${q("headers")} | ||
`);let v=p.query||k.some(e=>u("query",e));v&&(w+=`const url = c.request.url | ||
@@ -21,3 +32,3 @@ if(c.query !== -1) { | ||
} | ||
`);let x=w.some(e=>l("set",e))||$.some(e=>l("set",e.toString())),H=q||y.constructor.name===o||d.parse.length||d.afterHandle.find(s)||d.beforeHandle.find(s)||d.transform.find(s);if(q){let e=p?.body?.schema;if(e&&"anyOf"in e){let r=!1,t=e.anyOf[0].type;for(let n of e.anyOf)if(n.type!==t){r=!0;break}r&&(e=void 0)}if(E||e){if(d.parse.length){b+=(g?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+` | ||
`);let O=k.some(e=>u("set",e))||m.some(e=>u("set",e.toString())),S=H||y.constructor.name===s||d.parse.length||d.afterHandle.find(o)||d.beforeHandle.find(o)||d.transform.find(o);if(H){let e=p?.body?.schema;if(e&&"anyOf"in e){let r=!1,t=e.anyOf[0].type;for(let n of e.anyOf)if(n.type!==t){r=!0;break}r&&(e=void 0)}if(x||e){if(d.parse.length){w+=(R?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+` | ||
if (contentType) { | ||
@@ -27,6 +38,6 @@ const index = contentType.indexOf(';') | ||
`+`let used = false | ||
`;for(let e=0;e<d.parse.length;e++){let r=`bo${e}`;0!==e&&(b+=`if(!used) { | ||
`),b+=`let ${r} = parse[${e}](c, contentType);if(${r} instanceof Promise) ${r} = await ${r}; | ||
`;for(let e=0;e<d.parse.length;e++){let r=`bo${e}`;0!==e&&(w+=`if(!used) { | ||
`),w+=`let ${r} = parse[${e}](c, contentType);if(${r} instanceof Promise) ${r} = await ${r}; | ||
if(${r} !== undefined) { c.body = ${r}; used = true } | ||
`,0!==e&&(b+="}")}b+="if (!used) {"}if(e)"object"===e.type?"URLEncoded"===e.elysiaMeta?b+="c.body = parseQuery(await c.request.text())":p.body.Code().includes("custom('File")?b+=`c.body = {} | ||
`,0!==e&&(w+="}")}w+="if (!used) {"}if(e)"object"===e.type?"URLEncoded"===e.elysiaMeta?w+="c.body = parseQuery(await c.request.text())":p.body.Code().includes("custom('File")?w+=`c.body = {} | ||
@@ -43,3 +54,3 @@ await c.request.formData().then((form) => { | ||
} | ||
})`:b+="c.body = JSON.parse(await c.request.text())":b+="c.body = await c.request.text()";else switch(d.type){case"application/json":b+="c.body = JSON.parse(await c.request.text());";break;case"text/plain":b+="c.body = await c.request.text();";break;case"application/x-www-form-urlencoded":b+="c.body = parseQuery(await c.request.text());";break;case"multipart/form-data":b+=`c.body = {} | ||
})`:w+="c.body = JSON.parse(await c.request.text())":w+="c.body = await c.request.text()";else switch(d.type){case"application/json":w+="c.body = JSON.parse(await c.request.text());";break;case"text/plain":w+="c.body = await c.request.text();";break;case"application/x-www-form-urlencoded":w+="c.body = parseQuery(await c.request.text());";break;case"multipart/form-data":w+=`c.body = {} | ||
@@ -54,11 +65,11 @@ for (const key of (await c.request.formData()).keys()) { | ||
else c.body[key] = value | ||
}`}d.parse.length&&(b+="}}")}else{if(b+="\n"+(g?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+` | ||
}`}d.parse.length&&(w+="}}")}else{if(w+="\n"+(R?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+` | ||
if (contentType) { | ||
const index = contentType.indexOf(';') | ||
if (index !== -1) contentType = contentType.substring(0, index) | ||
`,d.parse.length){b+=`let used = false | ||
`;for(let e=0;e<d.parse.length;e++){let r=`bo${e}`;0!==e&&(b+=`if(!used) { | ||
`),b+=`let ${r} = parse[${e}](c, contentType);if(${r} instanceof Promise) ${r} = await ${r}; | ||
`,d.parse.length){w+=`let used = false | ||
`;for(let e=0;e<d.parse.length;e++){let r=`bo${e}`;0!==e&&(w+=`if(!used) { | ||
`),w+=`let ${r} = parse[${e}](c, contentType);if(${r} instanceof Promise) ${r} = await ${r}; | ||
if(${r} !== undefined) { c.body = ${r}; used = true } | ||
`,0!==e&&(b+="}")}b+="if (!used)"}b+=`switch (contentType) { | ||
`,0!==e&&(w+="}")}w+="if (!used)"}w+=`switch (contentType) { | ||
case 'application/json': | ||
@@ -92,59 +103,55 @@ c.body = JSON.parse(await c.request.text()) | ||
} | ||
`}b+="\n"}if(p.params){let e=u("Numeric",p.params.schema);if(e){if("object"==typeof e)for(let r of e)b+=`c.params.${r} = +c.params.${r};`;b+="\n"}}if(p.query){let e=u("Numeric",p.query.schema);if(e){if("object"==typeof e)for(let r of e)b+=`c.query.${r} = +c.query.${r};`;b+="\n"}}if(p.headers){let e=u("Numeric",p.headers.schema);if(e){if("object"==typeof e)for(let r of e)b+=`c.headers.${r} = +c.headers.${r};`;b+="\n"}}if(p.body){let e=u("Numeric",p.body.schema);if(e){switch(typeof e){case"string":b+="c.body = +c.body;";break;case"object":for(let r of e)b+=`c.body.${r} = +c.body.${r};`}b+="\n"}}if(d?.transform)for(let e=0;e<d.transform.length;e++){let r=d.transform[e];"derive"===r.$elysia?b+=d.transform[e].constructor.name===o?`Object.assign(c, await transform[${e}](c));`:`Object.assign(c, transform[${e}](c));`:b+=d.transform[e].constructor.name===o?`await transform[${e}](c);`:`transform[${e}](c);`}if(p&&(p.headers&&(b+=` | ||
`}w+="\n"}if(p.params){let e=f("Numeric",p.params.schema);if(e){if("object"==typeof e)for(let r of e)w+=`c.params.${r} = +c.params.${r};`;w+="\n"}}if(p.query){let e=f("Numeric",p.query.schema);if(e){if("object"==typeof e)for(let r of e)w+=`c.query.${r} = +c.query.${r};`;w+="\n"}}if(p.headers){let e=f("Numeric",p.headers.schema);if(e){if("object"==typeof e)for(let r of e)w+=`c.headers.${r} = +c.headers.${r};`;w+="\n"}}if(p.body){let e=f("Numeric",p.body.schema);if(e){switch(typeof e){case"string":w+="c.body = +c.body;";break;case"object":for(let r of e)w+=`c.body.${r} = +c.body.${r};`}w+="\n"}}if(d?.transform)for(let e=0;e<d.transform.length;e++){let r=d.transform[e];"derive"===r.$elysia?w+=d.transform[e].constructor.name===s?`Object.assign(c, await transform[${e}](c));`:`Object.assign(c, transform[${e}](c));`:w+=d.transform[e].constructor.name===s?`await transform[${e}](c);`:`transform[${e}](c);`}if(p&&(p.headers&&(w+=` | ||
if (headers.Check(c.headers) === false) { | ||
throw new ValidationError( | ||
'header', | ||
headers, | ||
c.headers | ||
) | ||
${q("headers")} | ||
} | ||
`),p.params&&(b+="if(params.Check(c.params) === false) { throw new ValidationError('params', params, c.params) }"),p.query&&(b+="if(query.Check(c.query) === false) { throw new ValidationError('query', query, c.query) }"),p.body&&(b+="if(body.Check(c.body) === false) { throw new ValidationError('body', body, c.body) }")),d?.beforeHandle)for(let e=0;e<d.beforeHandle.length;e++){let r=`be${e}`,t=i(d.beforeHandle[e].toString());if(t){if(b+=(d.beforeHandle[e].constructor.name===o?`let ${r} = await beforeHandle[${e}](c); | ||
`),p.params&&(w+=`if(params.Check(c.params) === false) { ${q("params")} }`),p.query&&(w+=`if(query.Check(c.query) === false) { ${q("query")} }`),p.body&&(w+=`if(body.Check(c.body) === false) { ${q("body")} }`)),d?.beforeHandle)for(let e=0;e<d.beforeHandle.length;e++){let r=`be${e}`,t=l(d.beforeHandle[e].toString());if(t){if(w+=(d.beforeHandle[e].constructor.name===s?`let ${r} = await beforeHandle[${e}](c); | ||
`:`let ${r} = beforeHandle[${e}](c); | ||
`)+`if(${r} !== undefined) { | ||
`,d?.afterHandle)for(let e=0;e<d.afterHandle.length;e++){let t=i(d.afterHandle[e].toString());if(t){let t=`af${e}`;b+=(d.afterHandle[e].constructor.name===o?`const ${t} = await afterHandle[${e}](c, ${r}); | ||
`,d?.afterHandle)for(let e=0;e<d.afterHandle.length;e++){let t=l(d.afterHandle[e].toString());if(t){let t=`af${e}`;w+=(d.afterHandle[e].constructor.name===s?`const ${t} = await afterHandle[${e}](c, ${r}); | ||
`:`const ${t} = afterHandle[${e}](c, ${r}); | ||
`)+`if(${t} !== undefined) { ${r} = ${t} } | ||
`}else b+=d.afterHandle[e].constructor.name===o?`await afterHandle[${e}](c, ${r}); | ||
`}else w+=d.afterHandle[e].constructor.name===s?`await afterHandle[${e}](c, ${r}); | ||
`:`afterHandle[${e}](c, ${r}); | ||
`}p.response&&(b+=`if(response[c.set.status]?.Check(${r}) === false) { | ||
`}p.response&&(w+=`if(response[c.set.status]?.Check(${r}) === false) { | ||
if(!(response instanceof Error)) | ||
throw new ValidationError('response', response[c.set.status], ${r}) | ||
${g(r)} | ||
} | ||
`),b+=`return mapEarlyResponse(${r}, c.set)} | ||
`}else b+=d.beforeHandle[e].constructor.name===o?`await beforeHandle[${e}](c); | ||
`),w+=`return mapEarlyResponse(${r}, c.set)} | ||
`}else w+=d.beforeHandle[e].constructor.name===s?`await beforeHandle[${e}](c); | ||
`:`beforeHandle[${e}](c); | ||
`}if(d?.afterHandle.length){b+=y.constructor.name===o?`let r = await handler(c); | ||
`}if(d?.afterHandle.length){w+=y.constructor.name===s?`let r = await handler(c); | ||
`:`let r = handler(c); | ||
`;for(let e=0;e<d.afterHandle.length;e++){let r=`af${e}`,t=i(d.afterHandle[e].toString());t?(b+=d.afterHandle[e].constructor.name===o?`let ${r} = await afterHandle[${e}](c, r) | ||
`;for(let e=0;e<d.afterHandle.length;e++){let r=`af${e}`,t=l(d.afterHandle[e].toString());t?(w+=d.afterHandle[e].constructor.name===s?`let ${r} = await afterHandle[${e}](c, r) | ||
`:`let ${r} = afterHandle[${e}](c, r) | ||
`,p.response?b+=`if(response[c.set.status]?.Check(${r}) === false) { | ||
`,p.response?w+=`if(response[c.set.status]?.Check(${r}) === false) { | ||
if(!(response instanceof Error)) | ||
throw new ValidationError('response', response[c.set.status], ${r}) | ||
${g(r)} | ||
} | ||
${r} = mapEarlyResponse(${r}, c.set) | ||
if(${r}) return ${r}; | ||
`:b+=`if(${r}) return ${r}; | ||
`):b+=d.afterHandle[e].constructor.name===o?`await afterHandle[${e}](c, r) | ||
`:w+=`if(${r}) return ${r}; | ||
`):w+=d.afterHandle[e].constructor.name===s?`await afterHandle[${e}](c, r) | ||
`:`afterHandle[${e}](c, r) | ||
`}p.response&&(b+=`if(response[c.set.status]?.Check(r) === false) { | ||
`}p.response&&(w+=`if(response[c.set.status]?.Check(r) === false) { | ||
if(!(response instanceof Error)) | ||
throw new ValidationError('response', response[c.set.status], r) | ||
${g()} | ||
} | ||
`),x?b+=`return mapResponse(r, c.set) | ||
`:b+=`return mapCompactResponse(r) | ||
`}else if(p.response)b+=(y.constructor.name===o?`const r = await handler(c); | ||
`),O?w+=`return mapResponse(r, c.set) | ||
`:w+=`return mapCompactResponse(r) | ||
`}else if(p.response)w+=(y.constructor.name===s?`const r = await handler(c); | ||
`:`const r = handler(c); | ||
`)+`if(response[c.set.status]?.Check(r) === false) { | ||
if(!(response instanceof Error)) | ||
throw new ValidationError('response', response[c.set.status], r) | ||
${g()} | ||
} | ||
`,x?b+=`return mapResponse(r, c.set) | ||
`:b+=`return mapCompactResponse(r) | ||
`;else{let e=y.constructor.name===o?"await handler(c) ":"handler(c)";x?b+=`return mapResponse(${e}, c.set) | ||
`:b+=`return mapCompactResponse(${e}) | ||
`}b+=` | ||
`,O?w+=`return mapResponse(r, c.set) | ||
`:w+=`return mapCompactResponse(r) | ||
`;else{let e=y.constructor.name===s?"await handler(c) ":"handler(c)";O?w+=`return mapResponse(${e}, c.set) | ||
`:w+=`return mapCompactResponse(${e}) | ||
`}E&&(w+=` | ||
} catch(error) { | ||
${H?"":"return (async () => {"} | ||
${S?"":"return (async () => {"} | ||
const set = c.set | ||
@@ -168,4 +175,4 @@ | ||
return handleError(c.request, error, set) | ||
${H?"":"})()"} | ||
}`,b=`const { | ||
${S?"":"})()"} | ||
}`),w=`const { | ||
handler, | ||
@@ -191,3 +198,2 @@ handleError, | ||
mapEarlyResponse, | ||
mapErrorCode, | ||
parseQuery | ||
@@ -201,3 +207,3 @@ }, | ||
}, | ||
${m?` | ||
${h?` | ||
meta, | ||
@@ -210,6 +216,7 @@ SCHEMA, | ||
return ${H?"async":""} function(c) { | ||
${m?"c[SCHEMA] = meta[SCHEMA]; c[DEFS] = meta[DEFS];":""} | ||
${b} | ||
}`;let R=Function("hooks",b);return R({handler:y,hooks:d,validator:p,handleError:h,utils:{mapResponse:r.mapResponse,mapCompactResponse:r.mapCompactResponse,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})},d=e=>{let t="";for(let r of Object.keys(e.decorators))t+=`,${r}: app.decorators.${r}`;let{router:o,staticRouter:s}=e,a=`const route = find(method, path) ${o.root.ALL?'?? find("ALL", path)':""} | ||
return ${S?"async":""} function(c) { | ||
${h?"c[SCHEMA] = meta[SCHEMA]; c[DEFS] = meta[DEFS];":""} | ||
${w} | ||
}`;let C=Function("hooks",w);return C({handler:y,hooks:d,validator:p,handleError:$,utils:{mapResponse:r.mapResponse,mapCompactResponse:r.mapCompactResponse,mapEarlyResponse:r.mapEarlyResponse,parseQuery:e.parse},error:{ParseError:n.ParseError,NotFoundError:n.NotFoundError,ValidationError:n.ValidationError,InternalServerError:n.InternalServerError},meta:h,SCHEMA:h?t.SCHEMA:void 0,DEFS:h?t.DEFS:void 0})},p=e=>{let t="";for(let r of Object.keys(e.decorators))t+=`,${r}: app.decorators.${r}`;let{router:s,staticRouter:o}=e,a=` | ||
const route = find(request.method, path) ${s.root.ALL?'?? find("ALL", path)':""} | ||
if (route === null) | ||
@@ -226,8 +233,8 @@ return ${e.event.error.length?`handleError( | ||
return route.store(ctx)`,c="";for(let[e,{code:r,all:t}]of Object.entries(s.map))c+=`case '${e}': | ||
switch(method) { | ||
return route.store(ctx)`,c="";for(let[e,{code:r,all:t}]of Object.entries(o.map))c+=`case '${e}': | ||
switch(request.method) { | ||
${r} | ||
${t??"default:\n"+a}} | ||
${t??`default: ${a}`}} | ||
`;let l=`const { | ||
`;let i=`const { | ||
app, | ||
@@ -243,3 +250,3 @@ app: { store, router, staticRouter }, | ||
${s.variables} | ||
${o.variables} | ||
@@ -252,5 +259,34 @@ const find = router.find.bind(router) | ||
return function(request) { | ||
`;if(e.event.request.length){i+=` | ||
const ctx = { | ||
request, | ||
store, | ||
set: { | ||
headers: {}, | ||
status: 200 | ||
} | ||
${t} | ||
} | ||
try { | ||
`;for(let r=0;r<e.event.request.length;r++){let t=l(e.event.request[r].toString());i+=t?`const response = mapEarlyResponse( | ||
onRequest[${r}](ctx), | ||
ctx.set | ||
) | ||
if (response) return response | ||
`:`mapEarlyResponse(onRequest[${r}](ctx), ctx.set)`}i+=`} catch (error) { | ||
return handleError(request, error, ctx.set) | ||
} | ||
const url = request.url, | ||
s = url.indexOf('/', 12), | ||
i = ctx.query = url.indexOf('?', s + 1), | ||
path = i === -1 ? url.substring(s) : url.substring(s, i);`}else i+=` | ||
const url = request.url, | ||
s = url.indexOf('/', 12) | ||
const ctx = { | ||
request, | ||
store, | ||
query: url.indexOf('?', s + 1), | ||
set: { | ||
@@ -262,21 +298,14 @@ headers: {}, | ||
} | ||
`;if(e.event.request.length){l+="try {";for(let r=0;r<e.event.request.length;r++){let t=i(e.event.request[r].toString());l+=t?`const response = mapEarlyResponse( | ||
onRequest[${r}](ctx), | ||
ctx.set | ||
) | ||
if (response) return response | ||
`:`mapEarlyResponse(onRequest[${r}](ctx), ctx.set)`}l+=`} catch (error) { | ||
return handleError(request, error, ctx.set) | ||
}`}return l+=` | ||
const { url, method } = request, | ||
s = url.indexOf('/', 12), | ||
i = ctx.query = url.indexOf('?', s + 1), | ||
path = i === -1 ? url.substring(s) : url.substring(s, i) | ||
const path = | ||
ctx.query === -1 | ||
? url.substring(s) | ||
: url.substring(s, ctx.query);`;return i+=` | ||
switch(path) { | ||
${c} | ||
default: ${a} | ||
default: | ||
${a} | ||
} | ||
}`,e.handleError=p(e),Function("data",l)({app:e,mapEarlyResponse:r.mapEarlyResponse,NotFoundError:n.NotFoundError})},p=e=>{let t=`const { | ||
}`,e.handleError=y(e),Function("data",i)({app:e,mapEarlyResponse:r.mapEarlyResponse,NotFoundError:n.NotFoundError})},y=e=>{let t=`const { | ||
app: { event: { error: onError } }, | ||
@@ -286,3 +315,3 @@ mapResponse | ||
return ${e.event.error.find(e=>e.constructor.name===o)?"async":""} function(request, error, set) {`;for(let r=0;r<e.event.error.length;r++){let n=e.event.error[r],s=`${n.constructor.name===o?"await ":""}onError[${r}]({ | ||
return ${e.event.error.find(e=>e.constructor.name===s)?"async":""} function(request, error, set) {`;for(let r=0;r<e.event.error.length;r++){let n=e.event.error[r],o=`${n.constructor.name===s?"await ":""}onError[${r}]({ | ||
request, | ||
@@ -292,4 +321,4 @@ code: error.code ?? 'UNKNOWN', | ||
set | ||
})`;i(n.toString())?t+=`const r${r} = ${s}; if(r${r} !== null) return mapResponse(r${r}, set) | ||
`:t+=s+"\n"}return Function("inject",t+=`return new Response(error.message, { headers: set.headers, status: error.status ?? 500 }) | ||
})`;l(n.toString())?t+=`const r${r} = ${o}; if(r${r} !== null) return mapResponse(r${r}, set) | ||
`:t+=o+"\n"}return Function("inject",t+=`return new Response(error.message, { headers: set.headers, status: error.status ?? 500 }) | ||
}`)({app:e,mapResponse:r.mapResponse})}; |
@@ -0,1 +1,2 @@ | ||
/// <reference types="bun-types" /> | ||
import type { TypeCheck } from '@sinclair/typebox/compiler'; | ||
@@ -24,2 +25,3 @@ export declare class InternalServerError extends Error { | ||
get all(): import("@sinclair/typebox/compiler").ValueError[]; | ||
toResponse(headers?: Record<string, any>): Response; | ||
} |
@@ -1,1 +0,1 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),function(r,t){for(var e in t)Object.defineProperty(r,e,{enumerable:!0,get:t[e]})}(exports,{InternalServerError:function(){return r},NotFoundError:function(){return t},ParseError:function(){return e},ValidationError:function(){return s}});class r extends Error{code="NOT_FOUND";status=500;constructor(){super("INTERNAL_SERVER_ERROR")}}class t extends Error{code="NOT_FOUND";status=404;constructor(){super("NOT_FOUND")}}class e extends Error{code="PARSE";status=400;constructor(){super("PARSE")}}class s extends Error{validator;value;code;status;constructor(r,t,e){let s=t.Errors(e).First();super(`Invalid ${r}: '${s?.path?.slice(1)||"root"}'. ${s?.message}`),this.validator=t,this.value=e,this.code="VALIDATION",this.status=400}get all(){return[...this.validator.Errors(this.value)]}} | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),function(r,t){for(var e in t)Object.defineProperty(r,e,{enumerable:!0,get:t[e]})}(exports,{InternalServerError:function(){return r},NotFoundError:function(){return t},ParseError:function(){return e},ValidationError:function(){return s}});class r extends Error{code="NOT_FOUND";status=500;constructor(){super("INTERNAL_SERVER_ERROR")}}class t extends Error{code="NOT_FOUND";status=404;constructor(){super("NOT_FOUND")}}class e extends Error{code="PARSE";status=400;constructor(){super("PARSE")}}class s extends Error{validator;value;code;status;constructor(r,t,e){let s=t.Errors(e).First();super(`Invalid ${r}: '${s?.path?.slice(1)||"root"}'. ${s?.message}`),this.validator=t,this.value=e,this.code="VALIDATION",this.status=400}get all(){return[...this.validator.Errors(this.value)]}toResponse(r){return new Response(this.message,{status:400,headers:r})}} |
@@ -421,2 +421,3 @@ /// <reference types="bun-types" /> | ||
handleError: (request: Request, error: Error | ValidationError | ParseError | NotFoundError | InternalServerError, set: Context['set']) => Promise<any>; | ||
private outerErrorHandler; | ||
listen: (options: string | number | Partial<Serve>, callback?: ListenCallback) => this; | ||
@@ -423,0 +424,0 @@ stop: () => Promise<void>; |
@@ -1,4 +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:{},all:""};wsRouter;lazyLoadModules=[];constructor(e){this.config={fn:"/~fn",...e}}add(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)},c=(0,r.mergeHook)(this.event,i),d=(0,o.composeHandler)({path:t,method:e,hooks:c,validator:u,handler:a,handleError:this.handleError,meta:n?this.meta:void 0,onRequest:this.event.request});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}] | ||
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:{},all:""};wsRouter;lazyLoadModules=[];constructor(e){this.config={fn:"/~fn",forceErrorEncapsulation:!1,...e}}add(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)},c=(0,r.mergeHook)(this.event,i),d=(0,o.composeHandler)({path:t,method:e,hooks:c,validator:u,handler:a,handleError:this.handleError,meta:n?this.meta:void 0,onRequest:this.event.request,config:this.config});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"===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 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}`,c=o.wsRouter?.find("subscribe",i);if(c){let e=o.wsRouter.history.find(([e,t])=>i===t);if(!e)return;return this.ws(i,e[2])}this.add(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.add(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.add(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.add("GET",e,t,r),this}post(e,t,r){return this.add("POST",e,t,r),this}put(e,t,r){return this.add("PUT",e,t,r),this}patch(e,t,r){return this.add("PATCH",e,t,r),this}delete(e,t,r){return this.add("DELETE",e,t,r),this}options(e,t,r){return this.add("OPTIONS",e,t,r),this}all(e,t,r){return this.add("ALL",e,t,r),this}head(e,t,r){return this.add("HEAD",e,t,r),this}trace(e,t,r){return this.add("TRACE",e,t,r),this}connect(e,t,r){return this.add("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(),headers:e.request.headers.toJSON(),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.add(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}} | ||
`}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 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}`,c=o.wsRouter?.find("subscribe",i);if(c){let e=o.wsRouter.history.find(([e,t])=>i===t);if(!e)return;return this.ws(i,e[2])}this.add(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.add(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.add(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.add("GET",e,t,r),this}post(e,t,r){return this.add("POST",e,t,r),this}put(e,t,r){return this.add("PUT",e,t,r),this}patch(e,t,r){return this.add("PATCH",e,t,r),this}delete(e,t,r){return this.add("DELETE",e,t,r),this}options(e,t,r){return this.add("OPTIONS",e,t,r),this}all(e,t,r){return this.add("ALL",e,t,r),this}head(e,t,r){return this.add("HEAD",e,t,r),this}trace(e,t,r){return this.add("TRACE",e,t,r),this}connect(e,t,r){return this.add("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(),headers:e.request.headers.toJSON(),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.add(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);outerErrorHandler=e=>new Response(e.message,{status:e?.status??500});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,error:this.outerErrorHandler}:{...this.config.serve,port:e,fetch:r,error:this.outerErrorHandler};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}} |
@@ -191,2 +191,3 @@ /// <reference types="bun-types" /> | ||
serve?: Partial<Serve>; | ||
forceErrorEncapsulation?: boolean; | ||
} | ||
@@ -193,0 +194,0 @@ export type IsPathParameter<Part> = Part extends `:${infer Parameter}` ? Parameter : never; |
@@ -23,3 +23,3 @@ /// <reference types="bun-types" /> | ||
request: { | ||
publish: (topic: string, data: string | import("bun").ArrayBufferView | ArrayBuffer | SharedArrayBuffer, compress?: boolean | undefined) => number; | ||
publish: (topic: string, data: string | ArrayBuffer | SharedArrayBuffer | import("bun").ArrayBufferView, compress?: boolean | undefined) => number; | ||
}; | ||
@@ -26,0 +26,0 @@ schema: {}; |
import type { Elysia } from '.'; | ||
import { SCHEMA, DEFS } from './utils'; | ||
import type { BeforeRequestHandler, ComposedHandler, HTTPMethod, LocalHandler, RegisteredHook, SchemaValidator } from './types'; | ||
import { TAnySchema } from '@sinclair/typebox'; | ||
import type { ElysiaConfig, BeforeRequestHandler, ComposedHandler, HTTPMethod, LocalHandler, RegisteredHook, SchemaValidator } from './types'; | ||
import type { TAnySchema } from '@sinclair/typebox'; | ||
export declare const hasReturn: (fnLiteral: string) => boolean; | ||
export declare const isFnUse: (keyword: string, fnLiteral: string) => boolean; | ||
export declare const findElysiaMeta: (type: string, schema: TAnySchema, found?: string[], parent?: string) => string[] | "root" | null; | ||
export declare const composeHandler: ({ path, method, hooks, validator, handler, handleError, meta, onRequest }: { | ||
export declare const composeHandler: ({ method, hooks, validator, handler, handleError, meta, onRequest, config }: { | ||
path: string; | ||
@@ -17,4 +17,5 @@ method: HTTPMethod; | ||
onRequest: BeforeRequestHandler<any, any>[]; | ||
config: ElysiaConfig; | ||
}) => ComposedHandler; | ||
export declare const composeGeneralHandler: (app: Elysia<any>) => any; | ||
export declare const composeErrorHandler: (app: Elysia<any>) => any; |
@@ -1,2 +0,18 @@ | ||
import{parse as e}from"fast-querystring";import{mapEarlyResponse as r,mapResponse as t,mapCompactResponse as n}from"./handler";import{SCHEMA as s,DEFS as o}from"./utils";import{ParseError as a,NotFoundError as c,ValidationError as i,InternalServerError as l}from"./error";let f="AsyncFunction",d=e=>e.constructor.name===f,u=new Headers,p=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(p))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:p,method:y,hooks:h,validator:m,handler:$,handleError:b,meta:E,onRequest:w})=>{let q="try {\n",g="string"==typeof h.type,x=m||"GET"!==y?[$,...h.transform,...h.beforeHandle,...h.afterHandle].map(e=>e.toString()):[],k="GET"!==y&&(m.body||g||x.some(e=>isFnUse("body",e))),H=m.headers||x.some(e=>isFnUse("headers",e));H&&(q+=u.toJSON?`c.headers = c.request.headers.toJSON() | ||
import{parse as e}from"fast-querystring";import{mapEarlyResponse as r,mapResponse as t,mapCompactResponse as s}from"./handler";import{SCHEMA as n,DEFS as o}from"./utils";import{ParseError as a,NotFoundError as c,ValidationError as l,InternalServerError as i}from"./error";let f="AsyncFunction",u=e=>e.constructor.name===f,d=new Headers,p=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")};let y=e=>({composeValidation:(r,t=`c.${r}`)=>e?`throw new ValidationError( | ||
'${r}', | ||
${r}, | ||
${t} | ||
)`:`return new ValidationError( | ||
'${r}', | ||
${r}, | ||
${t} | ||
).toResponse(c.set.headers)`,composeResponseValidation:(r="r")=>e?`throw new ValidationError( | ||
'response', | ||
response[c.set.status], | ||
${r} | ||
)`:`return new ValidationError( | ||
'response', | ||
response[c.set.status], | ||
${r} | ||
).toResponse(c.set.headers)`});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 s=[t];for(let e of r.matchAll(p))s.push(e[1]);let n=RegExp(`{.*?} = (${s.join("|")})`,"g");for(let[t]of r.matchAll(n))if(t.includes(`{ ${e}`)||t.includes(`, ${e}`))return!0;return!1};export const findElysiaMeta=(e,r,t=[],s="")=>{if("object"===r.type){let n=r.properties;for(let r in n){let o=n[r],a=s?s+"."+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?(s&&t.push(s),"root"):null};export const composeHandler=({method:p,hooks:h,validator:$,handler:m,handleError:b,meta:q,onRequest:E,config:g})=>{let x=g.forceErrorEncapsulation||h.error.length>0||void 0===Bun,{composeValidation:w,composeResponseValidation:k}=y(x),H=x?"try {\n":"",R="string"==typeof h.type,v=$||"GET"!==p?[m,...h.transform,...h.beforeHandle,...h.afterHandle].map(e=>e.toString()):[],O="GET"!==p&&($.body||R||v.some(e=>isFnUse("body",e))),S=$.headers||v.some(e=>isFnUse("headers",e));S&&(H+=d.toJSON?`c.headers = c.request.headers.toJSON() | ||
`:`c.headers = {} | ||
@@ -6,10 +22,5 @@ for (const key of c.request.headers.keys()) | ||
if (headers.Check(h) === false) { | ||
throw throw new ValidationError( | ||
'header', | ||
headers, | ||
h | ||
) | ||
} | ||
`);let R=m.query||x.some(e=>isFnUse("query",e));R&&(q+=`const url = c.request.url | ||
if (headers.Check(c.headers) === false) | ||
${w("headers")} | ||
`);let C=$.query||v.some(e=>isFnUse("query",e));C&&(H+=`const url = c.request.url | ||
@@ -21,3 +32,3 @@ if(c.query !== -1) { | ||
} | ||
`);let v=x.some(e=>isFnUse("set",e))||w.some(e=>isFnUse("set",e.toString())),O=k||$.constructor.name===f||h.parse.length||h.afterHandle.find(d)||h.beforeHandle.find(d)||h.transform.find(d);if(k){let e=m?.body?.schema;if(e&&"anyOf"in e){let r=!1,t=e.anyOf[0].type;for(let n of e.anyOf)if(n.type!==t){r=!0;break}r&&(e=void 0)}if(g||e){if(h.parse.length){q+=(H?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+` | ||
`);let F=v.some(e=>isFnUse("set",e))||E.some(e=>isFnUse("set",e.toString())),N=O||m.constructor.name===f||h.parse.length||h.afterHandle.find(u)||h.beforeHandle.find(u)||h.transform.find(u);if(O){let e=$?.body?.schema;if(e&&"anyOf"in e){let r=!1,t=e.anyOf[0].type;for(let s of e.anyOf)if(s.type!==t){r=!0;break}r&&(e=void 0)}if(R||e){if(h.parse.length){H+=(S?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+` | ||
if (contentType) { | ||
@@ -27,6 +38,6 @@ const index = contentType.indexOf(';') | ||
`+`let used = false | ||
`;for(let e=0;e<h.parse.length;e++){let r=`bo${e}`;0!==e&&(q+=`if(!used) { | ||
`),q+=`let ${r} = parse[${e}](c, contentType);if(${r} instanceof Promise) ${r} = await ${r}; | ||
`;for(let e=0;e<h.parse.length;e++){let r=`bo${e}`;0!==e&&(H+=`if(!used) { | ||
`),H+=`let ${r} = parse[${e}](c, contentType);if(${r} instanceof Promise) ${r} = await ${r}; | ||
if(${r} !== undefined) { c.body = ${r}; used = true } | ||
`,0!==e&&(q+="}")}q+="if (!used) {"}if(e)"object"===e.type?"URLEncoded"===e.elysiaMeta?q+="c.body = parseQuery(await c.request.text())":m.body.Code().includes("custom('File")?q+=`c.body = {} | ||
`,0!==e&&(H+="}")}H+="if (!used) {"}if(e)"object"===e.type?"URLEncoded"===e.elysiaMeta?H+="c.body = parseQuery(await c.request.text())":$.body.Code().includes("custom('File")?H+=`c.body = {} | ||
@@ -43,3 +54,3 @@ await c.request.formData().then((form) => { | ||
} | ||
})`:q+="c.body = JSON.parse(await c.request.text())":q+="c.body = await c.request.text()";else switch(h.type){case"application/json":q+="c.body = JSON.parse(await c.request.text());";break;case"text/plain":q+="c.body = await c.request.text();";break;case"application/x-www-form-urlencoded":q+="c.body = parseQuery(await c.request.text());";break;case"multipart/form-data":q+=`c.body = {} | ||
})`:H+="c.body = JSON.parse(await c.request.text())":H+="c.body = await c.request.text()";else switch(h.type){case"application/json":H+="c.body = JSON.parse(await c.request.text());";break;case"text/plain":H+="c.body = await c.request.text();";break;case"application/x-www-form-urlencoded":H+="c.body = parseQuery(await c.request.text());";break;case"multipart/form-data":H+=`c.body = {} | ||
@@ -54,11 +65,11 @@ for (const key of (await c.request.formData()).keys()) { | ||
else c.body[key] = value | ||
}`}h.parse.length&&(q+="}}")}else{if(q+="\n"+(H?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+` | ||
}`}h.parse.length&&(H+="}}")}else{if(H+="\n"+(S?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+` | ||
if (contentType) { | ||
const index = contentType.indexOf(';') | ||
if (index !== -1) contentType = contentType.substring(0, index) | ||
`,h.parse.length){q+=`let used = false | ||
`;for(let e=0;e<h.parse.length;e++){let r=`bo${e}`;0!==e&&(q+=`if(!used) { | ||
`),q+=`let ${r} = parse[${e}](c, contentType);if(${r} instanceof Promise) ${r} = await ${r}; | ||
`,h.parse.length){H+=`let used = false | ||
`;for(let e=0;e<h.parse.length;e++){let r=`bo${e}`;0!==e&&(H+=`if(!used) { | ||
`),H+=`let ${r} = parse[${e}](c, contentType);if(${r} instanceof Promise) ${r} = await ${r}; | ||
if(${r} !== undefined) { c.body = ${r}; used = true } | ||
`,0!==e&&(q+="}")}q+="if (!used)"}q+=`switch (contentType) { | ||
`,0!==e&&(H+="}")}H+="if (!used)"}H+=`switch (contentType) { | ||
case 'application/json': | ||
@@ -92,59 +103,55 @@ c.body = JSON.parse(await c.request.text()) | ||
} | ||
`}q+="\n"}if(m.params){let e=findElysiaMeta("Numeric",m.params.schema);if(e){if("object"==typeof e)for(let r of e)q+=`c.params.${r} = +c.params.${r};`;q+="\n"}}if(m.query){let e=findElysiaMeta("Numeric",m.query.schema);if(e){if("object"==typeof e)for(let r of e)q+=`c.query.${r} = +c.query.${r};`;q+="\n"}}if(m.headers){let e=findElysiaMeta("Numeric",m.headers.schema);if(e){if("object"==typeof e)for(let r of e)q+=`c.headers.${r} = +c.headers.${r};`;q+="\n"}}if(m.body){let e=findElysiaMeta("Numeric",m.body.schema);if(e){switch(typeof e){case"string":q+="c.body = +c.body;";break;case"object":for(let r of e)q+=`c.body.${r} = +c.body.${r};`}q+="\n"}}if(h?.transform)for(let e=0;e<h.transform.length;e++){let r=h.transform[e];"derive"===r.$elysia?q+=h.transform[e].constructor.name===f?`Object.assign(c, await transform[${e}](c));`:`Object.assign(c, transform[${e}](c));`:q+=h.transform[e].constructor.name===f?`await transform[${e}](c);`:`transform[${e}](c);`}if(m&&(m.headers&&(q+=` | ||
`}H+="\n"}if($.params){let e=findElysiaMeta("Numeric",$.params.schema);if(e){if("object"==typeof e)for(let r of e)H+=`c.params.${r} = +c.params.${r};`;H+="\n"}}if($.query){let e=findElysiaMeta("Numeric",$.query.schema);if(e){if("object"==typeof e)for(let r of e)H+=`c.query.${r} = +c.query.${r};`;H+="\n"}}if($.headers){let e=findElysiaMeta("Numeric",$.headers.schema);if(e){if("object"==typeof e)for(let r of e)H+=`c.headers.${r} = +c.headers.${r};`;H+="\n"}}if($.body){let e=findElysiaMeta("Numeric",$.body.schema);if(e){switch(typeof e){case"string":H+="c.body = +c.body;";break;case"object":for(let r of e)H+=`c.body.${r} = +c.body.${r};`}H+="\n"}}if(h?.transform)for(let e=0;e<h.transform.length;e++){let r=h.transform[e];"derive"===r.$elysia?H+=h.transform[e].constructor.name===f?`Object.assign(c, await transform[${e}](c));`:`Object.assign(c, transform[${e}](c));`:H+=h.transform[e].constructor.name===f?`await transform[${e}](c);`:`transform[${e}](c);`}if($&&($.headers&&(H+=` | ||
if (headers.Check(c.headers) === false) { | ||
throw new ValidationError( | ||
'header', | ||
headers, | ||
c.headers | ||
) | ||
${w("headers")} | ||
} | ||
`),m.params&&(q+="if(params.Check(c.params) === false) { throw new ValidationError('params', params, c.params) }"),m.query&&(q+="if(query.Check(c.query) === false) { throw new ValidationError('query', query, c.query) }"),m.body&&(q+="if(body.Check(c.body) === false) { throw new ValidationError('body', body, c.body) }")),h?.beforeHandle)for(let e=0;e<h.beforeHandle.length;e++){let r=`be${e}`,t=hasReturn(h.beforeHandle[e].toString());if(t){if(q+=(h.beforeHandle[e].constructor.name===f?`let ${r} = await beforeHandle[${e}](c); | ||
`),$.params&&(H+=`if(params.Check(c.params) === false) { ${w("params")} }`),$.query&&(H+=`if(query.Check(c.query) === false) { ${w("query")} }`),$.body&&(H+=`if(body.Check(c.body) === false) { ${w("body")} }`)),h?.beforeHandle)for(let e=0;e<h.beforeHandle.length;e++){let r=`be${e}`,t=hasReturn(h.beforeHandle[e].toString());if(t){if(H+=(h.beforeHandle[e].constructor.name===f?`let ${r} = await beforeHandle[${e}](c); | ||
`:`let ${r} = beforeHandle[${e}](c); | ||
`)+`if(${r} !== undefined) { | ||
`,h?.afterHandle)for(let e=0;e<h.afterHandle.length;e++){let t=hasReturn(h.afterHandle[e].toString());if(t){let t=`af${e}`;q+=(h.afterHandle[e].constructor.name===f?`const ${t} = await afterHandle[${e}](c, ${r}); | ||
`,h?.afterHandle)for(let e=0;e<h.afterHandle.length;e++){let t=hasReturn(h.afterHandle[e].toString());if(t){let t=`af${e}`;H+=(h.afterHandle[e].constructor.name===f?`const ${t} = await afterHandle[${e}](c, ${r}); | ||
`:`const ${t} = afterHandle[${e}](c, ${r}); | ||
`)+`if(${t} !== undefined) { ${r} = ${t} } | ||
`}else q+=h.afterHandle[e].constructor.name===f?`await afterHandle[${e}](c, ${r}); | ||
`}else H+=h.afterHandle[e].constructor.name===f?`await afterHandle[${e}](c, ${r}); | ||
`:`afterHandle[${e}](c, ${r}); | ||
`}m.response&&(q+=`if(response[c.set.status]?.Check(${r}) === false) { | ||
`}$.response&&(H+=`if(response[c.set.status]?.Check(${r}) === false) { | ||
if(!(response instanceof Error)) | ||
throw new ValidationError('response', response[c.set.status], ${r}) | ||
${k(r)} | ||
} | ||
`),q+=`return mapEarlyResponse(${r}, c.set)} | ||
`}else q+=h.beforeHandle[e].constructor.name===f?`await beforeHandle[${e}](c); | ||
`),H+=`return mapEarlyResponse(${r}, c.set)} | ||
`}else H+=h.beforeHandle[e].constructor.name===f?`await beforeHandle[${e}](c); | ||
`:`beforeHandle[${e}](c); | ||
`}if(h?.afterHandle.length){q+=$.constructor.name===f?`let r = await handler(c); | ||
`}if(h?.afterHandle.length){H+=m.constructor.name===f?`let r = await handler(c); | ||
`:`let r = handler(c); | ||
`;for(let e=0;e<h.afterHandle.length;e++){let r=`af${e}`,t=hasReturn(h.afterHandle[e].toString());t?(q+=h.afterHandle[e].constructor.name===f?`let ${r} = await afterHandle[${e}](c, r) | ||
`;for(let e=0;e<h.afterHandle.length;e++){let r=`af${e}`,t=hasReturn(h.afterHandle[e].toString());t?(H+=h.afterHandle[e].constructor.name===f?`let ${r} = await afterHandle[${e}](c, r) | ||
`:`let ${r} = afterHandle[${e}](c, r) | ||
`,m.response?q+=`if(response[c.set.status]?.Check(${r}) === false) { | ||
`,$.response?H+=`if(response[c.set.status]?.Check(${r}) === false) { | ||
if(!(response instanceof Error)) | ||
throw new ValidationError('response', response[c.set.status], ${r}) | ||
${k(r)} | ||
} | ||
${r} = mapEarlyResponse(${r}, c.set) | ||
if(${r}) return ${r}; | ||
`:q+=`if(${r}) return ${r}; | ||
`):q+=h.afterHandle[e].constructor.name===f?`await afterHandle[${e}](c, r) | ||
`:H+=`if(${r}) return ${r}; | ||
`):H+=h.afterHandle[e].constructor.name===f?`await afterHandle[${e}](c, r) | ||
`:`afterHandle[${e}](c, r) | ||
`}m.response&&(q+=`if(response[c.set.status]?.Check(r) === false) { | ||
`}$.response&&(H+=`if(response[c.set.status]?.Check(r) === false) { | ||
if(!(response instanceof Error)) | ||
throw new ValidationError('response', response[c.set.status], r) | ||
${k()} | ||
} | ||
`),v?q+=`return mapResponse(r, c.set) | ||
`:q+=`return mapCompactResponse(r) | ||
`}else if(m.response)q+=($.constructor.name===f?`const r = await handler(c); | ||
`),F?H+=`return mapResponse(r, c.set) | ||
`:H+=`return mapCompactResponse(r) | ||
`}else if($.response)H+=(m.constructor.name===f?`const r = await handler(c); | ||
`:`const r = handler(c); | ||
`)+`if(response[c.set.status]?.Check(r) === false) { | ||
if(!(response instanceof Error)) | ||
throw new ValidationError('response', response[c.set.status], r) | ||
${k()} | ||
} | ||
`,v?q+=`return mapResponse(r, c.set) | ||
`:q+=`return mapCompactResponse(r) | ||
`;else{let e=$.constructor.name===f?"await handler(c) ":"handler(c)";v?q+=`return mapResponse(${e}, c.set) | ||
`:q+=`return mapCompactResponse(${e}) | ||
`}q+=` | ||
`,F?H+=`return mapResponse(r, c.set) | ||
`:H+=`return mapCompactResponse(r) | ||
`;else{let e=m.constructor.name===f?"await handler(c) ":"handler(c)";F?H+=`return mapResponse(${e}, c.set) | ||
`:H+=`return mapCompactResponse(${e}) | ||
`}x&&(H+=` | ||
} catch(error) { | ||
${O?"":"return (async () => {"} | ||
${N?"":"return (async () => {"} | ||
const set = c.set | ||
@@ -168,4 +175,4 @@ | ||
return handleError(c.request, error, set) | ||
${O?"":"})()"} | ||
}`,q=`const { | ||
${N?"":"})()"} | ||
}`),H=`const { | ||
handler, | ||
@@ -191,3 +198,2 @@ handleError, | ||
mapEarlyResponse, | ||
mapErrorCode, | ||
parseQuery | ||
@@ -201,3 +207,3 @@ }, | ||
}, | ||
${E?` | ||
${q?` | ||
meta, | ||
@@ -210,6 +216,7 @@ SCHEMA, | ||
return ${O?"async":""} function(c) { | ||
${E?"c[SCHEMA] = meta[SCHEMA]; c[DEFS] = meta[DEFS];":""} | ||
${q} | ||
}`;let C=Function("hooks",q);return C({handler:$,hooks:h,validator:m,handleError:b,utils:{mapResponse:t,mapCompactResponse:n,mapEarlyResponse:r,parseQuery:e},error:{ParseError:a,NotFoundError:c,ValidationError:i,InternalServerError:l},meta:E,SCHEMA:E?s:void 0,DEFS:E?o:void 0})};export const composeGeneralHandler=e=>{let t="";for(let r of Object.keys(e.decorators))t+=`,${r}: app.decorators.${r}`;let{router:n,staticRouter:s}=e,o=`const route = find(method, path) ${n.root.ALL?'?? find("ALL", path)':""} | ||
return ${N?"async":""} function(c) { | ||
${q?"c[SCHEMA] = meta[SCHEMA]; c[DEFS] = meta[DEFS];":""} | ||
${H} | ||
}`;let T=Function("hooks",H);return T({handler:m,hooks:h,validator:$,handleError:b,utils:{mapResponse:t,mapCompactResponse:s,mapEarlyResponse:r,parseQuery:e},error:{ParseError:a,NotFoundError:c,ValidationError:l,InternalServerError:i},meta:q,SCHEMA:q?n:void 0,DEFS:q?o:void 0})};export const composeGeneralHandler=e=>{let t="";for(let r of Object.keys(e.decorators))t+=`,${r}: app.decorators.${r}`;let{router:s,staticRouter:n}=e,o=` | ||
const route = find(request.method, path) ${s.root.ALL?'?? find("ALL", path)':""} | ||
if (route === null) | ||
@@ -226,8 +233,8 @@ return ${e.event.error.length?`handleError( | ||
return route.store(ctx)`,a="";for(let[e,{code:r,all:t}]of Object.entries(s.map))a+=`case '${e}': | ||
switch(method) { | ||
return route.store(ctx)`,a="";for(let[e,{code:r,all:t}]of Object.entries(n.map))a+=`case '${e}': | ||
switch(request.method) { | ||
${r} | ||
${t??"default:\n"+o}} | ||
${t??`default: ${o}`}} | ||
`;let i=`const { | ||
`;let l=`const { | ||
app, | ||
@@ -243,3 +250,3 @@ app: { store, router, staticRouter }, | ||
${s.variables} | ||
${n.variables} | ||
@@ -252,5 +259,34 @@ const find = router.find.bind(router) | ||
return function(request) { | ||
`;if(e.event.request.length){l+=` | ||
const ctx = { | ||
request, | ||
store, | ||
set: { | ||
headers: {}, | ||
status: 200 | ||
} | ||
${t} | ||
} | ||
try { | ||
`;for(let r=0;r<e.event.request.length;r++){let t=hasReturn(e.event.request[r].toString());l+=t?`const response = mapEarlyResponse( | ||
onRequest[${r}](ctx), | ||
ctx.set | ||
) | ||
if (response) return response | ||
`:`mapEarlyResponse(onRequest[${r}](ctx), ctx.set)`}l+=`} catch (error) { | ||
return handleError(request, error, ctx.set) | ||
} | ||
const url = request.url, | ||
s = url.indexOf('/', 12), | ||
i = ctx.query = url.indexOf('?', s + 1), | ||
path = i === -1 ? url.substring(s) : url.substring(s, i);`}else l+=` | ||
const url = request.url, | ||
s = url.indexOf('/', 12) | ||
const ctx = { | ||
request, | ||
store, | ||
query: url.indexOf('?', s + 1), | ||
set: { | ||
@@ -262,21 +298,14 @@ headers: {}, | ||
} | ||
`;if(e.event.request.length){i+="try {";for(let r=0;r<e.event.request.length;r++){let t=hasReturn(e.event.request[r].toString());i+=t?`const response = mapEarlyResponse( | ||
onRequest[${r}](ctx), | ||
ctx.set | ||
) | ||
if (response) return response | ||
`:`mapEarlyResponse(onRequest[${r}](ctx), ctx.set)`}i+=`} catch (error) { | ||
return handleError(request, error, ctx.set) | ||
}`}return i+=` | ||
const { url, method } = request, | ||
s = url.indexOf('/', 12), | ||
i = ctx.query = url.indexOf('?', s + 1), | ||
path = i === -1 ? url.substring(s) : url.substring(s, i) | ||
const path = | ||
ctx.query === -1 | ||
? url.substring(s) | ||
: url.substring(s, ctx.query);`;return l+=` | ||
switch(path) { | ||
${a} | ||
default: ${o} | ||
default: | ||
${o} | ||
} | ||
}`,e.handleError=composeErrorHandler(e),Function("data",i)({app:e,mapEarlyResponse:r,NotFoundError:c})};export const composeErrorHandler=e=>{let r=`const { | ||
}`,e.handleError=composeErrorHandler(e),Function("data",l)({app:e,mapEarlyResponse:r,NotFoundError:c})};export const composeErrorHandler=e=>{let r=`const { | ||
app: { event: { error: onError } }, | ||
@@ -286,3 +315,3 @@ mapResponse | ||
return ${e.event.error.find(e=>e.constructor.name===f)?"async":""} function(request, error, set) {`;for(let t=0;t<e.event.error.length;t++){let n=e.event.error[t],s=`${n.constructor.name===f?"await ":""}onError[${t}]({ | ||
return ${e.event.error.find(e=>e.constructor.name===f)?"async":""} function(request, error, set) {`;for(let t=0;t<e.event.error.length;t++){let s=e.event.error[t],n=`${s.constructor.name===f?"await ":""}onError[${t}]({ | ||
request, | ||
@@ -292,4 +321,4 @@ code: error.code ?? 'UNKNOWN', | ||
set | ||
})`;hasReturn(n.toString())?r+=`const r${t} = ${s}; if(r${t} !== null) return mapResponse(r${t}, set) | ||
`:r+=s+"\n"}return Function("inject",r+=`return new Response(error.message, { headers: set.headers, status: error.status ?? 500 }) | ||
})`;hasReturn(s.toString())?r+=`const r${t} = ${n}; if(r${t} !== null) return mapResponse(r${t}, set) | ||
`:r+=n+"\n"}return Function("inject",r+=`return new Response(error.message, { headers: set.headers, status: error.status ?? 500 }) | ||
}`)({app:e,mapResponse:t})}; |
@@ -0,1 +1,2 @@ | ||
/// <reference types="bun-types" /> | ||
import type { TypeCheck } from '@sinclair/typebox/compiler'; | ||
@@ -24,2 +25,3 @@ export declare class InternalServerError extends Error { | ||
get all(): import("@sinclair/typebox/compiler").ValueError[]; | ||
toResponse(headers?: Record<string, any>): Response; | ||
} |
@@ -1,1 +0,1 @@ | ||
export class InternalServerError extends Error{code="NOT_FOUND";status=500;constructor(){super("INTERNAL_SERVER_ERROR")}}export class NotFoundError extends Error{code="NOT_FOUND";status=404;constructor(){super("NOT_FOUND")}}export class ParseError extends Error{code="PARSE";status=400;constructor(){super("PARSE")}}export class ValidationError extends Error{validator;value;code;status;constructor(r,t,s){let o=t.Errors(s).First();super(`Invalid ${r}: '${o?.path?.slice(1)||"root"}'. ${o?.message}`),this.validator=t,this.value=s,this.code="VALIDATION",this.status=400}get all(){return[...this.validator.Errors(this.value)]}} | ||
export class InternalServerError extends Error{code="NOT_FOUND";status=500;constructor(){super("INTERNAL_SERVER_ERROR")}}export class NotFoundError extends Error{code="NOT_FOUND";status=404;constructor(){super("NOT_FOUND")}}export class ParseError extends Error{code="PARSE";status=400;constructor(){super("PARSE")}}export class ValidationError extends Error{validator;value;code;status;constructor(r,s,t){let e=s.Errors(t).First();super(`Invalid ${r}: '${e?.path?.slice(1)||"root"}'. ${e?.message}`),this.validator=s,this.value=t,this.code="VALIDATION",this.status=400}get all(){return[...this.validator.Errors(this.value)]}toResponse(r){return new Response(this.message,{status:400,headers:r})}} |
@@ -421,2 +421,3 @@ /// <reference types="bun-types" /> | ||
handleError: (request: Request, error: Error | ValidationError | ParseError | NotFoundError | InternalServerError, set: Context['set']) => Promise<any>; | ||
private outerErrorHandler; | ||
listen: (options: string | number | Partial<Serve>, callback?: ListenCallback) => this; | ||
@@ -423,0 +424,0 @@ stop: () => Promise<void>; |
@@ -1,4 +0,4 @@ | ||
import{Memoirist as e}from"memoirist";import{SCHEMA as t,EXPOSED as r,DEFS as s,mergeHook as o,getSchemaValidator as i,getResponseSchemaValidator as a,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}}add(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:i(u?.body??this.$schema?.body,c),headers:i(u?.headers??this.$schema?.headers,c,!0),params:i(u?.params??this.$schema?.params,c),query:i(u?.query??this.$schema?.query,c),response:a(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,onRequest:this.event.request});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}] | ||
import{Memoirist as e}from"memoirist";import{SCHEMA as t,EXPOSED as r,DEFS as s,mergeHook as o,getSchemaValidator as i,getResponseSchemaValidator as a,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",forceErrorEncapsulation:!1,...e}}add(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:i(u?.body??this.$schema?.body,c),headers:i(u?.headers??this.$schema?.headers,c,!0),params:i(u?.params??this.$schema?.params,c),query:i(u?.query??this.$schema?.query,c),response:a(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,onRequest:this.event.request,config:this.config});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"===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 i=new p;i.store=this.store,this.wsRouter&&i.use(c());let a="object"==typeof t,n=(a?r:t)(i);return this.decorators=h(this.decorators,i.decorators),n.event.request.length&&(this.event.request=[...this.event.request,...n.event.request]),this.model(n.meta[s]),Object.values(i.routes).forEach(({method:r,path:s,handler:h,hooks:u})=>{if(a){let a=`${e}${s}`,d=i.wsRouter?.find("subscribe",a);if(d){let e=i.wsRouter.history.find(([e,t])=>a===t);if(!e)return;return this.ws(a,e[2])}this.add(r,a,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}`,a=i.wsRouter?.find("subscribe",t);if(a){let e=i.wsRouter.history.find(([e,t])=>s===t);if(!e)return;return this.ws(t,e[2])}this.add(r,t,h,o(u,{error:n.event.error}))}}),i.wsRouter&&this.wsRouter&&i.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 i=t(r);return this.decorators=h(this.decorators,r.decorators),i.event.request.length&&(this.event.request=[...this.event.request,...i.event.request]),this.model(i.meta[s]),Object.values(r.routes).forEach(({method:t,path:s,handler:a,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.add(t,s,a,o(e,{...h,error:h.error?Array.isArray(h.error)?[...h.error,...i.event.error]:[h.error,...i.event.error]:i.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.add("GET",e,t,r),this}post(e,t,r){return this.add("POST",e,t,r),this}put(e,t,r){return this.add("PUT",e,t,r),this}patch(e,t,r){return this.add("PATCH",e,t,r),this}delete(e,t,r){return this.add("DELETE",e,t,r),this}options(e,t,r){return this.add("OPTIONS",e,t,r),this}all(e,t,r){return this.add("ALL",e,t,r),this}head(e,t,r){return this.add("HEAD",e,t,r),this}trace(e,t,r){return this.add("TRACE",e,t,r),this}connect(e,t,r){return this.add("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(),headers:e.request.headers.toJSON(),message:i(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.add(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:i(e.body,t),headers:i(e?.headers,t,!0),params:i(e?.params,t),query:i(e?.query,t),response:i(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}; | ||
`}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 i=new p;i.store=this.store,this.wsRouter&&i.use(c());let a="object"==typeof t,n=(a?r:t)(i);return this.decorators=h(this.decorators,i.decorators),n.event.request.length&&(this.event.request=[...this.event.request,...n.event.request]),this.model(n.meta[s]),Object.values(i.routes).forEach(({method:r,path:s,handler:h,hooks:u})=>{if(a){let a=`${e}${s}`,d=i.wsRouter?.find("subscribe",a);if(d){let e=i.wsRouter.history.find(([e,t])=>a===t);if(!e)return;return this.ws(a,e[2])}this.add(r,a,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}`,a=i.wsRouter?.find("subscribe",t);if(a){let e=i.wsRouter.history.find(([e,t])=>s===t);if(!e)return;return this.ws(t,e[2])}this.add(r,t,h,o(u,{error:n.event.error}))}}),i.wsRouter&&this.wsRouter&&i.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 i=t(r);return this.decorators=h(this.decorators,r.decorators),i.event.request.length&&(this.event.request=[...this.event.request,...i.event.request]),this.model(i.meta[s]),Object.values(r.routes).forEach(({method:t,path:s,handler:a,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.add(t,s,a,o(e,{...h,error:h.error?Array.isArray(h.error)?[...h.error,...i.event.error]:[h.error,...i.event.error]:i.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.add("GET",e,t,r),this}post(e,t,r){return this.add("POST",e,t,r),this}put(e,t,r){return this.add("PUT",e,t,r),this}patch(e,t,r){return this.add("PATCH",e,t,r),this}delete(e,t,r){return this.add("DELETE",e,t,r),this}options(e,t,r){return this.add("OPTIONS",e,t,r),this}all(e,t,r){return this.add("ALL",e,t,r),this}head(e,t,r){return this.add("HEAD",e,t,r),this}trace(e,t,r){return this.add("TRACE",e,t,r),this}connect(e,t,r){return this.add("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(),headers:e.request.headers.toJSON(),message:i(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.add(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:i(e.body,t),headers:i(e?.headers,t,!0),params:i(e?.params,t),query:i(e?.query,t),response:i(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);outerErrorHandler=e=>new Response(e.message,{status:e?.status??500});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,error:this.outerErrorHandler}:{...this.config.serve,port:e,fetch:r,error:this.outerErrorHandler};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}; |
@@ -191,2 +191,3 @@ /// <reference types="bun-types" /> | ||
serve?: Partial<Serve>; | ||
forceErrorEncapsulation?: boolean; | ||
} | ||
@@ -193,0 +194,0 @@ export type IsPathParameter<Part> = Part extends `:${infer Parameter}` ? Parameter : never; |
@@ -23,3 +23,3 @@ /// <reference types="bun-types" /> | ||
request: { | ||
publish: (topic: string, data: string | import("bun").ArrayBufferView | ArrayBuffer | SharedArrayBuffer, compress?: boolean | undefined) => number; | ||
publish: (topic: string, data: string | ArrayBuffer | SharedArrayBuffer | import("bun").ArrayBufferView, compress?: boolean | undefined) => number; | ||
}; | ||
@@ -26,0 +26,0 @@ schema: {}; |
{ | ||
"name": "elysia", | ||
"description": "Fast, and friendly Bun web framework", | ||
"version": "0.5.3", | ||
"version": "0.5.4", | ||
"author": { | ||
@@ -6,0 +6,0 @@ "name": "saltyAom", |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Uses eval
Supply chain riskPackage uses dynamic code execution (e.g., eval()), which is a dangerous practice. This can prevent the code from running in certain environments and increases the risk that the code may contain exploits or malicious behavior.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Uses eval
Supply chain riskPackage uses dynamic code execution (e.g., eval()), which is a dangerous practice. This can prevent the code from running in certain environments and increases the risk that the code may contain exploits or malicious behavior.
Found 1 instance in 1 package
199398
2464