elysia 0.5.8 → 0.5.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/compose.js +13 -12
- package/dist/cjs/index.js +2 -2
- package/dist/cjs/types.d.ts +3 -2
- package/dist/compose.js +43 -42
- package/dist/index.js +2 -2
- package/dist/types.d.ts +3 -2
- package/package.json +2 -2
package/dist/cjs/compose.js
CHANGED
|
@@ -14,21 +14,18 @@ ${r}
|
|
|
14
14
|
'response',
|
|
15
15
|
response[c.set.status],
|
|
16
16
|
${r}
|
|
17
|
-
).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:
|
|
17
|
+
).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:m,onRequest:h,config:b})=>{let E=b.forceErrorEncapsulation||d.error.length>0||"undefined"==typeof 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&&"none"!==d.type&&(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()
|
|
18
18
|
`:`c.headers = {}
|
|
19
|
-
for (const key of c.request.headers.
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
if (headers.Check(c.headers) === false)
|
|
23
|
-
${q("headers")}
|
|
24
|
-
`);let v=p.query||k.some(e=>u("query",e));v&&(w+=`const url = c.request.url
|
|
19
|
+
for (const [key, value] of c.request.headers.entries())
|
|
20
|
+
c.headers[key] = value
|
|
21
|
+
`);let v=p.query||k.some(e=>u("query",e));v&&(w+=`const url = c.request.url
|
|
25
22
|
|
|
26
23
|
if(c.query !== -1) {
|
|
27
24
|
c.query = parseQuery(url.substring(c.query + 1))
|
|
28
25
|
} else {
|
|
29
26
|
c.query = {}
|
|
30
27
|
}
|
|
31
|
-
`);let O=k.some(e=>u("set",e))||
|
|
28
|
+
`);let O=k.some(e=>u("set",e))||h.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')")+`
|
|
32
29
|
if (contentType) {
|
|
33
30
|
const index = contentType.indexOf(';')
|
|
34
31
|
if (index !== -1) contentType = contentType.substring(0, index)
|
|
@@ -48,7 +45,7 @@ ${r}
|
|
|
48
45
|
c.body[key] = value[0]
|
|
49
46
|
else c.body[key] = value
|
|
50
47
|
}
|
|
51
|
-
})`: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 = {}
|
|
48
|
+
})`: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"application/octet-stream":w+="c.body = await c.request.arrayBuffer();";break;case"multipart/form-data":w+=`c.body = {}
|
|
52
49
|
|
|
53
50
|
for (const key of (await c.request.formData()).keys()) {
|
|
54
51
|
if (c.body[key])
|
|
@@ -79,6 +76,10 @@ ${r}
|
|
|
79
76
|
c.body = parseQuery(await c.request.text())
|
|
80
77
|
break
|
|
81
78
|
|
|
79
|
+
case 'application/octet-stream':
|
|
80
|
+
c.body = await c.request.arrayBuffer();
|
|
81
|
+
break
|
|
82
|
+
|
|
82
83
|
case 'multipart/form-data':
|
|
83
84
|
c.body = {}
|
|
84
85
|
|
|
@@ -196,7 +197,7 @@ if(${r}) return ${r};
|
|
|
196
197
|
ValidationError,
|
|
197
198
|
InternalServerError
|
|
198
199
|
},
|
|
199
|
-
${
|
|
200
|
+
${m?`
|
|
200
201
|
meta,
|
|
201
202
|
SCHEMA,
|
|
202
203
|
DEFS,`:""}
|
|
@@ -205,9 +206,9 @@ if(${r}) return ${r};
|
|
|
205
206
|
const parseError = new ParseError()
|
|
206
207
|
|
|
207
208
|
return ${S?"async":""} function(c) {
|
|
208
|
-
${
|
|
209
|
+
${m?"c[SCHEMA] = meta[SCHEMA]; c[DEFS] = meta[DEFS];":""}
|
|
209
210
|
${w}
|
|
210
|
-
}`;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:
|
|
211
|
+
}`;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:m,SCHEMA:m?t.SCHEMA:void 0,DEFS:m?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=`
|
|
211
212
|
const route = find(request.method, path) ${s.root.ALL?'?? find("ALL", path)':""}
|
|
212
213
|
if (route === null)
|
|
213
214
|
return ${e.event.error.length?`handleError(
|
package/dist/cjs/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
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),
|
|
1
|
+
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,basePath:"",...e}}add(e,t,a,i,{allowMeta:n=!1}={allowMeta:!1}){t=""===t?t:47===t.charCodeAt(0)?t:`/${t}`,this.config.basePath&&this.config.basePath,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";break;case"arrayBuffer":i.type="application/octet-stream"}(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),l=(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(l),this.staticRouter.variables+=`const st${r} = staticRouter.handlers[${r}]
|
|
2
2
|
`,this.staticRouter.map[t]||(this.staticRouter.map[t]={code:""}),"ALL"===e?this.staticRouter.map[t].all=`default: return st${r}(ctx)
|
|
3
3
|
`:this.staticRouter.map[t].code+=`case '${e}': return st${r}(ctx)
|
|
4
|
-
`}else this.router.add(e,t,
|
|
4
|
+
`}else this.router.add(e,t,l)}onStart(e){return this.event.start.push(e),this}onRequest(e){return this.event.request.push(e),this}onParse(e){return this.event.parse.splice(this.event.parse.length-1,0,e),this}onTransform(e){return this.event.transform.push(e),this}onBeforeHandle(e){return this.event.beforeHandle.push(e),this}onAfterHandle(e){return this.event.afterHandle.push(e),this}onError(e){return this.event.error.push(e),this}onStop(e){return this.event.stop.push(e),this}on(e,t){switch(e){case"start":this.event.start.push(t);break;case"request":this.event.request.push(t);break;case"parse":this.event.parse.push(t);break;case"transform":this.event.transform.push(t);break;case"beforeHandle":this.event.beforeHandle.push(t);break;case"afterHandle":this.event.afterHandle.push(t);break;case"error":this.event.error.push(t);break;case"stop":this.event.stop.push(t)}return this}group(e,t,s){let o=new h;o.store=this.store,this.wsRouter&&o.use((0,a.ws)());let i="object"==typeof t,n=(i?s:t)(o);return this.decorators=(0,r.mergeDeep)(this.decorators,o.decorators),n.event.request.length&&(this.event.request=[...this.event.request,...n.event.request]),this.model(n.meta[r.DEFS]),Object.values(o.routes).forEach(({method:s,path:a,handler:h,hooks:u})=>{if(i){let i=`${e}${a}`,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}}
|
package/dist/cjs/types.d.ts
CHANGED
|
@@ -127,7 +127,7 @@ export type MergeSchema<A extends TypedSchema, B extends TypedSchema> = {
|
|
|
127
127
|
response: NotUndefined<A['response']> extends true ? A['response'] : NotUndefined<B['response']> extends true ? B['response'] : undefined;
|
|
128
128
|
};
|
|
129
129
|
type MaybeArray<T> = T | T[];
|
|
130
|
-
type ContentType = MaybeArray<(string & {}) | 'text' | 'json' | 'formdata' | 'urlencoded' | 'text/plain' | 'application/json' | 'multipart/form-data' | 'application/x-www-form-urlencoded'>;
|
|
130
|
+
type ContentType = MaybeArray<(string & {}) | 'none' | 'text' | 'json' | 'formdata' | 'urlencoded' | 'arrayBuffer' | 'text/plain' | 'application/json' | 'multipart/form-data' | 'application/x-www-form-urlencoded'>;
|
|
131
131
|
export type LocalHook<Schema extends TypedSchema, Instance extends ElysiaInstance<any>, Path extends string = string> = Partial<Schema> & {
|
|
132
132
|
type?: ContentType;
|
|
133
133
|
detail?: Partial<OpenAPIV3.OperationObject>;
|
|
@@ -188,9 +188,10 @@ export type ComposedHandler = (context: Context) => MaybePromise<Response>;
|
|
|
188
188
|
export interface ElysiaConfig {
|
|
189
189
|
fn?: string;
|
|
190
190
|
serve?: Partial<Serve>;
|
|
191
|
+
basePath?: string;
|
|
191
192
|
forceErrorEncapsulation?: boolean;
|
|
192
193
|
}
|
|
193
|
-
export type IsPathParameter<Part> = Part extends `:${infer Parameter}` ? Parameter : never;
|
|
194
|
+
export type IsPathParameter<Part> = Part extends `:${infer Parameter}` ? Parameter : Part extends `*` ? '*' : never;
|
|
194
195
|
export type ExtractPath<Path> = Path extends `${infer A}/${infer B}` ? IsPathParameter<A> | ExtractPath<B> : IsPathParameter<Path>;
|
|
195
196
|
export interface InternalRoute<Instance extends ElysiaInstance> {
|
|
196
197
|
method: HTTPMethod;
|
package/dist/compose.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
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
|
|
1
|
+
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 i,InternalServerError as l}from"./error";let u="AsyncFunction",f=e=>e.constructor.name===u,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(
|
|
2
2
|
'${r}',
|
|
3
3
|
${r},
|
|
4
4
|
${t}
|
|
@@ -14,29 +14,26 @@ ${r}
|
|
|
14
14
|
'response',
|
|
15
15
|
response[c.set.status],
|
|
16
16
|
${r}
|
|
17
|
-
).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,
|
|
17
|
+
).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:$,validator:h,handler:m,handleError:b,meta:q,onRequest:E,config:g})=>{let w=g.forceErrorEncapsulation||$.error.length>0||"undefined"==typeof Bun,{composeValidation:x,composeResponseValidation:k}=y(w),H=w?"try {\n":"",R="string"==typeof $.type,v=h||"GET"!==p?[m,...$.transform,...$.beforeHandle,...$.afterHandle].map(e=>e.toString()):[],O="GET"!==p&&"none"!==$.type&&(h.body||R||v.some(e=>isFnUse("body",e))),S=h.headers||v.some(e=>isFnUse("headers",e));S&&(H+=d.toJSON?`c.headers = c.request.headers.toJSON()
|
|
18
18
|
`:`c.headers = {}
|
|
19
|
-
for (const key of c.request.headers.
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
if (headers.Check(c.headers) === false)
|
|
23
|
-
${w("headers")}
|
|
24
|
-
`);let C=$.query||v.some(e=>isFnUse("query",e));C&&(H+=`const url = c.request.url
|
|
19
|
+
for (const [key, value] of c.request.headers.entries())
|
|
20
|
+
c.headers[key] = value
|
|
21
|
+
`);let F=h.query||v.some(e=>isFnUse("query",e));F&&(H+=`const url = c.request.url
|
|
25
22
|
|
|
26
23
|
if(c.query !== -1) {
|
|
27
24
|
c.query = parseQuery(url.substring(c.query + 1))
|
|
28
25
|
} else {
|
|
29
26
|
c.query = {}
|
|
30
27
|
}
|
|
31
|
-
`);let
|
|
28
|
+
`);let C=v.some(e=>isFnUse("set",e))||E.some(e=>isFnUse("set",e.toString())),N=O||m.constructor.name===u||$.parse.length||$.afterHandle.find(f)||$.beforeHandle.find(f)||$.transform.find(f);if(O){let e=h?.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($.parse.length){H+=(S?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+`
|
|
32
29
|
if (contentType) {
|
|
33
30
|
const index = contentType.indexOf(';')
|
|
34
31
|
if (index !== -1) contentType = contentType.substring(0, index)
|
|
35
32
|
`+`let used = false
|
|
36
|
-
`;for(let e=0;e
|
|
33
|
+
`;for(let e=0;e<$.parse.length;e++){let r=`bo${e}`;0!==e&&(H+=`if(!used) {
|
|
37
34
|
`),H+=`let ${r} = parse[${e}](c, contentType);if(${r} instanceof Promise) ${r} = await ${r};
|
|
38
35
|
if(${r} !== undefined) { c.body = ${r}; used = true }
|
|
39
|
-
`,0!==e&&(H+="}")}H+="if (!used) {"}if(e)"object"===e.type?"URLEncoded"===e.elysiaMeta?H+="c.body = parseQuery(await c.request.text())"
|
|
36
|
+
`,0!==e&&(H+="}")}H+="if (!used) {"}if(e)"object"===e.type?"URLEncoded"===e.elysiaMeta?H+="c.body = parseQuery(await c.request.text())":h.body.Code().includes("custom('File")?H+=`c.body = {}
|
|
40
37
|
|
|
41
38
|
await c.request.formData().then((form) => {
|
|
42
39
|
for (const key of form.keys()) {
|
|
@@ -48,7 +45,7 @@ ${r}
|
|
|
48
45
|
c.body[key] = value[0]
|
|
49
46
|
else c.body[key] = value
|
|
50
47
|
}
|
|
51
|
-
})`:H+="c.body = JSON.parse(await c.request.text())":H+="c.body = await c.request.text()";else switch(
|
|
48
|
+
})`:H+="c.body = JSON.parse(await c.request.text())":H+="c.body = await c.request.text()";else switch($.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"application/octet-stream":H+="c.body = await c.request.arrayBuffer();";break;case"multipart/form-data":H+=`c.body = {}
|
|
52
49
|
|
|
53
50
|
for (const key of (await c.request.formData()).keys()) {
|
|
54
51
|
if (c.body[key])
|
|
@@ -58,12 +55,12 @@ ${r}
|
|
|
58
55
|
if (value.length === 1)
|
|
59
56
|
c.body[key] = value[0]
|
|
60
57
|
else c.body[key] = value
|
|
61
|
-
}`}
|
|
58
|
+
}`}$.parse.length&&(H+="}}")}else{if(H+="\n"+(S?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+`
|
|
62
59
|
if (contentType) {
|
|
63
60
|
const index = contentType.indexOf(';')
|
|
64
61
|
if (index !== -1) contentType = contentType.substring(0, index)
|
|
65
|
-
|
|
66
|
-
`;for(let e=0;e
|
|
62
|
+
`,$.parse.length){H+=`let used = false
|
|
63
|
+
`;for(let e=0;e<$.parse.length;e++){let r=`bo${e}`;0!==e&&(H+=`if(!used) {
|
|
67
64
|
`),H+=`let ${r} = parse[${e}](c, contentType);if(${r} instanceof Promise) ${r} = await ${r};
|
|
68
65
|
if(${r} !== undefined) { c.body = ${r}; used = true }
|
|
69
66
|
`,0!==e&&(H+="}")}H+="if (!used)"}H+=`switch (contentType) {
|
|
@@ -79,6 +76,10 @@ ${r}
|
|
|
79
76
|
c.body = parseQuery(await c.request.text())
|
|
80
77
|
break
|
|
81
78
|
|
|
79
|
+
case 'application/octet-stream':
|
|
80
|
+
c.body = await c.request.arrayBuffer();
|
|
81
|
+
break
|
|
82
|
+
|
|
82
83
|
case 'multipart/form-data':
|
|
83
84
|
c.body = {}
|
|
84
85
|
|
|
@@ -95,55 +96,55 @@ ${r}
|
|
|
95
96
|
break
|
|
96
97
|
}
|
|
97
98
|
}
|
|
98
|
-
`}H+="\n"}if(
|
|
99
|
+
`}H+="\n"}if(h.params){let e=findElysiaMeta("Numeric",h.params.schema);if(e){if("object"==typeof e)for(let r of e)H+=`c.params.${r} = +c.params.${r};`;H+="\n"}}if(h.query){let e=findElysiaMeta("Numeric",h.query.schema);if(e){if("object"==typeof e)for(let r of e)H+=`c.query.${r} = +c.query.${r};`;H+="\n"}}if(h.headers){let e=findElysiaMeta("Numeric",h.headers.schema);if(e){if("object"==typeof e)for(let r of e)H+=`c.headers.${r} = +c.headers.${r};`;H+="\n"}}if(h.body){let e=findElysiaMeta("Numeric",h.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($?.transform)for(let e=0;e<$.transform.length;e++){let r=$.transform[e];"derive"===r.$elysia?H+=$.transform[e].constructor.name===u?`Object.assign(c, await transform[${e}](c));`:`Object.assign(c, transform[${e}](c));`:H+=$.transform[e].constructor.name===u?`await transform[${e}](c);`:`transform[${e}](c);`}if(h&&(h.headers&&(H+=`
|
|
99
100
|
if (headers.Check(c.headers) === false) {
|
|
100
|
-
${
|
|
101
|
+
${x("headers")}
|
|
101
102
|
}
|
|
102
|
-
`)
|
|
103
|
+
`),h.params&&(H+=`if(params.Check(c.params) === false) { ${x("params")} }`),h.query&&(H+=`if(query.Check(c.query) === false) { ${x("query")} }`),h.body&&(H+=`if(body.Check(c.body) === false) { ${x("body")} }`)),$?.beforeHandle)for(let e=0;e<$.beforeHandle.length;e++){let r=`be${e}`,t=hasReturn($.beforeHandle[e].toString());if(t){if(H+=($.beforeHandle[e].constructor.name===u?`let ${r} = await beforeHandle[${e}](c);
|
|
103
104
|
`:`let ${r} = beforeHandle[${e}](c);
|
|
104
105
|
`)+`if(${r} !== undefined) {
|
|
105
|
-
|
|
106
|
+
`,$?.afterHandle)for(let e=0;e<$.afterHandle.length;e++){let t=hasReturn($.afterHandle[e].toString());if(t){let t=`af${e}`;H+=($.afterHandle[e].constructor.name===u?`const ${t} = await afterHandle[${e}](c, ${r});
|
|
106
107
|
`:`const ${t} = afterHandle[${e}](c, ${r});
|
|
107
108
|
`)+`if(${t} !== undefined) { ${r} = ${t} }
|
|
108
|
-
`}else H
|
|
109
|
+
`}else H+=$.afterHandle[e].constructor.name===u?`await afterHandle[${e}](c, ${r});
|
|
109
110
|
`:`afterHandle[${e}](c, ${r});
|
|
110
|
-
`}
|
|
111
|
+
`}h.response&&(H+=`if(response[c.set.status]?.Check(${r}) === false) {
|
|
111
112
|
if(!(response instanceof Error))
|
|
112
113
|
${k(r)}
|
|
113
114
|
}
|
|
114
115
|
`),H+=`return mapEarlyResponse(${r}, c.set)}
|
|
115
|
-
`}else H
|
|
116
|
+
`}else H+=$.beforeHandle[e].constructor.name===u?`await beforeHandle[${e}](c);
|
|
116
117
|
`:`beforeHandle[${e}](c);
|
|
117
|
-
`}if(
|
|
118
|
+
`}if($?.afterHandle.length){H+=m.constructor.name===u?`let r = await handler(c);
|
|
118
119
|
`:`let r = handler(c);
|
|
119
|
-
`;for(let e=0;e
|
|
120
|
+
`;for(let e=0;e<$.afterHandle.length;e++){let r=`af${e}`,t=hasReturn($.afterHandle[e].toString());t?(H+=$.afterHandle[e].constructor.name===u?`let ${r} = await afterHandle[${e}](c, r)
|
|
120
121
|
`:`let ${r} = afterHandle[${e}](c, r)
|
|
121
|
-
|
|
122
|
+
`,h.response?H+=`if(response[c.set.status]?.Check(${r}) === false) {
|
|
122
123
|
if(!(response instanceof Error))
|
|
123
124
|
${k(r)}
|
|
124
125
|
}
|
|
125
126
|
${r} = mapEarlyResponse(${r}, c.set)
|
|
126
127
|
if(${r}) return ${r};
|
|
127
128
|
`:H+=`if(${r}) return ${r};
|
|
128
|
-
`):H
|
|
129
|
+
`):H+=$.afterHandle[e].constructor.name===u?`await afterHandle[${e}](c, r)
|
|
129
130
|
`:`afterHandle[${e}](c, r)
|
|
130
|
-
`}
|
|
131
|
+
`}h.response&&(H+=`if(response[c.set.status]?.Check(r) === false) {
|
|
131
132
|
if(!(response instanceof Error))
|
|
132
133
|
${k()}
|
|
133
134
|
}
|
|
134
|
-
`),
|
|
135
|
+
`),C?H+=`return mapResponse(r, c.set)
|
|
135
136
|
`:H+=`return mapCompactResponse(r)
|
|
136
|
-
`}else if(
|
|
137
|
+
`}else if(h.response)H+=(m.constructor.name===u?`const r = await handler(c);
|
|
137
138
|
`:`const r = handler(c);
|
|
138
139
|
`)+`if(response[c.set.status]?.Check(r) === false) {
|
|
139
140
|
if(!(response instanceof Error))
|
|
140
141
|
${k()}
|
|
141
142
|
}
|
|
142
|
-
`,
|
|
143
|
+
`,C?H+=`return mapResponse(r, c.set)
|
|
143
144
|
`:H+=`return mapCompactResponse(r)
|
|
144
|
-
`;else{let e=m.constructor.name===
|
|
145
|
+
`;else{let e=m.constructor.name===u?"await handler(c) ":"handler(c)";C?H+=`return mapResponse(${e}, c.set)
|
|
145
146
|
`:H+=`return mapCompactResponse(${e})
|
|
146
|
-
`}
|
|
147
|
+
`}w&&(H+=`
|
|
147
148
|
} catch(error) {
|
|
148
149
|
|
|
149
150
|
|
|
@@ -152,7 +153,7 @@ if(${r}) return ${r};
|
|
|
152
153
|
|
|
153
154
|
if (!set.status || set.status < 300) set.status = 500
|
|
154
155
|
|
|
155
|
-
${
|
|
156
|
+
${$.error.length?`for (let i = 0; i < handleErrors.length; i++) {
|
|
156
157
|
let handled = handleErrors[i]({
|
|
157
158
|
request: c.request,
|
|
158
159
|
error: error,
|
|
@@ -207,7 +208,7 @@ if(${r}) return ${r};
|
|
|
207
208
|
return ${N?"async":""} function(c) {
|
|
208
209
|
${q?"c[SCHEMA] = meta[SCHEMA]; c[DEFS] = meta[DEFS];":""}
|
|
209
210
|
${H}
|
|
210
|
-
}`;let T=Function("hooks",H);return T({handler:m,hooks:h,
|
|
211
|
+
}`;let T=Function("hooks",H);return T({handler:m,hooks:$,validator:h,handleError:b,utils:{mapResponse:t,mapCompactResponse:s,mapEarlyResponse:r,parseQuery:e},error:{ParseError:a,NotFoundError:c,ValidationError:i,InternalServerError:l},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=`
|
|
211
212
|
const route = find(request.method, path) ${s.root.ALL?'?? find("ALL", path)':""}
|
|
212
213
|
if (route === null)
|
|
213
214
|
return ${e.event.error.length?`handleError(
|
|
@@ -225,7 +226,7 @@ switch(request.method) {
|
|
|
225
226
|
${r}
|
|
226
227
|
${t??`default: ${o}`}}
|
|
227
228
|
|
|
228
|
-
`;let
|
|
229
|
+
`;let i=`const {
|
|
229
230
|
app,
|
|
230
231
|
app: { store, router, staticRouter },
|
|
231
232
|
${e.event.request.length?"mapEarlyResponse,":""}
|
|
@@ -244,7 +245,7 @@ ${t??`default: ${o}`}}
|
|
|
244
245
|
${e.event.error.length?"":"const error404 = notFound.message.toString()"}
|
|
245
246
|
|
|
246
247
|
return function(request) {
|
|
247
|
-
`;if(e.event.request.length){
|
|
248
|
+
`;if(e.event.request.length){i+=`
|
|
248
249
|
const ctx = {
|
|
249
250
|
request,
|
|
250
251
|
store,
|
|
@@ -256,19 +257,19 @@ ${t??`default: ${o}`}}
|
|
|
256
257
|
}
|
|
257
258
|
|
|
258
259
|
try {
|
|
259
|
-
`;for(let r=0;r<e.event.request.length;r++){let t=hasReturn(e.event.request[r].toString());
|
|
260
|
+
`;for(let r=0;r<e.event.request.length;r++){let t=hasReturn(e.event.request[r].toString());i+=t?`const response = mapEarlyResponse(
|
|
260
261
|
onRequest[${r}](ctx),
|
|
261
262
|
ctx.set
|
|
262
263
|
)
|
|
263
264
|
if (response) return response
|
|
264
|
-
`:`mapEarlyResponse(onRequest[${r}](ctx), ctx.set)`}
|
|
265
|
+
`:`mapEarlyResponse(onRequest[${r}](ctx), ctx.set)`}i+=`} catch (error) {
|
|
265
266
|
return handleError(request, error, ctx.set)
|
|
266
267
|
}
|
|
267
268
|
|
|
268
269
|
const url = request.url,
|
|
269
270
|
s = url.indexOf('/', 12),
|
|
270
271
|
i = ctx.query = url.indexOf('?', s + 1),
|
|
271
|
-
path = i === -1 ? url.substring(s) : url.substring(s, i);`}else
|
|
272
|
+
path = i === -1 ? url.substring(s) : url.substring(s, i);`}else i+=`
|
|
272
273
|
const url = request.url,
|
|
273
274
|
s = url.indexOf('/', 12)
|
|
274
275
|
|
|
@@ -286,19 +287,19 @@ ${t??`default: ${o}`}}
|
|
|
286
287
|
const path =
|
|
287
288
|
ctx.query === -1
|
|
288
289
|
? url.substring(s)
|
|
289
|
-
: url.substring(s, ctx.query);`;return
|
|
290
|
+
: url.substring(s, ctx.query);`;return i+=`
|
|
290
291
|
switch(path) {
|
|
291
292
|
${a}
|
|
292
293
|
|
|
293
294
|
default:
|
|
294
295
|
${o}
|
|
295
296
|
}
|
|
296
|
-
}`,e.handleError=composeErrorHandler(e),Function("data",
|
|
297
|
+
}`,e.handleError=composeErrorHandler(e),Function("data",i)({app:e,mapEarlyResponse:r,NotFoundError:c})};export const composeErrorHandler=e=>{let r=`const {
|
|
297
298
|
app: { event: { error: onError } },
|
|
298
299
|
mapResponse
|
|
299
300
|
} = inject
|
|
300
301
|
|
|
301
|
-
return ${e.event.error.find(e=>e.constructor.name===
|
|
302
|
+
return ${e.event.error.find(e=>e.constructor.name===u)?"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===u?"await ":""}onError[${t}]({
|
|
302
303
|
request,
|
|
303
304
|
code: error.code ?? 'UNKNOWN',
|
|
304
305
|
error,
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Memoirist as e}from"memoirist";import{SCHEMA as t,EXPOSED as r,DEFS as s,mergeHook as o,getSchemaValidator as
|
|
1
|
+
import{Memoirist as e}from"memoirist";import{SCHEMA as t,EXPOSED as r,DEFS as s,mergeHook as o,getSchemaValidator as a,getResponseSchemaValidator as i,mergeDeep as h}from"./utils";import{registerSchemaPath as n}from"./schema";import{composeErrorHandler as u,composeGeneralHandler as d,composeHandler as l}from"./compose";import{ws as c}from"./ws";export default class p{config;store={};meta={[t]:Object.create(null),[s]:Object.create(null),[r]:Object.create(null)};decorators={};event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],error:[],stop:[]};server=null;$schema=null;router=new e;routes=[];staticRouter={handlers:[],variables:"",map:{},all:""};wsRouter;lazyLoadModules=[];constructor(e){this.config={fn:"/~fn",forceErrorEncapsulation:!1,basePath:"",...e}}add(e,r,h,u,{allowMeta:d=!1}={allowMeta:!1}){r=""===r?r:47===r.charCodeAt(0)?r:`/${r}`,this.config.basePath&&this.config.basePath,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";break;case"arrayBuffer":u.type="application/octet-stream"}n({schema:this.meta[t],contentType:u?.type,hook:u,method:e,path:r,models:this.meta[s]});let p={body:a(u?.body??this.$schema?.body,c),headers:a(u?.headers??this.$schema?.headers,c,!0),params:a(u?.params??this.$schema?.params,c),query:a(u?.query??this.$schema?.query,c),response:i(u?.response??this.$schema?.response,c)},f=o(this.event,u),m=l({path:r,method:e,hooks:f,validator:p,handler:h,handleError:this.handleError,meta:d?this.meta:void 0,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}]
|
|
2
2
|
`,this.staticRouter.map[r]||(this.staticRouter.map[r]={code:""}),"ALL"===e?this.staticRouter.map[r].all=`default: return st${t}(ctx)
|
|
3
3
|
`:this.staticRouter.map[r].code+=`case '${e}': return st${t}(ctx)
|
|
4
|
-
`}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
|
|
4
|
+
`}else this.router.add(e,r,m)}onStart(e){return this.event.start.push(e),this}onRequest(e){return this.event.request.push(e),this}onParse(e){return this.event.parse.splice(this.event.parse.length-1,0,e),this}onTransform(e){return this.event.transform.push(e),this}onBeforeHandle(e){return this.event.beforeHandle.push(e),this}onAfterHandle(e){return this.event.afterHandle.push(e),this}onError(e){return this.event.error.push(e),this}onStop(e){return this.event.stop.push(e),this}on(e,t){switch(e){case"start":this.event.start.push(t);break;case"request":this.event.request.push(t);break;case"parse":this.event.parse.push(t);break;case"transform":this.event.transform.push(t);break;case"beforeHandle":this.event.beforeHandle.push(t);break;case"afterHandle":this.event.afterHandle.push(t);break;case"error":this.event.error.push(t);break;case"stop":this.event.stop.push(t)}return this}group(e,t,r){let a=new p;a.store=this.store,this.wsRouter&&a.use(c());let i="object"==typeof t,n=(i?r:t)(a);return this.decorators=h(this.decorators,a.decorators),n.event.request.length&&(this.event.request=[...this.event.request,...n.event.request]),this.model(n.meta[s]),Object.values(a.routes).forEach(({method:r,path:s,handler:h,hooks:u})=>{if(i){let i=`${e}${s}`,d=a.wsRouter?.find("subscribe",i);if(d){let e=a.wsRouter.history.find(([e,t])=>i===t);if(!e)return;return this.ws(i,e[2])}this.add(r,i,h,o(t,{...u,error:u.error?Array.isArray(u.error)?[...u.error,...n.event.error]:[u.error,...n.event.error]:n.event.error}))}else{let t=`${e}${s}`,i=a.wsRouter?.find("subscribe",t);if(i){let e=a.wsRouter.history.find(([e,t])=>s===t);if(!e)return;return this.ws(t,e[2])}this.add(r,t,h,o(u,{error:n.event.error}))}}),a.wsRouter&&this.wsRouter&&a.wsRouter.history.forEach(([t,r,s])=>{"/"===r?this.wsRouter?.add(t,e,s):this.wsRouter?.add(t,`${e}${r}`,s)}),this}guard(e,t){let r=new p;r.store=this.store,this.wsRouter&&r.use(c());let a=t(r);return this.decorators=h(this.decorators,r.decorators),a.event.request.length&&(this.event.request=[...this.event.request,...a.event.request]),this.model(a.meta[s]),Object.values(r.routes).forEach(({method:t,path:s,handler:i,hooks:h})=>{let n=r.wsRouter?.find("subscribe",s);if(n){let e=r.wsRouter.history.find(([e,t])=>s===t);if(!e)return;return this.ws(s,e[2])}this.add(t,s,i,o(e,{...h,error:h.error?Array.isArray(h.error)?[...h.error,...a.event.error]:[h.error,...a.event.error]:a.event.error}))}),r.wsRouter&&this.wsRouter&&r.wsRouter.history.forEach(([e,t,r])=>{this.wsRouter?.add(e,t,r)}),this}use(e){if(e instanceof Promise)return this.lazyLoadModules.push(e.then(e=>"function"==typeof e?e(this):e.default(this)).then(e=>e.compile())),this;let t=e(this);return t instanceof Promise?(this.lazyLoadModules.push(t.then(e=>e.compile())),this):t}if(e,t){return e?this.use(t):this}get(e,t,r){return this.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:a(t?.body,this.meta[s]),transformMessage:t.transform?Array.isArray(t.transformMessage)?t.transformMessage:[t.transformMessage]:[]}}))return e.set.status=400,"Expected a websocket connection"},{beforeHandle:t.beforeHandle,transform:t.transform,headers:t?.headers,params:t?.params,query:t?.query}),this}route(e,t,r,{config:s,...o}={config:{allowMeta:!1}}){return this.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:a(e.body,t),headers:a(e?.headers,t,!0),params:a(e?.params,t),query:a(e?.query,t),response:a(e?.response,t)},this}compile(){return this.fetch=d(this),this.server&&this.server.reload({...this.server,fetch:this.fetch}),this}handle=async e=>this.fetch(e);fetch=e=>(this.fetch=d(this))(e);handleError=async(e,t,r)=>(this.handleError=u(this))(e,t,r);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};
|
package/dist/types.d.ts
CHANGED
|
@@ -127,7 +127,7 @@ export type MergeSchema<A extends TypedSchema, B extends TypedSchema> = {
|
|
|
127
127
|
response: NotUndefined<A['response']> extends true ? A['response'] : NotUndefined<B['response']> extends true ? B['response'] : undefined;
|
|
128
128
|
};
|
|
129
129
|
type MaybeArray<T> = T | T[];
|
|
130
|
-
type ContentType = MaybeArray<(string & {}) | 'text' | 'json' | 'formdata' | 'urlencoded' | 'text/plain' | 'application/json' | 'multipart/form-data' | 'application/x-www-form-urlencoded'>;
|
|
130
|
+
type ContentType = MaybeArray<(string & {}) | 'none' | 'text' | 'json' | 'formdata' | 'urlencoded' | 'arrayBuffer' | 'text/plain' | 'application/json' | 'multipart/form-data' | 'application/x-www-form-urlencoded'>;
|
|
131
131
|
export type LocalHook<Schema extends TypedSchema, Instance extends ElysiaInstance<any>, Path extends string = string> = Partial<Schema> & {
|
|
132
132
|
type?: ContentType;
|
|
133
133
|
detail?: Partial<OpenAPIV3.OperationObject>;
|
|
@@ -188,9 +188,10 @@ export type ComposedHandler = (context: Context) => MaybePromise<Response>;
|
|
|
188
188
|
export interface ElysiaConfig {
|
|
189
189
|
fn?: string;
|
|
190
190
|
serve?: Partial<Serve>;
|
|
191
|
+
basePath?: string;
|
|
191
192
|
forceErrorEncapsulation?: boolean;
|
|
192
193
|
}
|
|
193
|
-
export type IsPathParameter<Part> = Part extends `:${infer Parameter}` ? Parameter : never;
|
|
194
|
+
export type IsPathParameter<Part> = Part extends `:${infer Parameter}` ? Parameter : Part extends `*` ? '*' : never;
|
|
194
195
|
export type ExtractPath<Path> = Path extends `${infer A}/${infer B}` ? IsPathParameter<A> | ExtractPath<B> : IsPathParameter<Path>;
|
|
195
196
|
export interface InternalRoute<Instance extends ElysiaInstance> {
|
|
196
197
|
method: HTTPMethod;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "elysia",
|
|
3
3
|
"description": "Fast, and friendly Bun web framework",
|
|
4
|
-
"version": "0.5.
|
|
4
|
+
"version": "0.5.10",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "saltyAom",
|
|
7
7
|
"url": "https://github.com/SaltyAom",
|
|
@@ -112,7 +112,7 @@
|
|
|
112
112
|
"@types/lodash.clonedeep": "^4.5.7",
|
|
113
113
|
"fast-querystring": "^1.1.1",
|
|
114
114
|
"lodash.clonedeep": "^4.5.0",
|
|
115
|
-
"memoirist": "0.1.
|
|
115
|
+
"memoirist": "0.1.4",
|
|
116
116
|
"openapi-types": "^12.1.0"
|
|
117
117
|
},
|
|
118
118
|
"devDependencies": {
|