elysia 0.2.5 → 0.2.7

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.
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env sh
2
+ . "$(dirname -- "$0")/_/husky.sh"
3
+
4
+ npx pretty-quick --staged
@@ -0,0 +1,80 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or advances of any kind
22
+ * Trolling, insulting or derogatory comments, and personal or political attacks
23
+ * Public or private harassment
24
+ * Publishing others' private information, such as a physical or email address, without their explicit permission
25
+ * Contacting individual members, contributors, or leaders privately, outside designated community mechanisms, without their explicit permission
26
+ * Other conduct which could reasonably be considered inappropriate in a professional setting
27
+
28
+ ## Enforcement Responsibilities
29
+
30
+ Maintaners are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
31
+
32
+ Mainteiners have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
33
+
34
+ ## Scope
35
+
36
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
37
+
38
+ ## Enforcement
39
+
40
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the maintainers. All complaints will be reviewed and investigated promptly and fairly.
41
+
42
+ All maintainers are obligated to respect the privacy and security of the reporter of any incident.
43
+
44
+ ## Enforcement Guidelines
45
+
46
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
47
+
48
+ ### 1. Correction
49
+
50
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
51
+
52
+ **Consequence**: A private, written warning from maintainers, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
53
+
54
+ ### 2. Warning
55
+
56
+ **Community Impact**: A violation through a single incident or series of actions.
57
+
58
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
59
+
60
+ ### 3. Temporary Ban
61
+
62
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
63
+
64
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
65
+
66
+ ### 4. Permanent Ban
67
+
68
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
69
+
70
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
71
+
72
+ ## Attribution
73
+
74
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at <https://www.contributor-covenant.org/version/2/0/code_of_conduct.html>.
75
+
76
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
77
+
78
+ [homepage]: https://www.contributor-covenant.org
79
+
80
+ For answers to common questions about this code of conduct, see the FAQ at <https://www.contributor-covenant.org/faq>. Translations are available at <https://www.contributor-covenant.org/translations>.
@@ -0,0 +1,49 @@
1
+ # Welcome to Elysia.js contributing guide
2
+
3
+ Thank you for investing your time in contributing to Elysia.js! Any contribution you make will be amazing :sparkles:.
4
+
5
+ Read our [Code of Conduct](./CODE_OF_CONDUCT.md) to keep our community approachable and respectable.
6
+
7
+ In this guide you will get an overview of the contribution workflow from opening an issue, creating a PR, reviewing, and merging the PR.
8
+
9
+ ## Setup Local Development Environment
10
+
11
+ The Elysia.js repo is using [bun](https://bun.sh). Make sure you have the [latest version of bun](https://github.com/oven-sh/bun/releases) installed in your system. To run Elysia.js locally:
12
+
13
+ 1. Clone this repository
14
+
15
+ 2. In the root of this project, run `bun install` to install all of the necessary dependencies
16
+
17
+ 3. To run the development verision, run `bun run dev`
18
+
19
+ ### Unit Testing
20
+
21
+ In Elysia.js, all of the test files are located inside the [`test/`](test/) directory. Unit testing are powered by [bun's wiptest](https://github.com/oven-sh/bun/tree/main/packages/bun-test).
22
+
23
+ - `bun test` to run all the test inside the [`test/`](test/) directory
24
+
25
+ - `bun test test/<test-file>.ts` to run a specific test
26
+
27
+ ## Pull Request Guidelines
28
+
29
+ - Checkout a topic branch from a base branch (e.g. `main`), and merge back against that branch.
30
+
31
+ - If adding a new feature:
32
+
33
+ - Add accompanying test case if possible.
34
+
35
+ - Provide a convincing reason to add this feature. Ideally, you should open a suggestion issue first, and have it approved before working on it.
36
+
37
+ - If fixing a bug:
38
+
39
+ - If you are resolving a special issue, please add the issues number in the PR's description.
40
+
41
+ - Provide a detailed description of the bug in the PR. Live demo preferred.
42
+
43
+ - Add appropriate test coverage if applicable.
44
+
45
+ - It's OK to have multiple small commits as you work on the PR. GitHub can automatically squash them before merging.
46
+
47
+ ## Thanks :purple_heart:
48
+
49
+ Thanks for all your contributions and efforts towards improving Elysia.js. We thank you for being part of our :sparkles: community :sparkles:!
package/README.md CHANGED
@@ -30,5 +30,8 @@ Designed with TypeScript in mind, you don't need to understand TypeScript to gai
30
30
  ## Documentation
31
31
  The documentation is available on [elysiajs.com](https://elysiajs.com).
32
32
 
33
+ ## Contributing
34
+ See [Contributing Guide](CONTRIBUTING.md) and please follow our [Code of Conduct](CODE_OF_CONDUCT.md).
35
+
33
36
  ## Discord
34
37
  Come join the [Discord channel~](https://discord.gg/eaFJ2KDJck)
package/dist/handler.js CHANGED
@@ -1 +1 @@
1
- let e=e=>{for(let s in e)return!0;return!1};export const mapEarlyResponse=(s,n)=>{if(n.redirect)return Response.redirect(n.redirect,{headers:n.headers});if(e(n.headers)||200!==n.status)switch(typeof s){case"string":return new Response(s,{status:n.status,headers:n.headers});case"object":if(s instanceof Error)return errorToResponse(s,n.headers);if(s instanceof Response){for(let e in n.headers)s.headers.append(e,n.headers[e]);return s}if(s instanceof Blob)return new Response(s,{status:n.status,headers:n.headers});return n.headers["Content-Type"]||(n.headers["Content-Type"]="application/json"),new Response(JSON.stringify(s),{status:n.status,headers:n.headers});case"function":if(s instanceof Blob)return new Response(s,{status:n.status,headers:n.headers});for(let e in n.headers)s.headers.append(e,n.headers[e]);return s;case"number":case"boolean":return new Response(s.toString(),{status:n.status,headers:n.headers})}else switch(typeof s){case"string":return new Response(s);case"object":if(s instanceof Response)return s;if(s instanceof Error)return errorToResponse(s,n.headers);if(s instanceof Blob)return new Response(s);return new Response(JSON.stringify(s),{headers:{"content-type":"application/json"}});case"function":if(s instanceof Blob)return new Response(s);return s;case"number":case"boolean":return new Response(s.toString())}};export const mapResponse=(s,n)=>{if(n.redirect)return Response.redirect(n.redirect,{headers:n.headers});if(e(n.headers)||200!==n.status)switch(typeof s){case"string":default:return new Response(s,{status:n.status,headers:n.headers});case"object":if(s instanceof Error)return errorToResponse(s,n.headers);if(s instanceof Response){for(let e in n.headers)s.headers.append(e,n.headers[e]);return s}if(s instanceof Blob)return new Response(s,{status:n.status,headers:n.headers});return n.headers["Content-Type"]||(n.headers["Content-Type"]="application/json"),new Response(JSON.stringify(s),{status:n.status,headers:n.headers});case"function":if(s instanceof Blob)return new Response(s,{status:n.status,headers:n.headers});return s();case"number":case"boolean":return new Response(s.toString(),{status:n.status,headers:n.headers});case"undefined":return new Response("",{status:n.status,headers:n.headers})}else switch(typeof s){case"string":default:return new Response(s);case"object":if(s instanceof Response)return s;if(s instanceof Error)return errorToResponse(s,n.headers);if(s instanceof Blob)return new Response(s);return new Response(JSON.stringify(s),{headers:{"content-type":"application/json"}});case"function":if(s instanceof Blob)return new Response(s);return s();case"number":case"boolean":return new Response(s.toString());case"undefined":return new Response("")}};export const errorToResponse=(e,s)=>new Response(JSON.stringify({name:e?.name,message:e?.message,cause:e?.cause}),{status:500,headers:s});
1
+ let e=e=>{for(let s in e)return!0;return!1},s=(e,s)=>{if(Array.isArray(s)){e.delete("Set-Cookie");for(let r=0;r<s.length;r++){let n=s[r].indexOf("=");e.append("Set-Cookie",`${s[r].slice(0,n)}=${s[r].slice(n+1)}`)}}return e};export const mapEarlyResponse=(r,n)=>{if(n.headers?.["Set-Cookie"]&&(n.headers=s(new Headers(n.headers),n.headers["Set-Cookie"])),n.redirect)return Response.redirect(n.redirect,{headers:n.headers});if(e(n.headers)||200!==n.status)switch(typeof r){case"string":return new Response(r,{status:n.status,headers:n.headers});case"object":if(r instanceof Error)return errorToResponse(r,n.headers);if(r instanceof Response){for(let e in n.headers)r.headers.append(e,n.headers[e]);return r}if(r instanceof Blob)return new Response(r,{status:n.status,headers:n.headers});return n.headers["Content-Type"]||(n.headers["Content-Type"]="application/json"),new Response(JSON.stringify(r),{status:n.status,headers:n.headers});case"function":if(r instanceof Blob)return new Response(r,{status:n.status,headers:n.headers});for(let e in n.headers)r.headers.append(e,n.headers[e]);return r;case"number":case"boolean":return new Response(r.toString(),{status:n.status,headers:n.headers})}else switch(typeof r){case"string":return new Response(r);case"object":if(r instanceof Response)return r;if(r instanceof Error)return errorToResponse(r,n.headers);if(r instanceof Blob)return new Response(r);return new Response(JSON.stringify(r),{headers:{"content-type":"application/json"}});case"function":if(r instanceof Blob)return new Response(r);return r;case"number":case"boolean":return new Response(r.toString())}};export const mapResponse=(r,n)=>{if(n.headers?.["Set-Cookie"]&&(n.headers=s(new Headers(n.headers),n.headers["Set-Cookie"])),n.redirect)return Response.redirect(n.redirect,{headers:n.headers});if(e(n.headers)||200!==n.status)switch(typeof r){case"string":default:return new Response(r,{status:n.status,headers:n.headers});case"object":if(r instanceof Error)return errorToResponse(r,n.headers);if(r instanceof Response){for(let e in n.headers)r.headers.append(e,n.headers[e]);return r}if(r instanceof Blob)return new Response(r,{status:n.status,headers:n.headers});return n.headers["Content-Type"]||(n.headers["Content-Type"]="application/json"),new Response(JSON.stringify(r),{status:n.status,headers:n.headers});case"function":if(r instanceof Blob)return new Response(r,{status:n.status,headers:n.headers});return r();case"number":case"boolean":return new Response(r.toString(),{status:n.status,headers:n.headers});case"undefined":return new Response("",{status:n.status,headers:n.headers})}else switch(typeof r){case"string":default:return new Response(r);case"object":if(r instanceof Response)return r;if(r instanceof Error)return errorToResponse(r,n.headers);if(r instanceof Blob)return new Response(r);return new Response(JSON.stringify(r),{headers:{"content-type":"application/json"}});case"function":if(r instanceof Blob)return new Response(r);return r();case"number":case"boolean":return new Response(r.toString());case"undefined":return new Response("")}};export const errorToResponse=(e,s)=>new Response(JSON.stringify({name:e?.name,message:e?.message,cause:e?.cause}),{status:500,headers:s});
package/dist/index.d.ts CHANGED
@@ -88,9 +88,9 @@ export default class Elysia<Instance extends ElysiaInstance = ElysiaInstance> {
88
88
  store: Instance['store'];
89
89
  schema: MergeSchema<Schema, Instance['schema']>;
90
90
  }>>(schema: Schema): NewInstance;
91
- handle(request: Request): Promise<Response>;
91
+ handle: (request: Request) => Promise<Response>;
92
92
  handleError(error: Error, set?: Context['set']): Promise<Response>;
93
- listen(options: string | number | Partial<Serve>, callback?: ListenCallback): this;
93
+ listen: (options: string | number | Partial<Serve>, callback?: ListenCallback) => this;
94
94
  stop: () => Promise<void>;
95
95
  get modules(): Promise<Elysia<ElysiaInstance<{
96
96
  store: Record<any, any> & Record<typeof SCHEMA, {}> & Record<typeof DEFS, {}>;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{Raikiri as e}from"raikiri";import{mapResponse as t,mapEarlyResponse as r}from"./handler";import{mapQuery as s,clone as a,mergeHook as i,mergeDeep as h,createValidationError as n,getSchemaValidator as o,SCHEMA as l,DEFS as d,getResponseSchemaValidator as u,mapPathnameAndQueryRegEx as f}from"./utils";import{registerSchemaPath as c}from"./schema";import{mapErrorCode as p,mapErrorStatus as m}from"./error";export default class v{store={[l]:{},[d]:{}};decorators=null;event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],error:[],stop:[]};server=null;$schema=null;router=new e;routes=[];lazyLoadModules=[];constructor(e={}){this.config={...e}}_addHandler(e,t,r,s){t=t.startsWith("/")?t:`/${t}`,this.routes.push({method:e,path:t,handler:r,hooks:i(a(this.event),s)});let h=this.store[d],n=o(s?.schema?.body??this.$schema?.body,h),f=o(s?.schema?.headers??this.$schema?.headers,h,!0),p=o(s?.schema?.params??this.$schema?.params,h),m=o(s?.schema?.query??this.$schema?.query,h),v=u(s?.schema?.response??this.$schema?.response,h);c({schema:this.store[l],hook:s,method:e,path:t,models:this.store[d]});let g=i(a(this.event),s);g.schema||g.transform.length||g.beforeHandle.length||g.error.length||g.afterHandle.length||(g=void 0);let y={handle:r,hooks:g,validator:n||f||p||m||v?{body:n,header:f,params:p,query:m,response:v}:void 0};this.router.add(e,t,y)}onStart(e){return this.event.start.push(e),this}onRequest(e){return this.event.request.push(e),this}onParse(e){return this.event.parse.splice(this.event.parse.length-1,0,e),this}onTransform(e){return this.event.transform.push(e),this}onBeforeHandle(e){return this.event.beforeHandle.push(e),this}onAfterHandle(e){return this.event.afterHandle.push(e),this}onError(e){return this.event.error.push(e),this}onStop(e){return this.event.stop.push(e),this}on(e,t){switch(e){case"start":this.event.start.push(t);break;case"request":this.event.request.push(t);break;case"parse":this.event.parse.push(t);break;case"transform":this.event.transform.push(t);break;case"beforeHandle":this.event.beforeHandle.push(t);break;case"afterHandle":this.event.afterHandle.push(t);break;case"error":this.event.error.push(t);break;case"stop":this.event.stop.push(t)}return this}group(e,t){let r=new v;r.store=this.store;let s=t(r);return s.event.request.length&&(this.event.request=[...this.event.request,...s.event.request]),Object.values(r.routes).forEach(({method:t,path:r,handler:s,hooks:a})=>{"/"===r?this._addHandler(t,e,s,a):this._addHandler(t,`${e}${r}`,s,a)}),this}guard(e,t){let r=new v;r.store=this.store;let s=t(r);return s.event.request.length&&(this.event.request=[...this.event.request,...s.event.request]),Object.values(r.routes).forEach(({method:t,path:r,handler:s,hooks:a})=>{this._addHandler(t,r,s,i(e,a))}),this}use(e){if(e instanceof Promise)return this.lazyLoadModules.push(e.then(e=>"function"==typeof e?e(this):e.default(this))),this;let t=e(this);return t instanceof Promise?(this.lazyLoadModules.push(t),this):t}get(e,t,r){return this._addHandler("GET",e,t,r),this}post(e,t,r){return this._addHandler("POST",e,t,r),this}put(e,t,r){return this._addHandler("PUT",e,t,r),this}patch(e,t,r){return this._addHandler("PATCH",e,t,r),this}delete(e,t,r){return this._addHandler("DELETE",e,t,r),this}options(e,t,r){return this._addHandler("OPTIONS",e,t,r),this}all(e,t,r){return this._addHandler("ALL",e,t,r),this}head(e,t,r){return this._addHandler("HEAD",e,t,r),this}trace(e,t,r){return this._addHandler("TRACE",e,t,r),this}connect(e,t,r){return this._addHandler("CONNECT",e,t,r),this}route(e,t,r,s){return this._addHandler(e,t,r,s),this}state(e,t){return e in this.store||(this.store[e]=t),this}decorate(e,t){return this.decorators||(this.decorators={}),e in this.decorators||(this.decorators[e]=t),this}derive(e){return this.store=h(this.store,e(()=>this.store)),this}inject(e){return this.onTransform(t=>{Object.assign(t,e(t))})}schema(e){let t=this.store[d];return this.$schema={body:o(e.body,t),headers:o(e?.headers,t,!0),params:o(e?.params,t),query:o(e?.query,t),response:o(e?.response,t)},this}async handle(e){let i;let h={status:200,headers:{}};this.decorators?((i=a(this.decorators)).request=e,i.set=h,i.store=this.store,i.query={}):i={set:h,store:this.store,request:e,query:{}};try{let a;let o=this.event;if(o.request.length)for(let e=0;e<o.request.length;e++){let t=o.request[e](i);if(t instanceof Promise&&(t=await t),t=r(t,h))return t}let l=e.url.match(f);if(!l)throw Error("NOT_FOUND");let d=this.router.match(e.method,l[1])??this.router.match("ALL",l[1]),u=d?.store;if(!u)throw Error("NOT_FOUND");if("GET"!==e.method){let t=e.headers.get("content-type");if(t){let r=t.indexOf(";");if(-1!==r&&(t=t.slice(0,r)),o.parse.length)for(let e=0;e<o.parse.length;e++){let r=o.parse[e](i,t);if(r instanceof Promise&&(r=await r),void 0!==r){a=r;break}}if(void 0===a)switch(t){case"application/json":a=await e.json();break;case"text/plain":a=await e.text();break;case"application/x-www-form-urlencoded":a=s(await e.text())}}}i.body=a,i.params=d?.params||{},l[2]&&(i.query=s(l[2]));let c=u.hooks;if(c?.transform.length)for(let e=0;e<c.transform.length;e++){let t=c.transform[e](i);t instanceof Promise&&await t}if(u.validator){let t=u.validator;if(t.headers){let r={};for(let t in e.headers)r[t]=e.headers.get(t);if(!1===t.headers.Check(r))throw n("header",t.headers,r)}if(!1===t.params?.Check(i.params))throw n("params",t.params,i.params);if(!1===t.query?.Check(i.query))throw n("query",t.query,i.query);if(!1===t.body?.Check(a))throw n("body",t.body,a)}if(c?.beforeHandle.length)for(let e=0;e<c.beforeHandle.length;e++){let t=c.beforeHandle[e](i);if(t instanceof Promise&&(t=await t),null!=t){for(let e=0;e<c.afterHandle.length;e++){let r=c.afterHandle[e](i,t);r instanceof Promise&&(r=await r),r&&(t=r)}let e=r(t,i.set);if(e)return e}}let p=u.handle(i);if(p instanceof Promise&&(p=await p),!1===u.validator?.response?.Check(p))throw n("response",u.validator.response,p);if(c?.afterHandle.length)for(let e=0;e<c.afterHandle.length;e++){let t=c.afterHandle[e](i,p);t instanceof Promise&&(t=await t);let s=r(t,i.set);if(s)return s}return t(p,i.set)}catch(e){return this.handleError(e,h)}}async handleError(e,r={headers:{}}){for(let s=0;s<this.event.error.length;s++){let a=this.event.error[s]({code:p(e.message),error:e,set:r});if(a instanceof Promise&&(a=await a),null!=a)return t(a,r)}return new Response("string"==typeof e.cause?e.cause:e.message,{headers:r.headers,status:m(p(e.message))})}listen(e,t){if(!Bun)throw Error("Bun to run");if("string"==typeof e&&Number.isNaN(e=+e))throw Error("Port must be a numeric value");let r=this.handle.bind(this),s="object"==typeof e?{...this.config.serve,...e,fetch:r}:{...this.config.serve,port:e,fetch:r},a=`$$Elysia:${s.port}`;globalThis[a]?(this.server=globalThis[a],this.server.reload(s)):globalThis[a]=this.server=Bun.serve(s);for(let e=0;e<this.event.start.length;e++)this.event.start[e](this);return t&&t(this.server),Promise.all(this.lazyLoadModules).then(()=>{this.server.pendingRequests||Bun.gc(!0)}),this}stop=async()=>{if(!this.server)throw Error("Elysia isn't running. Call `app.listen` to start the server.");this.server.stop();for(let e=0;e<this.event.stop.length;e++)await this.event.stop[e](this)};get modules(){return Promise.all(this.lazyLoadModules)}setModel(e){return Object.entries(e).forEach(([e,t])=>{e in this.store[d]||(this.store[d][e]=t)}),this}}export{Type as t}from"@sinclair/typebox";export{SCHEMA,DEFS,createValidationError,getSchemaValidator,mergeDeep,mergeHook,mergeObjectArray,mapPathnameAndQueryRegEx,mapQuery}from"./utils";export{v as Elysia};
1
+ import{Raikiri as e}from"raikiri";import{mapResponse as t,mapEarlyResponse as r}from"./handler";import{mapQuery as s,clone as a,mergeHook as i,mergeDeep as h,createValidationError as n,getSchemaValidator as o,SCHEMA as l,DEFS as d,getResponseSchemaValidator as u,mapPathnameAndQueryRegEx as f}from"./utils";import{registerSchemaPath as c}from"./schema";import{mapErrorCode as p,mapErrorStatus as m}from"./error";export default class v{store={[l]:{},[d]:{}};decorators=null;event={start:[],request:[],parse:[],transform:[],beforeHandle:[],afterHandle:[],error:[],stop:[]};server=null;$schema=null;router=new e;routes=[];lazyLoadModules=[];constructor(e={}){this.config={...e}}_addHandler(e,t,r,s){t=t.startsWith("/")?t:`/${t}`,this.routes.push({method:e,path:t,handler:r,hooks:i(a(this.event),s)});let h=this.store[d],n=o(s?.schema?.body??this.$schema?.body,h),f=o(s?.schema?.headers??this.$schema?.headers,h,!0),p=o(s?.schema?.params??this.$schema?.params,h),m=o(s?.schema?.query??this.$schema?.query,h),v=u(s?.schema?.response??this.$schema?.response,h);c({schema:this.store[l],hook:s,method:e,path:t,models:this.store[d]});let g=i(a(this.event),s);g.schema||g.transform.length||g.beforeHandle.length||g.error.length||g.afterHandle.length||(g=void 0);let y={handle:r,hooks:g,validator:n||f||p||m||v?{body:n,header:f,params:p,query:m,response:v}:void 0};this.router.add(e,t,y)}onStart(e){return this.event.start.push(e),this}onRequest(e){return this.event.request.push(e),this}onParse(e){return this.event.parse.splice(this.event.parse.length-1,0,e),this}onTransform(e){return this.event.transform.push(e),this}onBeforeHandle(e){return this.event.beforeHandle.push(e),this}onAfterHandle(e){return this.event.afterHandle.push(e),this}onError(e){return this.event.error.push(e),this}onStop(e){return this.event.stop.push(e),this}on(e,t){switch(e){case"start":this.event.start.push(t);break;case"request":this.event.request.push(t);break;case"parse":this.event.parse.push(t);break;case"transform":this.event.transform.push(t);break;case"beforeHandle":this.event.beforeHandle.push(t);break;case"afterHandle":this.event.afterHandle.push(t);break;case"error":this.event.error.push(t);break;case"stop":this.event.stop.push(t)}return this}group(e,t){let r=new v;r.store=this.store;let s=t(r);return s.event.request.length&&(this.event.request=[...this.event.request,...s.event.request]),Object.values(r.routes).forEach(({method:t,path:r,handler:s,hooks:a})=>{"/"===r?this._addHandler(t,e,s,a):this._addHandler(t,`${e}${r}`,s,a)}),this}guard(e,t){let r=new v;r.store=this.store;let s=t(r);return s.event.request.length&&(this.event.request=[...this.event.request,...s.event.request]),Object.values(r.routes).forEach(({method:t,path:r,handler:s,hooks:a})=>{this._addHandler(t,r,s,i(e,a))}),this}use(e){if(e instanceof Promise)return this.lazyLoadModules.push(e.then(e=>"function"==typeof e?e(this):e.default(this))),this;let t=e(this);return t instanceof Promise?(this.lazyLoadModules.push(t),this):t}get(e,t,r){return this._addHandler("GET",e,t,r),this}post(e,t,r){return this._addHandler("POST",e,t,r),this}put(e,t,r){return this._addHandler("PUT",e,t,r),this}patch(e,t,r){return this._addHandler("PATCH",e,t,r),this}delete(e,t,r){return this._addHandler("DELETE",e,t,r),this}options(e,t,r){return this._addHandler("OPTIONS",e,t,r),this}all(e,t,r){return this._addHandler("ALL",e,t,r),this}head(e,t,r){return this._addHandler("HEAD",e,t,r),this}trace(e,t,r){return this._addHandler("TRACE",e,t,r),this}connect(e,t,r){return this._addHandler("CONNECT",e,t,r),this}route(e,t,r,s){return this._addHandler(e,t,r,s),this}state(e,t){return e in this.store||(this.store[e]=t),this}decorate(e,t){return this.decorators||(this.decorators={}),e in this.decorators||(this.decorators[e]=t),this}derive(e){return this.store=h(this.store,e(()=>this.store)),this}inject(e){return this.onTransform(t=>{Object.assign(t,e(t))})}schema(e){let t=this.store[d];return this.$schema={body:o(e.body,t),headers:o(e?.headers,t,!0),params:o(e?.params,t),query:o(e?.query,t),response:o(e?.response,t)},this}handle=async e=>{let i;let h={status:200,headers:{}};this.decorators?((i=a(this.decorators)).request=e,i.set=h,i.store=this.store,i.query={}):i={set:h,store:this.store,request:e,query:{}};try{let a;if(this.event.request.length)for(let e=0;e<this.event.request.length;e++){let t=this.event.request[e](i);if(t instanceof Promise&&(t=await t),t=r(t,h))return t}let o=e.url.match(f);if(!o)throw Error("NOT_FOUND");let l=this.router.match(e.method,o[1])??this.router.match("ALL",o[1]),d=l?.store;if(!d)throw Error("NOT_FOUND");if("GET"!==e.method){let t=e.headers.get("content-type");if(t){let r=t.indexOf(";");if(-1!==r&&(t=t.slice(0,r)),this.event.parse.length)for(let e=0;e<this.event.parse.length;e++){let r=this.event.parse[e](i,t);if(r instanceof Promise&&(r=await r),void 0!==r){a=r;break}}if(void 0===a)switch(t){case"application/json":a=await e.json();break;case"text/plain":a=await e.text();break;case"application/x-www-form-urlencoded":a=s(await e.text())}}}i.body=a,i.params=l.params,o[2]&&(i.query=s(o[2]));let u=d.hooks;if(u?.transform.length)for(let e=0;e<u.transform.length;e++){let t=u.transform[e](i);t instanceof Promise&&await t}if(d.validator){let t=d.validator;if(t.headers){let r={};for(let t in e.headers)r[t]=e.headers.get(t);if(!1===t.headers.Check(r))throw n("header",t.headers,r)}if(!1===t.params?.Check(i.params))throw n("params",t.params,i.params);if(!1===t.query?.Check(i.query))throw n("query",t.query,i.query);if(!1===t.body?.Check(a))throw n("body",t.body,a)}if(u?.beforeHandle.length)for(let e=0;e<u.beforeHandle.length;e++){let t=u.beforeHandle[e](i);if(t instanceof Promise&&(t=await t),null!=t){for(let e=0;e<u.afterHandle.length;e++){let r=u.afterHandle[e](i,t);r instanceof Promise&&(r=await r),r&&(t=r)}let e=r(t,i.set);if(e)return e}}let c=d.handle(i);if(c instanceof Promise&&(c=await c),!1===d.validator?.response?.Check(c))throw n("response",d.validator.response,c);if(u?.afterHandle.length)for(let e=0;e<u.afterHandle.length;e++){let t=u.afterHandle[e](i,c);t instanceof Promise&&(t=await t);let s=r(t,i.set);if(s)return s}return t(c,i.set)}catch(e){return this.handleError(e,h)}};async handleError(e,r={headers:{}}){for(let s=0;s<this.event.error.length;s++){let a=this.event.error[s]({code:p(e.message),error:e,set:r});if(a instanceof Promise&&(a=await a),null!=a)return t(a,r)}return new Response("string"==typeof e.cause?e.cause:e.message,{headers:r.headers,status:m(p(e.message))})}listen=(e,t)=>{if(!Bun)throw Error("Bun to run");if("string"==typeof e&&Number.isNaN(e=+e))throw Error("Port must be a numeric value");let r=this.handle,s="object"==typeof e?{...this.config.serve,...e,fetch:r}:{...this.config.serve,port:e,fetch:r},a=`$$Elysia:${s.port}`;globalThis[a]?(this.server=globalThis[a],this.server.reload(s)):globalThis[a]=this.server=Bun.serve(s);for(let e=0;e<this.event.start.length;e++)this.event.start[e](this);return t&&t(this.server),Promise.all(this.lazyLoadModules).then(()=>{this.server.pendingRequests||Bun.gc(!0)}),this};stop=async()=>{if(!this.server)throw Error("Elysia isn't running. Call `app.listen` to start the server.");this.server.stop();for(let e=0;e<this.event.stop.length;e++)await this.event.stop[e](this)};get modules(){return Promise.all(this.lazyLoadModules)}setModel(e){return Object.entries(e).forEach(([e,t])=>{e in this.store[d]||(this.store[d][e]=t)}),this}}export{Type as t}from"@sinclair/typebox";export{SCHEMA,DEFS,createValidationError,getSchemaValidator,mergeDeep,mergeHook,mergeObjectArray,mapPathnameAndQueryRegEx,mapQuery}from"./utils";export{v as Elysia};
package/package.json CHANGED
@@ -1,53 +1,53 @@
1
1
  {
2
- "name": "elysia",
3
- "description": "Fast, and friendly Bun web framework",
4
- "version": "0.2.5",
5
- "author": {
6
- "name": "saltyAom",
7
- "url": "https://github.com/SaltyAom",
8
- "email": "saltyaom@gmail.com"
9
- },
10
- "main": "./dist/index.js",
11
- "exports": {
12
- "require": "./dist/index.js",
13
- "import": "./dist/index.js",
14
- "node": "./dist/index.js",
15
- "default": "./dist/index.js"
16
- },
17
- "types": "./dist/index.d.ts",
18
- "repository": {
19
- "type": "git",
20
- "url": "https://github.com/elysiajs/elysia"
21
- },
22
- "bugs": "https://github.com/elysiajs/elysia/issues",
23
- "homepage": "https://github.com/elysiajs/elysia",
24
- "keywords": [
25
- "bun",
26
- "http",
27
- "web",
28
- "server"
29
- ],
30
- "license": "MIT",
31
- "scripts": {
32
- "test": "bun wiptest",
33
- "dev": "bun run --hot example/http.ts",
34
- "build": "rimraf dist && swc src -d dist && tsc --project tsconfig.esm.json",
35
- "release": "npm run build && npm run test && npm publish"
36
- },
37
- "dependencies": {
38
- "@sinclair/typebox": "^0.25.21",
39
- "openapi-types": "^12.1.0",
40
- "raikiri": "^0.0.0-beta.5"
41
- },
42
- "devDependencies": {
43
- "@swc/cli": "^0.1.60",
44
- "@swc/core": "^1.3.32",
45
- "@types/node": "^18.11.18",
46
- "@typescript-eslint/eslint-plugin": "^5.48.2",
47
- "@typescript-eslint/parser": "^5.48.2",
48
- "bun-types": "^0.5.0",
49
- "eslint": "^8.32.0",
50
- "rimraf": "^3.0.2",
51
- "typescript": "^4.9.4"
52
- }
2
+ "name": "elysia",
3
+ "description": "Fast, and friendly Bun web framework",
4
+ "version": "0.2.7",
5
+ "author": {
6
+ "name": "saltyAom",
7
+ "url": "https://github.com/SaltyAom",
8
+ "email": "saltyaom@gmail.com"
9
+ },
10
+ "main": "./dist/index.js",
11
+ "exports": {
12
+ "require": "./dist/index.js",
13
+ "import": "./dist/index.js",
14
+ "node": "./dist/index.js",
15
+ "default": "./dist/index.js"
16
+ },
17
+ "types": "./dist/index.d.ts",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "https://github.com/elysiajs/elysia"
21
+ },
22
+ "bugs": "https://github.com/elysiajs/elysia/issues",
23
+ "homepage": "https://github.com/elysiajs/elysia",
24
+ "keywords": [
25
+ "bun",
26
+ "http",
27
+ "web",
28
+ "server"
29
+ ],
30
+ "license": "MIT",
31
+ "scripts": {
32
+ "test": "bun wiptest",
33
+ "dev": "bun run --hot example/http.ts",
34
+ "build": "rimraf dist && swc src -d dist && tsc --project tsconfig.esm.json",
35
+ "release": "npm run build && npm run test && npm publish"
36
+ },
37
+ "dependencies": {
38
+ "@sinclair/typebox": "^0.25.21",
39
+ "openapi-types": "^12.1.0",
40
+ "raikiri": "^0.0.0-beta.5"
41
+ },
42
+ "devDependencies": {
43
+ "@swc/cli": "^0.1.60",
44
+ "@swc/core": "^1.3.32",
45
+ "@types/node": "^18.11.18",
46
+ "@typescript-eslint/eslint-plugin": "^5.48.2",
47
+ "@typescript-eslint/parser": "^5.48.2",
48
+ "bun-types": "^0.5.0",
49
+ "eslint": "^8.32.0",
50
+ "rimraf": "^3.0.2",
51
+ "typescript": "^4.9.4"
52
+ }
53
53
  }