diesel-core 0.0.6 → 0.0.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.
- package/dist/handleRequest.js +1 -1
- package/dist/router.js +1 -1
- package/dist/server.js +1 -1
- package/package.json +1 -1
- package/src/handleRequest.js +18 -20
- package/src/server.js +14 -5
package/dist/handleRequest.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
async function
|
|
1
|
+
async function A(G){const F={};if(!G)return F;return G.split(";").forEach((J)=>{const[U,L]=J.trim().split("=");F[U]=L.split(" ")[0]}),F}function V(G,F){const z={},J=G.split("/"),[U]=F.split("?"),L=U.split("/");if(J.length!==L.length)return null;return J.forEach((X,$)=>{if(X.startsWith(":")){const K=X.slice(1);z[K]=L[$]}}),z}async function B(G){const F=G.headers.get("Content-Type")||"";if(!F)return{};try{if(F.startsWith("application/json"))return await G.json();if(F.startsWith("application/x-www-form-urlencoded")){const z=await G.text();return Object.fromEntries(new URLSearchParams(z))}if(F.startsWith("multipart/form-data")){const z=await G.formData();return j(z)}return new Response({error:"Unknown request body type"})}catch(z){return new Response({error:"Invalid request body format"})}}function j(G){const F={};for(let[z,J]of G.entries())F[z]=J;return F}function M(G,F){let z={},J={},U=!1,L=null,X=null,$=null,K=null,Z=200;return{req:G,url:F,next:()=>{},status(E){return Z=E,this},async body(){if(!K)K=await B(G);return K},setHeader(E,I){return z[E]=I,this},set(E,I){return J[E]=I,this},get(E){return J[E]},setAuth(E){return U=E,this},getAuth(){return U},text(E,I){if(I)Z=I;return new Response(E,{status:Z,headers:z})},json(E,I){if(I)Z=I;return new Response(JSON.stringify(E),{status:Z,headers:{"Content-Type":"application/json",...z}})},html(E,I){if(I)Z=I;return new Response(Bun.file(E),{status:Z,headers:{...z}})},file(E,I){if(I)Z=I;return new Response(Bun.file(E),{status:Z,headers:{...z}})},redirect(E,I){if(I)Z=I;return new Response(null,{status:Z,headers:{Location:E,...z}})},getParams(E){if(!$)$=V(G.routePattern,F.pathname);return E?$[E]:$},getQuery(E){if(!L)L=Object.fromEntries(F.searchParams);return E?L[E]:L},async cookie(E,I,Y={}){let _=`${encodeURIComponent(E)}=${encodeURIComponent(I)}`;if(Y.maxAge)_+=`; Max-Age=${Y.maxAge}`;if(Y.expires)_+=`; Expires=${Y.expires.toUTCString()}`;if(Y.path)_+=`; Path=${Y.path}`;if(Y.domain)_+=`; Domain=${Y.domain}`;if(Y.secure)_+="; Secure";if(Y.httpOnly)_+="; HttpOnly";if(Y.sameSite)_+=`; SameSite=${Y.sameSite}`;if(z["Set-Cookie"]){const O=Array.isArray(z["Set-Cookie"])?z["Set-Cookie"]:[z["Set-Cookie"]];O.push(_),z["Set-Cookie"]=O}else z["Set-Cookie"]=_;return this},async getCookie(E){if(!X)X=await A(G.headers.get("cookie"));return E?X[E]:X}}}async function N(G,F){for(let z of G){const J=await z(F);if(J)return J}}var W={};async function D(G,F,z){const J=M(G,F);if(z.hasOnReqHook)await z.hooks.onRequest(J);if(z.hasMiddleware){const L=[...z.globalMiddlewares,...z.middlewares.get(F.pathname)||[]],X=await N(L,J);if(X)return X}let U;if(W[F.pathname+G.method])U=W[F.pathname+G.method];else U=z.trie.search(F.pathname,G.method),W[F.pathname+G.method]=U;if(!U||!U.handler)return new Response(`Route not found for ${F.pathname}`,{status:404});if(U.method!==G.method)return new Response("Method not allowed",{status:405});if(U.isDynamic)G.routePattern=U.path;if(z.hasPreHandlerHook){const L=await z.hooks.preHandler(J);if(L)return L}try{const L=await U.handler(J);if(z.hasPostHandlerHook)await z.hooks.postHandler(J);if(z.hasOnSendHook){const X=await z.hooks.onSend(L,J);if(X)return X}return L??new Response("No response from handler",{status:204})}catch(L){return new Response("Internal Server Error",{status:500})}}export{D as default};
|
package/dist/router.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
class V{constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[],this.subMiddlewares=new Map}}class M{constructor(){this.root=new V}insert(L,G){let E=this.root;const
|
|
1
|
+
class V{constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[],this.subMiddlewares=new Map}}class M{constructor(){this.root=new V}insert(L,G){let E=this.root;const z=L.split("/").filter(Boolean);if(L==="/"){E.isEndOfWord=!0,E.handler.push(G.handler),E.path=L,E.method.push(G.method);return}for(let U of z){let F=!1,X=U;if(U.startsWith(":"))F=!0,X=":";if(!E.children[X])E.children[X]=new V;E=E.children[X],E.isDynamic=F,E.pattern=U}E.isEndOfWord=!0,E.method.push(G.method),E.handler.push(G.handler),E.path=L}insertMidl(L){if(!this.root.subMiddlewares.has(L))this.root.subMiddlewares.set(L)}search(L,G){let E=this.root;const z=L.split("/").filter(Boolean);for(let F of z){let X=F;if(!E.children[X])if(E.children[":"])E=E.children[":"];else return null;else E=E.children[X]}let U=E.method.indexOf(G);if(U!==-1)return{path:E.path,handler:E.handler[U],isDynamic:E.isDynamic,pattern:E.pattern,method:E.method[U]};return{path:E.path,handler:E.handler,isDynamic:E.isDynamic,pattern:E.pattern,method:E.method[U]}}getAllRoutes(){const L=[],G=(E,z)=>{if(E.isEndOfWord)L.push({path:z,handler:E.handler,isImportant:E.isImportant,isDynamic:E.isDynamic,pattern:E.pattern});for(let U in E.children){const F=E.children[U],X=z+(U===":"?"/:"+F.pattern:"/"+U);G(F,X)}};return G(this.root,""),L}}async function v(L){const G={};if(!L)return G;return L.split(";").forEach((z)=>{const[U,F]=z.trim().split("=");G[U]=F.split(" ")[0]}),G}function N(L,G){const E={},z=L.split("/"),[U]=G.split("?"),F=U.split("/");if(z.length!==F.length)return null;return z.forEach((X,$)=>{if(X.startsWith(":")){const A=X.slice(1);E[A]=F[$]}}),E}async function I(L){const G=L.headers.get("Content-Type")||"";if(!G)return{};try{if(G.startsWith("application/json"))return await L.json();if(G.startsWith("application/x-www-form-urlencoded")){const E=await L.text();return Object.fromEntries(new URLSearchParams(E))}if(G.startsWith("multipart/form-data")){const E=await L.formData();return C(E)}return new Response({error:"Unknown request body type"})}catch(E){return new Response({error:"Invalid request body format"})}}function C(L){const G={};for(let[E,z]of L.entries())G[E]=z;return G}function B(L,G){let E={},z={},U=!1,F=null,X=null,$=null,A=null,_=200;return{req:L,url:G,next:()=>{},status(J){return _=J,this},async body(){if(!A)A=await I(L);return A},setHeader(J,Y){return E[J]=Y,this},set(J,Y){return z[J]=Y,this},get(J){return z[J]},setAuth(J){return U=J,this},getAuth(){return U},text(J,Y){if(Y)_=Y;return new Response(J,{status:_,headers:E})},json(J,Y){if(Y)_=Y;return new Response(JSON.stringify(J),{status:_,headers:{"Content-Type":"application/json",...E}})},html(J,Y){if(Y)_=Y;return new Response(Bun.file(J),{status:_,headers:{...E}})},file(J,Y){if(Y)_=Y;return new Response(Bun.file(J),{status:_,headers:{...E}})},redirect(J,Y){if(Y)_=Y;return new Response(null,{status:_,headers:{Location:J,...E}})},getParams(J){if(!$)$=N(L.routePattern,G.pathname);return J?$[J]:$},getQuery(J){if(!F)F=Object.fromEntries(G.searchParams);return J?F[J]:F},async cookie(J,Y,Z={}){let W=`${encodeURIComponent(J)}=${encodeURIComponent(Y)}`;if(Z.maxAge)W+=`; Max-Age=${Z.maxAge}`;if(Z.expires)W+=`; Expires=${Z.expires.toUTCString()}`;if(Z.path)W+=`; Path=${Z.path}`;if(Z.domain)W+=`; Domain=${Z.domain}`;if(Z.secure)W+="; Secure";if(Z.httpOnly)W+="; HttpOnly";if(Z.sameSite)W+=`; SameSite=${Z.sameSite}`;if(E["Set-Cookie"]){const b=Array.isArray(E["Set-Cookie"])?E["Set-Cookie"]:[E["Set-Cookie"]];b.push(W),E["Set-Cookie"]=b}else E["Set-Cookie"]=W;return this},async getCookie(J){if(!X)X=await v(L.headers.get("cookie"));return J?X[J]:X}}}async function w(L,G){for(let E of L){const z=await E(G);if(z)return z}}var Q={};async function T(L,G,E){const z=B(L,G);if(E.hasOnReqHook)await E.hooks.onRequest(z);if(E.hasMiddleware){const F=[...E.globalMiddlewares,...E.middlewares.get(G.pathname)||[]],X=await w(F,z);if(X)return X}let U;if(Q[G.pathname+L.method])U=Q[G.pathname+L.method];else U=E.trie.search(G.pathname,L.method),Q[G.pathname+L.method]=U;if(!U||!U.handler)return new Response(`Route not found for ${G.pathname}`,{status:404});if(U.method!==L.method)return new Response("Method not allowed",{status:405});if(U.isDynamic)L.routePattern=U.path;if(E.hasPreHandlerHook){const F=await E.hooks.preHandler(z);if(F)return F}try{const F=await U.handler(z);if(E.hasPostHandlerHook)await E.hooks.postHandler(z);if(E.hasOnSendHook){const X=await E.hooks.onSend(F,z);if(X)return X}return F??new Response("No response from handler",{status:204})}catch(F){return new Response("Internal Server Error",{status:500})}}class j{constructor(){this.routes=new Map,this.globalMiddlewares=[],this.middlewares=new Map,this.trie=new M,this.hasMiddleware=!1,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hooks={onRequest:null,preHandler:null,postHandler:null,onSend:null,onError:null,onClose:null}}addHooks(L,G){if(typeof L!=="string")throw new Error("hookName must be a string");if(typeof G!=="function")throw new Error("callback must be a instance of function");if(this.hooks.hasOwnProperty(L))this.hooks[L]=G;else throw new Error(`Unknown hook type: ${L}`)}compile(){if(this.globalMiddlewares.length>0)this.hasMiddleware=!0;for(let[L,G]of this.middlewares.entries())if(G.length>0){this.hasMiddleware=!0;break}if(this.hooks.onRequest)this.hasOnReqHook=!0;if(this.hooks.preHandler)this.hasPreHandlerHook=!0;if(this.hooks.postHandler)this.hasPostHandlerHook=!0;if(this.hooks.onSend)this.hasOnSendHook=!0}listen(L,G,{sslCert:E=null,sslKey:z=null}={}){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");if(typeof L!=="number")throw new Error("Port must be a numeric value");this.compile();const U={port:L,fetch:async(X)=>{const $=new URL(X.url);try{return await T(X,$,this)}catch(A){return new Response("Internal Server Error",{status:500})}},onClose(){console.log("Server is shutting down...")}};if(E&&z)U.certFile=E,U.keyFile=z;const F=Bun.serve(U);if(typeof G==="function")return G();if(E&&z)console.log(`HTTPS server is running on https://localhost:${L}`);else console.log(`HTTP server is running on http://localhost:${L}`);return F}register(L,G){if(typeof L!=="string")throw new Error("path must be a string");if(typeof G!=="object")throw new Error("handler parameter should be a instance of router object",G);const E=Object.entries(G.trie.root.children);G.trie.root.subMiddlewares.forEach((z,U)=>{if(!this.middlewares.has(L+U))this.middlewares.set(L+U,[]);if(!this.middlewares.get(L+U).includes(...z))this.middlewares.get(L+U).push(...z)});for(let[z,U]of E){const F=L+U?.path,X=U.handler[0],$=U.method[0];this.trie.insert(F,{handler:X,method:$})}G.trie=new M}#E(L,G,E){if(typeof G!=="string")throw new Error("Path must be a string type");if(typeof L!=="string")throw new Error("method must be a string type");const z=E.slice(0,-1);if(!this.middlewares.has(G))this.middlewares.set(G,[]);if(G==="/")z.forEach((F)=>{if(!this.globalMiddlewares.includes(F))this.globalMiddlewares.push(F)});else if(!this.middlewares.get(G).includes(...z))this.middlewares.get(G).push(...z);const U=E[E.length-1];this.trie.insert(G,{handler:U,method:L})}use(L,G){if(typeof L==="function"){if(!this.globalMiddlewares.includes(L))return this.globalMiddlewares.push(L)}const E=L;if(!this.middlewares.has(E))this.middlewares.set(E,[]);if(!this.middlewares.get(E).includes(G))this.middlewares.get(E).push(G)}get(L,...G){return this.#E("GET",L,G),this}post(L,...G){return this.#E("POST",L,G),this}put(L,...G){return this.#E("PUT",L,G),this}patch(L,...G){return this.#E("PATCH",L,G),this}delete(L,...G){return this.#E("DELETE",L,G),this}}var K=j;class D extends K{constructor(){super()}#E(L,G,E){if(!this.trie.root.subMiddlewares.has(G))this.trie.root.subMiddlewares.set(G,[]);const z=E.slice(0,-1);if(!this.trie.root.subMiddlewares.get(G).includes(...z))this.trie.root.subMiddlewares.get(G).push(...z);const U=E[E.length-1];this.trie.insert(G,{handler:U,method:L})}get(L,...G){return this.#E("GET",L,G)}post(L,...G){return this.#E("POST",L,G)}put(L,...G){return this.#E("PUT",L,G)}patch(L,...G){if(G.length>0)return this.#E("PATCH",L,G)}delete(L,...G){return this.#E("DELETE",L,G)}}var y=D;export{y as default};
|
package/dist/server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
class B{constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[],this.subMiddlewares=new Map}}class
|
|
1
|
+
class B{constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[],this.subMiddlewares=new Map}}class V{constructor(){this.root=new B}insert(F,G){let z=this.root;const L=F.split("/").filter(Boolean);if(F==="/"){z.isEndOfWord=!0,z.handler.push(G.handler),z.path=F,z.method.push(G.method);return}for(let J of L){let U=!1,Y=J;if(J.startsWith(":"))U=!0,Y=":";if(!z.children[Y])z.children[Y]=new B;z=z.children[Y],z.isDynamic=U,z.pattern=J}z.isEndOfWord=!0,z.method.push(G.method),z.handler.push(G.handler),z.path=F}insertMidl(F){if(!this.root.subMiddlewares.has(F))this.root.subMiddlewares.set(F)}search(F,G){let z=this.root;const L=F.split("/").filter(Boolean);for(let U of L){let Y=U;if(!z.children[Y])if(z.children[":"])z=z.children[":"];else return null;else z=z.children[Y]}let J=z.method.indexOf(G);if(J!==-1)return{path:z.path,handler:z.handler[J],isDynamic:z.isDynamic,pattern:z.pattern,method:z.method[J]};return{path:z.path,handler:z.handler,isDynamic:z.isDynamic,pattern:z.pattern,method:z.method[J]}}getAllRoutes(){const F=[],G=(z,L)=>{if(z.isEndOfWord)F.push({path:L,handler:z.handler,isImportant:z.isImportant,isDynamic:z.isDynamic,pattern:z.pattern});for(let J in z.children){const U=z.children[J],Y=L+(J===":"?"/:"+U.pattern:"/"+J);G(U,Y)}};return G(this.root,""),F}}async function b(F){const G={};if(!F)return G;return F.split(";").forEach((L)=>{const[J,U]=L.trim().split("=");G[J]=U.split(" ")[0]}),G}function v(F,G){const z={},L=F.split("/"),[J]=G.split("?"),U=J.split("/");if(L.length!==U.length)return null;return L.forEach((Y,E)=>{if(Y.startsWith(":")){const A=Y.slice(1);z[A]=U[E]}}),z}async function T(F){const G=F.headers.get("Content-Type")||"";if(!G)return{};try{if(G.startsWith("application/json"))return await F.json();if(G.startsWith("application/x-www-form-urlencoded")){const z=await F.text();return Object.fromEntries(new URLSearchParams(z))}if(G.startsWith("multipart/form-data")){const z=await F.formData();return N(z)}return new Response({error:"Unknown request body type"})}catch(z){return new Response({error:"Invalid request body format"})}}function N(F){const G={};for(let[z,L]of F.entries())G[z]=L;return G}function Q(F,G){let z={},L={},J=!1,U=null,Y=null,E=null,A=null,$=200;return{req:F,url:G,next:()=>{},status(X){return $=X,this},async body(){if(!A)A=await T(F);return A},setHeader(X,Z){return z[X]=Z,this},set(X,Z){return L[X]=Z,this},get(X){return L[X]},setAuth(X){return J=X,this},getAuth(){return J},text(X,Z){if(Z)$=Z;return new Response(X,{status:$,headers:z})},json(X,Z){if(Z)$=Z;return new Response(JSON.stringify(X),{status:$,headers:{"Content-Type":"application/json",...z}})},html(X,Z){if(Z)$=Z;return new Response(Bun.file(X),{status:$,headers:{...z}})},file(X,Z){if(Z)$=Z;return new Response(Bun.file(X),{status:$,headers:{...z}})},redirect(X,Z){if(Z)$=Z;return new Response(null,{status:$,headers:{Location:X,...z}})},getParams(X){if(!E)E=v(F.routePattern,G.pathname);return X?E[X]:E},getQuery(X){if(!U)U=Object.fromEntries(G.searchParams);return X?U[X]:U},async cookie(X,Z,_={}){let W=`${encodeURIComponent(X)}=${encodeURIComponent(Z)}`;if(_.maxAge)W+=`; Max-Age=${_.maxAge}`;if(_.expires)W+=`; Expires=${_.expires.toUTCString()}`;if(_.path)W+=`; Path=${_.path}`;if(_.domain)W+=`; Domain=${_.domain}`;if(_.secure)W+="; Secure";if(_.httpOnly)W+="; HttpOnly";if(_.sameSite)W+=`; SameSite=${_.sameSite}`;if(z["Set-Cookie"]){const K=Array.isArray(z["Set-Cookie"])?z["Set-Cookie"]:[z["Set-Cookie"]];K.push(W),z["Set-Cookie"]=K}else z["Set-Cookie"]=W;return this},async getCookie(X){if(!Y)Y=await b(F.headers.get("cookie"));return X?Y[X]:Y}}}async function I(F,G){for(let z of F){const L=await z(G);if(L)return L}}var M={};async function j(F,G,z){const L=Q(F,G);if(z.hasOnReqHook)await z.hooks.onRequest(L);if(z.hasMiddleware){const U=[...z.globalMiddlewares,...z.middlewares.get(G.pathname)||[]],Y=await I(U,L);if(Y)return Y}let J;if(M[G.pathname+F.method])J=M[G.pathname+F.method];else J=z.trie.search(G.pathname,F.method),M[G.pathname+F.method]=J;if(!J||!J.handler)return new Response(`Route not found for ${G.pathname}`,{status:404});if(J.method!==F.method)return new Response("Method not allowed",{status:405});if(J.isDynamic)F.routePattern=J.path;if(z.hasPreHandlerHook){const U=await z.hooks.preHandler(L);if(U)return U}try{const U=await J.handler(L);if(z.hasPostHandlerHook)await z.hooks.postHandler(L);if(z.hasOnSendHook){const Y=await z.hooks.onSend(U,L);if(Y)return Y}return U??new Response("No response from handler",{status:204})}catch(U){return new Response("Internal Server Error",{status:500})}}class D{constructor(){this.routes=new Map,this.globalMiddlewares=[],this.middlewares=new Map,this.trie=new V,this.hasMiddleware=!1,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hooks={onRequest:null,preHandler:null,postHandler:null,onSend:null,onError:null,onClose:null}}addHooks(F,G){if(typeof F!=="string")throw new Error("hookName must be a string");if(typeof G!=="function")throw new Error("callback must be a instance of function");if(this.hooks.hasOwnProperty(F))this.hooks[F]=G;else throw new Error(`Unknown hook type: ${F}`)}compile(){if(this.globalMiddlewares.length>0)this.hasMiddleware=!0;for(let[F,G]of this.middlewares.entries())if(G.length>0){this.hasMiddleware=!0;break}if(this.hooks.onRequest)this.hasOnReqHook=!0;if(this.hooks.preHandler)this.hasPreHandlerHook=!0;if(this.hooks.postHandler)this.hasPostHandlerHook=!0;if(this.hooks.onSend)this.hasOnSendHook=!0}listen(F,G,{sslCert:z=null,sslKey:L=null}={}){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");if(typeof F!=="number")throw new Error("Port must be a numeric value");this.compile();const J={port:F,fetch:async(Y)=>{const E=new URL(Y.url);try{return await j(Y,E,this)}catch(A){return new Response("Internal Server Error",{status:500})}},onClose(){console.log("Server is shutting down...")}};if(z&&L)J.certFile=z,J.keyFile=L;const U=Bun.serve(J);if(typeof G==="function")return G();if(z&&L)console.log(`HTTPS server is running on https://localhost:${F}`);else console.log(`HTTP server is running on http://localhost:${F}`);return U}register(F,G){if(typeof F!=="string")throw new Error("path must be a string");if(typeof G!=="object")throw new Error("handler parameter should be a instance of router object",G);const z=Object.entries(G.trie.root.children);G.trie.root.subMiddlewares.forEach((L,J)=>{if(!this.middlewares.has(F+J))this.middlewares.set(F+J,[]);if(!this.middlewares.get(F+J).includes(...L))this.middlewares.get(F+J).push(...L)});for(let[L,J]of z){const U=F+J?.path,Y=J.handler[0],E=J.method[0];this.trie.insert(U,{handler:Y,method:E})}G.trie=new V}#z(F,G,z){if(typeof G!=="string")throw new Error("Path must be a string type");if(typeof F!=="string")throw new Error("method must be a string type");const L=z.slice(0,-1);if(!this.middlewares.has(G))this.middlewares.set(G,[]);if(G==="/")L.forEach((U)=>{if(!this.globalMiddlewares.includes(U))this.globalMiddlewares.push(U)});else if(!this.middlewares.get(G).includes(...L))this.middlewares.get(G).push(...L);const J=z[z.length-1];this.trie.insert(G,{handler:J,method:F})}use(F,G){if(typeof F==="function"){if(!this.globalMiddlewares.includes(F))return this.globalMiddlewares.push(F)}const z=F;if(!this.middlewares.has(z))this.middlewares.set(z,[]);if(!this.middlewares.get(z).includes(G))this.middlewares.get(z).push(G)}get(F,...G){return this.#z("GET",F,G),this}post(F,...G){return this.#z("POST",F,G),this}put(F,...G){return this.#z("PUT",F,G),this}patch(F,...G){return this.#z("PATCH",F,G),this}delete(F,...G){return this.#z("DELETE",F,G),this}}var H=D;export{H as default};
|
package/package.json
CHANGED
package/src/handleRequest.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import createCtx from "./ctx";
|
|
2
2
|
|
|
3
|
+
const routeCache = {}
|
|
4
|
+
|
|
3
5
|
export default async function handleRequest(req, url, diesel) {
|
|
4
6
|
|
|
5
7
|
const ctx = createCtx(req, url);
|
|
@@ -21,11 +23,22 @@ export default async function handleRequest(req, url, diesel) {
|
|
|
21
23
|
}
|
|
22
24
|
|
|
23
25
|
// Try to find the route handler in the trie
|
|
24
|
-
|
|
26
|
+
let routeHandler;
|
|
27
|
+
if(routeCache[url.pathname+req.method]) {
|
|
28
|
+
routeHandler = routeCache[url.pathname+req.method]
|
|
29
|
+
} else {
|
|
30
|
+
routeHandler = diesel.trie.search(url.pathname, req.method);
|
|
31
|
+
routeCache[url.pathname+req.method]=routeHandler
|
|
32
|
+
}
|
|
25
33
|
|
|
26
34
|
// Early return if route or method is not found
|
|
27
|
-
if (!routeHandler || !routeHandler.handler)
|
|
28
|
-
|
|
35
|
+
if (!routeHandler || !routeHandler.handler) {
|
|
36
|
+
return new Response(`Route not found for ${url.pathname}`, { status: 404 })
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
if (routeHandler.method !== req.method) {
|
|
40
|
+
return new Response("Method not allowed", { status: 405 })
|
|
41
|
+
}
|
|
29
42
|
|
|
30
43
|
// If the route is dynamic, we only set routePattern if necessary
|
|
31
44
|
if (routeHandler.isDynamic) req.routePattern = routeHandler.path;
|
|
@@ -52,9 +65,9 @@ export default async function handleRequest(req, url, diesel) {
|
|
|
52
65
|
if(hookResponse) return hookResponse
|
|
53
66
|
}
|
|
54
67
|
|
|
55
|
-
return result ??
|
|
68
|
+
return result ?? new Response("No response from handler", { status: 204 })
|
|
56
69
|
} catch (error) {
|
|
57
|
-
return
|
|
70
|
+
return new Response("Internal Server Error", { status: 500 });
|
|
58
71
|
}
|
|
59
72
|
}
|
|
60
73
|
|
|
@@ -66,19 +79,4 @@ async function executeMiddleware(middlewares, ctx) {
|
|
|
66
79
|
}
|
|
67
80
|
}
|
|
68
81
|
|
|
69
|
-
// Reused response functions for better organization and clarity
|
|
70
|
-
function responseNotFound(path) {
|
|
71
|
-
return new Response(`Route not found for ${path}`, { status: 404 });
|
|
72
|
-
}
|
|
73
82
|
|
|
74
|
-
function responseMethodNotAllowed() {
|
|
75
|
-
return new Response("Method not allowed", { status: 405 });
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
function responseNoHandler() {
|
|
79
|
-
return new Response("No response from handler", { status: 204 });
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
function responseServerError() {
|
|
83
|
-
return new Response("Internal Server Error", { status: 500 });
|
|
84
|
-
}
|
package/src/server.js
CHANGED
|
@@ -23,6 +23,12 @@ class Diesel {
|
|
|
23
23
|
}
|
|
24
24
|
|
|
25
25
|
addHooks(typeOfHook,fnc){
|
|
26
|
+
if(typeof typeOfHook !== 'string'){
|
|
27
|
+
throw new Error("hookName must be a string")
|
|
28
|
+
}
|
|
29
|
+
if(typeof fnc !== 'function'){
|
|
30
|
+
throw new Error("callback must be a instance of function")
|
|
31
|
+
}
|
|
26
32
|
if (this.hooks.hasOwnProperty(typeOfHook)) {
|
|
27
33
|
this.hooks[typeOfHook] = fnc; // Overwrite or set the hook
|
|
28
34
|
} else {
|
|
@@ -49,7 +55,7 @@ class Diesel {
|
|
|
49
55
|
|
|
50
56
|
}
|
|
51
57
|
|
|
52
|
-
listen(port, { sslCert = null, sslKey = null } = {}
|
|
58
|
+
listen(port, callback,{ sslCert = null, sslKey = null } = {}) {
|
|
53
59
|
if (typeof Bun === 'undefined')
|
|
54
60
|
throw new Error(
|
|
55
61
|
'.listen() is designed to run on Bun only...'
|
|
@@ -82,7 +88,7 @@ class Diesel {
|
|
|
82
88
|
}
|
|
83
89
|
const server = Bun.serve(options);
|
|
84
90
|
|
|
85
|
-
Bun?.gc(false)
|
|
91
|
+
// Bun?.gc(false)
|
|
86
92
|
|
|
87
93
|
if (typeof callback === "function") {
|
|
88
94
|
return callback();
|
|
@@ -98,6 +104,12 @@ class Diesel {
|
|
|
98
104
|
}
|
|
99
105
|
|
|
100
106
|
register(pathPrefix, handlerInstance) {
|
|
107
|
+
if (typeof pathPrefix !== 'string') {
|
|
108
|
+
throw new Error("path must be a string")
|
|
109
|
+
}
|
|
110
|
+
if(typeof handlerInstance !== 'object'){
|
|
111
|
+
throw new Error("handler parameter should be a instance of router object",handlerInstance)
|
|
112
|
+
}
|
|
101
113
|
const routeEntries = Object.entries(handlerInstance.trie.root.children);
|
|
102
114
|
// console.log(handlerInstance.trie.root);
|
|
103
115
|
handlerInstance.trie.root.subMiddlewares.forEach((middleware, path) => {
|
|
@@ -178,9 +190,6 @@ class Diesel {
|
|
|
178
190
|
}
|
|
179
191
|
|
|
180
192
|
patch(path, ...handlers) {
|
|
181
|
-
if(typeof path !== "string"){
|
|
182
|
-
throw new Error("Path must be a string type");
|
|
183
|
-
}
|
|
184
193
|
this.#addRoute("PATCH", path, handlers);
|
|
185
194
|
return this
|
|
186
195
|
}
|