Comparing version 0.5.0-exp-230507.1517 to 0.5.0-exp-230507.1922
import type { Elysia } from '.'; | ||
import { SCHEMA, DEFS } from './utils'; | ||
import type { ComposedHandler, HTTPMethod, LocalHandler, RegisteredHook, SchemaValidator } from './types'; | ||
export declare const hasReturn: (fnLiteral: string) => boolean; | ||
export declare const isFnUse: (keyword: string, fnLiteral: string) => boolean; | ||
@@ -5,0 +6,0 @@ export declare const composeHandler: ({ path, method, hooks, validator, handler, handleError, meta }: { |
@@ -1,2 +0,2 @@ | ||
import{parse as e}from"fast-querystring";import{mapEarlyResponse as r,mapResponse as t}from"./handler";import{SCHEMA as s,DEFS as a}from"./utils";import{ParseError as o,NotFoundError as n,ValidationError as c,InternalServerError as l}from"./error";let d="AsyncFunction",i=e=>e.constructor.name===d,u=new Headers,f=RegExp(" (\\w+) = context","g");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(f))s.push(e[1]);let a=RegExp(`{.*?} = (${s.join("|")})`,"g");for(let[t]of r.matchAll(a))if(t.includes(`{ ${e}`)||t.includes(`, ${e}`))return!0;return!1};export const composeHandler=({path:f,method:p,hooks:h,validator:y,handler:m,handleError:$,meta:b})=>{let w="try {\n",q="string"==typeof h.type,E=y||"GET"!==p?[m,...h.transform,...h.beforeHandle,...h.afterHandle].map(e=>e.toString()):[],k="GET"!==p&&(y.body||q||E.some(e=>isFnUse("body",e))),g=y.headers||E.some(e=>isFnUse("headers",e));g&&(w+=u.toJSON?`c.headers = c.request.headers.toJSON() | ||
import{parse as e}from"fast-querystring";import{mapEarlyResponse as r,mapResponse as t}from"./handler";import{SCHEMA as a,DEFS as s}from"./utils";import{ParseError as o,NotFoundError as n,ValidationError as c,InternalServerError as l}from"./error";let d="AsyncFunction",i=e=>e.constructor.name===d,u=new Headers,f=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 a=[t];for(let e of r.matchAll(f))a.push(e[1]);let s=RegExp(`{.*?} = (${a.join("|")})`,"g");for(let[t]of r.matchAll(s))if(t.includes(`{ ${e}`)||t.includes(`, ${e}`))return!0;return!1};export const composeHandler=({path:f,method:p,hooks:h,validator:y,handler:m,handleError:$,meta:b})=>{let w="try {\n",q="string"==typeof h.type,E=y||"GET"!==p?[m,...h.transform,...h.beforeHandle,...h.afterHandle].map(e=>e.toString()):[],g="GET"!==p&&(y.body||q||E.some(e=>isFnUse("body",e))),k=y.headers||E.some(e=>isFnUse("headers",e));k&&(w+=u.toJSON?`c.headers = c.request.headers.toJSON() | ||
`:`c.headers = {} | ||
@@ -15,3 +15,3 @@ for (const key of c.request.headers.keys()) | ||
if(url.charCodeAt(c.query) === 63 || (c.query = url.indexOf("?", ${11+f.length})) !== -1) { | ||
if(url.charCodeAt(c.query) === 63 || (c.query = url.indexOf("?", ${11+f.split("/").map(e=>e.startsWith(":")?"-":"").length})) !== -1) { | ||
c.query = parseQuery(url.substring(c.query + 1)) | ||
@@ -21,3 +21,3 @@ } else { | ||
} | ||
`);let H=k||m.constructor.name===d||h.parse.length||h.afterHandle.find(i)||h.beforeHandle.find(i)||h.transform.find(i);if(k){let e=y?.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(q||e){if(e)switch(e.type){case"object":"URLEncoded"===e.elysiaMeta?w+="c.body = parseQuery(await c.request.text())":y.body.Code().includes("custom('File")?w+=`c.body = {} | ||
`);let H=g||m.constructor.name===d||h.parse.length||h.afterHandle.find(i)||h.beforeHandle.find(i)||h.transform.find(i);if(g){let e=y?.body?.schema;if(e&&"anyOf"in e){let r=!1,t=e.anyOf[0].type;for(let a of e.anyOf)if(a.type!==t){r=!0;break}r&&(e=void 0)}if(q||e){if(e)switch(e.type){case"object":"URLEncoded"===e.elysiaMeta?w+="c.body = parseQuery(await c.request.text())":y.body.Code().includes("custom('File")?w+=`c.body = {} | ||
@@ -44,3 +44,3 @@ await c.request.formData().then((form) => { | ||
else c.body[key] = value | ||
}`}}else{if(w+="\n"+(g?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+` | ||
}`}}else{if(w+="\n"+(k?"let contentType = c.headers['content-type']":"let contentType = c.request.headers.get('content-type')")+` | ||
if (contentType) { | ||
@@ -91,13 +91,17 @@ const index = contentType.indexOf(';') | ||
} | ||
`),y.params&&(w+="if(params.Check(c.params) === false) { throw new ValidationError('params', params, c.params) }"),y.query&&(w+="if(query.Check(c.query) === false) { throw new ValidationError('query', query, c.query) }"),y.body&&(w+="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}`;if(w+=(h.beforeHandle[e].constructor.name===d?`let ${r} = await beforeHandle[${e}](c); | ||
`),y.params&&(w+="if(params.Check(c.params) === false) { throw new ValidationError('params', params, c.params) }"),y.query&&(w+="if(query.Check(c.query) === false) { throw new ValidationError('query', query, c.query) }"),y.body&&(w+="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(w+=(h.beforeHandle[e].constructor.name===d?`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=`af${e}`;w+=(h.afterHandle[e].constructor.name===d?`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}`;w+=(h.afterHandle[e].constructor.name===d?`const ${t} = await afterHandle[${e}](c, ${r}); | ||
`:`const ${t} = afterHandle[${e}](c, ${r}); | ||
`)+`if(${t} !== undefined) { ${r} = ${t} } | ||
`}else w+=h.afterHandle[e].constructor.name===d?`await afterHandle[${e}](c, ${r}); | ||
`:`afterHandle[${e}](c, ${r}); | ||
`}y.response&&(w+=`if(response[c.set.status]?.Check(${r}) === false) { throw new ValidationError('response', response[c.set.status], ${r}) } | ||
`),w+=`return mapEarlyResponse(${r}, c.set)} | ||
`}else w+=h.beforeHandle[e].constructor.name===d?`await beforeHandle[${e}](c); | ||
`:`beforeHandle[${e}](c); | ||
`}if(h?.afterHandle.length){w+=m.constructor.name===d?`let r = await handler(c); | ||
`:`let r = handler(c); | ||
`;for(let e=0;e<h.afterHandle.length;e++){let r=`af${e}`;w+=h.afterHandle[e].constructor.name===d?`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?(w+=h.afterHandle[e].constructor.name===d?`let ${r} = await afterHandle[${e}](c, r) | ||
`:`let ${r} = afterHandle[${e}](c, r) | ||
@@ -108,2 +112,4 @@ `,y.response?w+=`if(response[c.set.status]?.Check(${r}) === false) { throw new ValidationError('response', response[c.set.status], ${r}) } | ||
`:w+=`if(${r}) return ${r}; | ||
`):w+=h.afterHandle[e].constructor.name===d?`await afterHandle[${e}](c, r) | ||
`:`afterHandle[${e}](c, r) | ||
`}y.response&&(w+=`if(response[c.set.status]?.Check(r) === false) { throw new ValidationError('response', response[c.set.status], r) } | ||
@@ -178,3 +184,3 @@ `),w+=`return mapResponse(r, c.set); | ||
${w} | ||
}`;let v=Function("hooks",w);return v({handler:m,hooks:h,validator:y,handleError:$,utils:{mapResponse:t,mapEarlyResponse:r,parseQuery:e},error:{ParseError:o,NotFoundError:n,ValidationError:c,InternalServerError:l},meta:b,SCHEMA:b?s:void 0,DEFS:b?a:void 0})};export const composeGeneralHandler=e=>{let t="";for(let r of Object.keys(e.decorators))t+=`,${r}: app.decorators.${r}`;let s=e.staticRouter,a="";for(let[e,r]of Object.entries(s.map))a+=`case '${e}': | ||
}`;let v=Function("hooks",w);return v({handler:m,hooks:h,validator:y,handleError:$,utils:{mapResponse:t,mapEarlyResponse:r,parseQuery:e},error:{ParseError:o,NotFoundError:n,ValidationError:c,InternalServerError:l},meta:b,SCHEMA:b?a:void 0,DEFS:b?s:void 0})};export const composeGeneralHandler=e=>{let t="";for(let r of Object.keys(e.decorators))t+=`,${r}: app.decorators.${r}`;let a=e.staticRouter,s="";for(let[e,r]of Object.entries(a.map))s+=`case '${e}': | ||
switch(method) { | ||
@@ -196,4 +202,6 @@ ${r}} | ||
${s.variables} | ||
${a.variables} | ||
const find = router.find.bind(router) | ||
return function(request) { | ||
@@ -230,6 +238,6 @@ const ctx = { | ||
switch(path) { | ||
${a} | ||
${s} | ||
} | ||
const route = router.find(method, path) | ||
const route = find(method, path) | ||
if (route === null) | ||
@@ -236,0 +244,0 @@ return app.handleError( |
@@ -5,4 +5,4 @@ /// <reference types="bun-types" /> | ||
request: Request; | ||
headers: Route['headers'] extends undefined ? Record<string, unknown> : Route['headers']; | ||
query: Route['query'] extends undefined ? Record<string, unknown> : Route['query']; | ||
headers: undefined extends Route['headers'] ? Record<string, unknown> : Route['headers']; | ||
query: undefined extends Route['query'] ? Record<string, unknown> : Route['query']; | ||
params: Route['params']; | ||
@@ -9,0 +9,0 @@ body: Route['body']; |
@@ -27,2 +27,4 @@ /// <reference types="bun-types" /> | ||
export type ElysiaWSContext<Schema extends WSTypedSchema = WSTypedSchema, Path extends string = string> = ServerWebSocket<Context<ExtractPath<Path> extends never ? WebSocketSchemaToRoute<Schema> : Omit<WebSocketSchemaToRoute<Schema>, 'params'> & { | ||
query: any; | ||
headers: any; | ||
params: Record<ExtractPath<Path>, string>; | ||
@@ -29,0 +31,0 @@ }> & { |
{ | ||
"name": "elysia", | ||
"description": "Fast, and friendly Bun web framework", | ||
"version": "0.5.0-exp-230507.1517", | ||
"version": "0.5.0-exp-230507.1922", | ||
"author": { | ||
@@ -6,0 +6,0 @@ "name": "saltyAom", |
@@ -29,2 +29,16 @@ import type { Elysia } from '.' | ||
export const hasReturn = (fnLiteral: string) => { | ||
const parenthesisEnd = fnLiteral.indexOf(')') | ||
// Is direct arrow function return eg. () => 1 | ||
if ( | ||
fnLiteral.charCodeAt(parenthesisEnd + 2) === 61 && | ||
fnLiteral.charCodeAt(parenthesisEnd + 5) !== 123 | ||
) { | ||
return true | ||
} | ||
return fnLiteral.includes('return') | ||
} | ||
export const isFnUse = (keyword: string, fnLiteral: string) => { | ||
@@ -51,3 +65,7 @@ const argument = fnLiteral.slice( | ||
// Match dot notation and named access | ||
if (fnLiteral.match(new RegExp(`${argument}(.${keyword}|\\["${keyword}"\\])`))) { | ||
if ( | ||
fnLiteral.match( | ||
new RegExp(`${argument}(.${keyword}|\\["${keyword}"\\])`) | ||
) | ||
) { | ||
return true | ||
@@ -136,3 +154,4 @@ } | ||
if(url.charCodeAt(c.query) === 63 || (c.query = url.indexOf("?", ${ | ||
11 + path.length | ||
11 + | ||
path.split('/').map((x) => (x.startsWith(':') ? '-' : '')).length | ||
})) !== -1) { | ||
@@ -331,26 +350,48 @@ c.query = parseQuery(url.substring(c.query + 1)) | ||
fnLiteral += | ||
hooks.beforeHandle[i].constructor.name === ASYNC_FN | ||
? `let ${name} = await beforeHandle[${i}](c);\n` | ||
: `let ${name} = beforeHandle[${i}](c);\n` | ||
const returning = hasReturn(hooks.beforeHandle[i].toString()) | ||
fnLiteral += `if(${name} !== undefined) {\n` | ||
if (hooks?.afterHandle) { | ||
const beName = name | ||
for (let i = 0; i < hooks.afterHandle.length; i++) { | ||
const name = `af${i}` | ||
if (!returning) { | ||
fnLiteral += | ||
hooks.beforeHandle[i].constructor.name === ASYNC_FN | ||
? `await beforeHandle[${i}](c);\n` | ||
: `beforeHandle[${i}](c);\n` | ||
} else { | ||
fnLiteral += | ||
hooks.beforeHandle[i].constructor.name === ASYNC_FN | ||
? `let ${name} = await beforeHandle[${i}](c);\n` | ||
: `let ${name} = beforeHandle[${i}](c);\n` | ||
fnLiteral += | ||
hooks.afterHandle[i].constructor.name === ASYNC_FN | ||
? `const ${name} = await afterHandle[${i}](c, ${beName});\n` | ||
: `const ${name} = afterHandle[${i}](c, ${beName});\n` | ||
fnLiteral += `if(${name} !== undefined) {\n` | ||
if (hooks?.afterHandle) { | ||
const beName = name | ||
for (let i = 0; i < hooks.afterHandle.length; i++) { | ||
const returning = hasReturn( | ||
hooks.afterHandle[i].toString() | ||
) | ||
fnLiteral += `if(${name} !== undefined) { ${beName} = ${name} }\n` | ||
if (!returning) { | ||
fnLiteral += | ||
hooks.afterHandle[i].constructor.name === | ||
ASYNC_FN | ||
? `await afterHandle[${i}](c, ${beName});\n` | ||
: `afterHandle[${i}](c, ${beName});\n` | ||
} else { | ||
const name = `af${i}` | ||
fnLiteral += | ||
hooks.afterHandle[i].constructor.name === | ||
ASYNC_FN | ||
? `const ${name} = await afterHandle[${i}](c, ${beName});\n` | ||
: `const ${name} = afterHandle[${i}](c, ${beName});\n` | ||
fnLiteral += `if(${name} !== undefined) { ${beName} = ${name} }\n` | ||
} | ||
} | ||
} | ||
} | ||
if (validator.response) | ||
fnLiteral += `if(response[c.set.status]?.Check(${name}) === false) { throw new ValidationError('response', response[c.set.status], ${name}) }\n` | ||
if (validator.response) | ||
fnLiteral += `if(response[c.set.status]?.Check(${name}) === false) { throw new ValidationError('response', response[c.set.status], ${name}) }\n` | ||
fnLiteral += `return mapEarlyResponse(${name}, c.set)}\n` | ||
fnLiteral += `return mapEarlyResponse(${name}, c.set)}\n` | ||
} | ||
} | ||
@@ -367,14 +408,23 @@ | ||
fnLiteral += | ||
hooks.afterHandle[i].constructor.name === ASYNC_FN | ||
? `let ${name} = await afterHandle[${i}](c, r)\n` | ||
: `let ${name} = afterHandle[${i}](c, r)\n` | ||
const returning = hasReturn(hooks.afterHandle[i].toString()) | ||
if (validator.response) { | ||
fnLiteral += `if(response[c.set.status]?.Check(${name}) === false) { throw new ValidationError('response', response[c.set.status], ${name}) }\n` | ||
if (!returning) { | ||
fnLiteral += | ||
hooks.afterHandle[i].constructor.name === ASYNC_FN | ||
? `await afterHandle[${i}](c, r)\n` | ||
: `afterHandle[${i}](c, r)\n` | ||
} else { | ||
fnLiteral += | ||
hooks.afterHandle[i].constructor.name === ASYNC_FN | ||
? `let ${name} = await afterHandle[${i}](c, r)\n` | ||
: `let ${name} = afterHandle[${i}](c, r)\n` | ||
fnLiteral += `${name} = mapEarlyResponse(${name}, c.set)\n` | ||
if (validator.response) { | ||
fnLiteral += `if(response[c.set.status]?.Check(${name}) === false) { throw new ValidationError('response', response[c.set.status], ${name}) }\n` | ||
fnLiteral += `if(${name}) return ${name};\n` | ||
} else fnLiteral += `if(${name}) return ${name};\n` | ||
fnLiteral += `${name} = mapEarlyResponse(${name}, c.set)\n` | ||
fnLiteral += `if(${name}) return ${name};\n` | ||
} else fnLiteral += `if(${name}) return ${name};\n` | ||
} | ||
} | ||
@@ -438,2 +488,4 @@ | ||
// console.log(fnLiteral) | ||
fnLiteral = `const { | ||
@@ -542,2 +594,4 @@ handler, | ||
const find = router.find.bind(router) | ||
return function(request) { | ||
@@ -581,3 +635,3 @@ const ctx = { | ||
const route = router.find(method, path) | ||
const route = find(method, path) | ||
if (route === null) | ||
@@ -584,0 +638,0 @@ return app.handleError( |
@@ -8,6 +8,6 @@ import type { Elysia, TypedRoute, DEFS, SCHEMA, TypedSchema } from '.' | ||
request: Request | ||
headers: Route['headers'] extends undefined | ||
headers: undefined extends Route['headers'] | ||
? Record<string, unknown> | ||
: Route['headers'] | ||
query: Route['query'] extends undefined | ||
query: undefined extends Route['query'] | ||
? Record<string, unknown> | ||
@@ -14,0 +14,0 @@ : Route['query'] |
@@ -144,3 +144,2 @@ import type { Server, ServerWebSocket, WebSocketHandler } from 'bun' | ||
const route = router.find('subscribe', url)?.store | ||
if (!route?.message) return | ||
@@ -147,0 +146,0 @@ |
@@ -104,2 +104,4 @@ import type { ServerWebSocket, WebSocketHandler } from 'bun' | ||
: Omit<WebSocketSchemaToRoute<Schema>, 'params'> & { | ||
query: any | ||
headers: any | ||
params: Record<ExtractPath<Path>, string> | ||
@@ -106,0 +108,0 @@ } |
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
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
218091
5860