diesel-core 1.0.21 → 1.0.22
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/main.js +1 -1
- package/package.json +1 -1
package/dist/handleRequest.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
function B(G){let{time:K=60000,max:L=100,message:z="Rate limit exceeded. Please try again later."}=G,J=new Map;return(X)=>{let Y=new Date,V=X.ip;if(!J.has(V))J.set(V,{count:0,startTime:Y});let O=J.get(V);if(O)if(Y-O.startTime>K)O.count=1,O.startTime=Y;else O.count++;if(O&&O.count>L)return X.json({error:z},429)}}function W(G){switch(G.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}var E=(G,K,L,z)=>{if(L>z)return!1;let J=L+(z-L)/2;if(G[J]==K)return!0;if(G[J]>K)return E(G,K,L,J-1);return E(G,K,J+1,z)};function j(G,K,L){let z=new Headers({"Cache-Control":"no-cache"}),J=null,X=null,Y=null,V=null,O={};return{req:G,server:K,url:L,setHeader(A,Z){return z.set(A,Z),this},removeHeader(A){return z.delete(A),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!J)try{J=Object.fromEntries(this.url.searchParams)}catch(A){throw new Error("Failed to parse query parameters")}return J},get params(){if(!X&&this.req.routePattern)try{X=F(this.req.routePattern,this.url.pathname)}catch(A){throw new Error("Failed to extract route parameters")}return X??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!V)V=(async()=>{let A=await C(this.req);if(A.error)throw new Error(A.error);return Object.keys(A).length===0?null:A})();return V},set(A,Z){return O[A]=Z,this},get(A){return O[A]},text(A,Z=200){if(!z.has("Content-Type"))z.set("Content-Type","text/plain; charset=utf-8");return new Response(A,{status:Z,headers:z})},send(A,Z=200){let $=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),U=A instanceof Uint8Array?"Uint8Array":A instanceof ArrayBuffer?"ArrayBuffer":typeof A;if(!z.has("Content-Type"))z.set("Content-Type",$.get(U)??"text/plain; charset=utf-8");let Q=U==="object"&&A!==null?JSON.stringify(A):A;return new Response(Q,{status:Z,headers:z})},json(A,Z=200){if(!z.has("Content-Type"))z.set("Content-Type","application/json; charset=utf-8");return new Response(JSON.stringify(A),{status:Z,headers:z})},file(A,Z=200,$){let U=Bun.file(A);if(!z.has("Content-Type"))z.set("Content-Type",$??W(A));return new Response(U,{status:Z,headers:z})},redirect(A,Z=302){return z.set("Location",A),new Response(null,{status:Z,headers:z})},setCookie(A,Z,$={}){let U=`${encodeURIComponent(A)}=${encodeURIComponent(Z)}`;if($.maxAge)U+=`; Max-Age=${$.maxAge}`;if($.expires)U+=`; Expires=${$.expires.toUTCString()}`;if($.path)U+=`; Path=${$.path}`;if($.domain)U+=`; Domain=${$.domain}`;if($.secure)U+="; Secure";if($.httpOnly)U+="; HttpOnly";if($.sameSite)U+=`; SameSite=${$.sameSite}`;return z.append("Set-Cookie",U),this},get cookies(){if(!Y){let A=this.req.headers.get("cookie");Y=A?D(A):{}}return Y}}}function D(G){return Object.fromEntries(G.split(";").map((K)=>{let[L,...z]=K.trim().split("=");return[L,decodeURIComponent(z.join("="))]}))}function F(G,K){let L={},z=G.split("/"),[J]=K.split("?"),X=J.split("/");if(z.length!==X.length)return null;for(let Y=0;Y<z.length;Y++)if(z[Y].startsWith(":"))L[z[Y].slice(1)]=X[Y];return L}async function C(G){let K=G.headers.get("Content-Type");if(!K)return{};if(G.headers.get("Content-Length")==="0"||!G.body)return{};try{if(K.startsWith("application/json"))return await G.json();if(K.startsWith("application/x-www-form-urlencoded")){let z=await G.text();return Object.fromEntries(new URLSearchParams(z))}if(K.startsWith("multipart/form-data")){let z=await G.formData(),J={};for(let[X,Y]of z.entries())J[X]=Y;return J}return{error:"Unknown request body type"}}catch(z){return{error:"Invalid request body format"}}}async function b(G,K,L,z){let J=j(G,K,L),X=z.trie.search(L.pathname,G.method);if(G.routePattern=X?.path,z.hasFilterEnabled){let O=G.routePattern??L.pathname,A=await I(z,O,J,K);if(A)return A}if(z.hasMiddleware){let O=await N(z.globalMiddlewares,J,K);if(O)return O;let A=z.middlewares.get(L.pathname)||[],Z=await N(A,J,K);if(Z)return Z}if(!X?.handler||X.method!==G.method){if(z.staticPath){let O=await M(z,L.pathname,J);if(O)return O;let A=z.trie.search("*",G.method);if(A?.handler)return await A.handler(J)}if(z.hooks.routeNotFound&&!X?.handler){let O=await z.hooks.routeNotFound(J);if(O)return O}if(!X||!X?.handler?.length)return _(404,`Route not found for ${L.pathname}`);if(X?.method!==G.method)return _(405,"Method not allowed")}if(z.hooks.preHandler){let O=await z.hooks.preHandler(J);if(O)return O}let Y=X.handler(J),V=Y instanceof Promise?await Y:Y;if(z.hooks.postHandler)await z.hooks.postHandler(J);if(z.hooks.onSend){let O=await z.hooks.onSend(J,V);if(O)return O}return V??_(204,"No response from this handler")}async function N(G,K,L){for(let z of G){let J=await z(K,L);if(J)return J}return null}async function I(G,K,L,z){if(!G.filters.has(K))if(G.filterFunction.length)for(let J of G.filterFunction){let X=await J(L,z);if(X)return X}else return L.json({error:!0,message:"Protected route, authentication required",status:401},401)}function _(G,K){return new Response(JSON.stringify({error:!0,message:K,status:G}),{status:G,headers:{"Content-Type":"application/json"}})}async function M(G,K,L){if(!G.staticPath)return null;let z=`${G.staticPath}${K}`;if(await Bun.file(z).exists()){let X=W(z);return L.file(z,200,X)}return null}export{M as handleStaticFiles,I as handleFilterRequest,_ as generateErrorResponse,b as default};
|
package/dist/main.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
class Y{children;isEndOfWord;handler;isDynamic;pattern;path;method;constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[]}}class U{root;constructor(){this.root=new Y}insert(w,F){let E=this.root,$=w.split("/").filter(Boolean);if(w==="/"){E.isEndOfWord=!0,E.handler.push(F.handler),E.path=w,E.method.push(F.method);return}for(let R of $){let L=!1,J=R;if(R.startsWith(":"))L=!0,J=":";if(!E.children[J])E.children[J]=new Y;E=E.children[J],E.isDynamic=L,E.pattern=R,E.method.push(F.method),E.handler.push(F.handler),E.path=w}E.isEndOfWord=!0,E.method.push(F.method),E.handler.push(F.handler),E.path=w}search(w,F){let E=this.root,$=w.split("/").filter(Boolean),R=$.length;for(let G of $){let A=G;if(!E.children[A])if(E.children[":"])E=E.children[":"];else return null;else E=E.children[A]}let L=E.path.split("/").filter(Boolean);if(R!==L.length)return null;let J=E.method.indexOf(F);if(J!==-1)return{path:E.path,handler:E.handler[J],isDynamic:E.isDynamic,pattern:E.pattern,method:E.method[J]};return{path:E.path,handler:E.handler,isDynamic:E.isDynamic,pattern:E.pattern,method:E.method[J]}}}function D(w){let{time:F=60000,max:E=100,message:$="Rate limit exceeded. Please try again later."}=w,R=new Map;return(L)=>{let J=new Date,G=L.ip;if(!R.has(G))R.set(G,{count:0,startTime:J});let A=R.get(G);if(A)if(J-A.startTime>F)A.count=1,A.startTime=J;else A.count++;if(A&&A.count>E)return L.json({error:$},429)}}function X(w){switch(w.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}var V=(w,F,E,$)=>{if(E>$)return!1;let R=E+($-E)/2;if(w[R]==F)return!0;if(w[R]>F)return V(w,F,E,R-1);return V(w,F,R+1,$)};function Z(w,F,E){let $=new Headers({"Cache-Control":"no-cache"}),R=null,L=null,J=null,G=null,A={};return{req:w,server:F,url:E,setHeader(z,C){return $.set(z,C),this},removeHeader(z){return $.delete(z),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!R)try{R=Object.fromEntries(this.url.searchParams)}catch(z){throw new Error("Failed to parse query parameters")}return R},get params(){if(!L&&this.req.routePattern)try{L=Q(this.req.routePattern,this.url.pathname)}catch(z){throw new Error("Failed to extract route parameters")}return L??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!G)G=(async()=>{let z=await x(this.req);if(z.error)throw new Error(z.error);return Object.keys(z).length===0?null:z})();return G},set(z,C){return A[z]=C,this},get(z){return A[z]},text(z,C=200){if(!$.has("Content-Type"))$.set("Content-Type","text/plain; charset=utf-8");return new Response(z,{status:C,headers:$})},send(z,C=200){let K=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),N=z instanceof Uint8Array?"Uint8Array":z instanceof ArrayBuffer?"ArrayBuffer":typeof z;if(!$.has("Content-Type"))$.set("Content-Type",K.get(N)??"text/plain; charset=utf-8");let j=N==="object"&&z!==null?JSON.stringify(z):z;return new Response(j,{status:C,headers:$})},json(z,C=200){if(!$.has("Content-Type"))$.set("Content-Type","application/json; charset=utf-8");return new Response(JSON.stringify(z),{status:C,headers:$})},file(z,C=200,K){let N=Bun.file(z);if(!$.has("Content-Type"))$.set("Content-Type",K??X(z));return new Response(N,{status:C,headers:$})},redirect(z,C=302){return $.set("Location",z),new Response(null,{status:C,headers:$})},setCookie(z,C,K={}){let N=`${encodeURIComponent(z)}=${encodeURIComponent(C)}`;if(K.maxAge)N+=`; Max-Age=${K.maxAge}`;if(K.expires)N+=`; Expires=${K.expires.toUTCString()}`;if(K.path)N+=`; Path=${K.path}`;if(K.domain)N+=`; Domain=${K.domain}`;if(K.secure)N+="; Secure";if(K.httpOnly)N+="; HttpOnly";if(K.sameSite)N+=`; SameSite=${K.sameSite}`;return $.append("Set-Cookie",N),this},get cookies(){if(!J){let z=this.req.headers.get("cookie");J=z?B(z):{}}return J}}}function B(w){return Object.fromEntries(w.split(";").map((F)=>{let[E,...$]=F.trim().split("=");return[E,decodeURIComponent($.join("="))]}))}function Q(w,F){let E={},$=w.split("/"),[R]=F.split("?"),L=R.split("/");if($.length!==L.length)return null;for(let J=0;J<$.length;J++)if($[J].startsWith(":"))E[$[J].slice(1)]=L[J];return E}async function x(w){let F=w.headers.get("Content-Type");if(!F)return{};if(w.headers.get("Content-Length")==="0"||!w.body)return{};try{if(F.startsWith("application/json"))return await w.json();if(F.startsWith("application/x-www-form-urlencoded")){let $=await w.text();return Object.fromEntries(new URLSearchParams($))}if(F.startsWith("multipart/form-data")){let $=await w.formData(),R={};for(let[L,J]of $.entries())R[L]=J;return R}return{error:"Unknown request body type"}}catch($){return{error:"Invalid request body format"}}}async function M(w,F,E,$){let R=Z(w,F,E),L=$.trie.search(E.pathname,w.method);if(w.routePattern=L?.path,$.hasFilterEnabled){let A=w.routePattern??E.pathname,z=await T($,A,R,F);if(z)return z}if($.hasMiddleware){let A=await W($.globalMiddlewares,R,F);if(A)return A;let z=$.middlewares.get(E.pathname)||[],C=await W(z,R,F);if(C)return C}if(!L?.handler||L.method!==w.method){if($.staticPath){let A=await S($,E.pathname,R);if(A)return A;let z=$.trie.search("*",w.method);if(z?.handler)return await z.handler(R)}if($.hooks.routeNotFound&&!L?.handler){let A=await $.hooks.routeNotFound(R);if(A)return A}if(!L||!L?.handler?.length)return f(404,`Route not found for ${E.pathname}`);if(L?.method!==w.method)return f(405,"Method not allowed")}if($.hooks.preHandler){let A=await $.hooks.preHandler(R);if(A)return A}let J=L.handler(R),G=J instanceof Promise?await J:J;if($.hooks.postHandler)await $.hooks.postHandler(R);if($.hooks.onSend){let A=await $.hooks.onSend(R,G);if(A)return A}return G??f(204,"No response from this handler")}async function W(w,F,E){for(let $ of w){let R=await $(F,E);if(R)return R}return null}async function T(w,F,E,$){if(!w.filters.has(F))if(w.filterFunction.length)for(let R of w.filterFunction){let L=await R(E,$);if(L)return L}else return E.json({error:!0,message:"Protected route, authentication required",status:401},401)}function f(w,F){return new Response(JSON.stringify({error:!0,message:F,status:w}),{status:w,headers:{"Content-Type":"application/json"}})}async function S(w,F,E){if(!w.staticPath)return null;let $=`${w.staticPath}${F}`;if(await Bun.file($).exists()){let L=X($);return E.file($,200,L)}return null}class _{tempRoutes;globalMiddlewares;middlewares;trie;hasOnReqHook;hasMiddleware;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hasOnError;hooks;corsConfig;FilterRoutes;filters;filterFunction;hasFilterEnabled;serverInstance;staticPath;staticFiles;constructor(){this.tempRoutes=new Map,this.globalMiddlewares=[],this.middlewares=new Map,this.trie=new U,this.corsConfig=null,this.hasMiddleware=!1,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hasOnError=!1,this.hooks={onRequest:null,preHandler:null,postHandler:null,onSend:null,onError:null,onClose:null,routeNotFound:null},this.FilterRoutes=[],this.filters=new Set,this.filterFunction=[],this.hasFilterEnabled=!1,this.serverInstance=null,this.staticPath=null,this.staticFiles={}}setupFilter(){return this.hasFilterEnabled=!0,{routeMatcher:(...w)=>{return this.FilterRoutes=w,this.setupFilter()},permitAll:()=>{for(let w of this?.FilterRoutes)this.filters.add(w);return this.FilterRoutes=null,this.setupFilter()},authenticate:(w)=>{if(w?.length)for(let F of w)this.filterFunction.push(F)}}}redirect(w,F,E){return this.any(w,($)=>{let R=$.params,L=F;if(R)for(let G in R)L=L.replace(`:${G}`,R[G]);let J=$.url.search;if(J)L+=J;return $.redirect(L,E)}),this}serveStatic(w){this.staticPath=w}static(w={}){return this.staticFiles={...this.staticFiles,...w},this}addHooks(w,F){if(typeof w!=="string")throw new Error("hookName must be a string");if(typeof F!=="function")throw new Error("callback must be a instance of function");switch(w){case"onRequest":this.hooks.onRequest=F;break;case"preHandler":this.hooks.preHandler=F;break;case"postHandler":this.hooks.postHandler=F;break;case"onSend":this.hooks.onSend=F;break;case"onError":this.hooks.onError=F;break;case"onClose":this.hooks.onClose=F;break;case"routeNotFound":this.hooks.routeNotFound=F;break;default:throw new Error(`Unknown hook type: ${w}`)}return this}compile(){if(this.globalMiddlewares.length>0)this.hasMiddleware=!0;for(let[w,F]of this.middlewares.entries())if(F.length>0){this.hasMiddleware=!0;break}this.tempRoutes=new Map}listen(w,...F){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");let E="0.0.0.0",$=void 0,R={};for(let J of F)if(typeof J==="string")E=J;else if(typeof J==="function")$=J;else if(typeof J==="object"&&J!==null)R=J;let L={port:w,hostname:E,fetch:async(J,G)=>{let A=new URL(J.url);try{if(this.hooks.onRequest)this.hooks.onRequest(J,A,G);return await M(J,G,A,this)}catch(z){return this.hooks.onError?this.hooks.onError(z,J,A,G):new Response(JSON.stringify({message:"Internal Server Error",error:z.message,status:500}),{status:500})}},static:this.staticFiles,development:!0};if(R.sslCert&&R.sslKey)L.certFile=R.sslCert,L.keyFile=R.sslKey;if(this.compile(),this.serverInstance=Bun?.serve(L),$)return $();if(R.sslCert&&R.sslKey)console.log(`HTTPS server is running on https://localhost:${w}`);else console.log(`HTTP server is running on http://localhost:${w}`);return this.serverInstance}close(w){if(this.serverInstance)this.serverInstance.stop(!0),this.serverInstance=null,w?w():console.log("Server has been stopped");else console.warn("Server is not running.")}route(w,F){if(!w||typeof w!=="string")throw new Error("Path must be a string");let E=Object.fromEntries(F.tempRoutes);return Object.entries(E).forEach(([R,L])=>{let J=`${w}${R}`;if(!this.middlewares.has(J))this.middlewares.set(J,[]);L.handlers.slice(0,-1).forEach((C)=>{if(!this.middlewares.get(J)?.includes(C))this.middlewares.get(J)?.push(C)});let A=L.handlers[L.handlers.length-1],z=L.method;try{this.trie.insert(J,{handler:A,method:z})}catch(C){console.error(`Error inserting ${J}:`,C)}}),F=null,this}register(w,F){return this.route(w,F)}addRoute(w,F,E){if(typeof F!=="string")throw new Error(`Error in ${E[E.length-1]}: Path must be a string. Received: ${typeof F}`);if(typeof w!=="string")throw new Error(`Error in addRoute: Method must be a string. Received: ${typeof w}`);this.tempRoutes.set(F,{method:w,handlers:E});let $=E.slice(0,-1),R=E[E.length-1];if(!this.middlewares.has(F))this.middlewares.set(F,[]);$.forEach((L)=>{if(F==="/")this.globalMiddlewares=[...new Set([...this.globalMiddlewares,...$])];else if(!this.middlewares.get(F)?.includes(L))this.middlewares.get(F)?.push(L)});try{if(w==="ANY"){let L=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD","PROPFIND"];for(let J of L)this.trie.insert(F,{handler:R,method:J})}this.trie.insert(F,{handler:R,method:w})}catch(L){console.error(`Error inserting ${F}:`,L)}}use(w,F){if(Array.isArray(w))w.forEach(($)=>{if(typeof $==="function")this.globalMiddlewares.push($)});if(typeof w==="function"){if(this.globalMiddlewares.push(w),Array.isArray(F))F.forEach(($)=>{this.globalMiddlewares.push($)});return}return(Array.isArray(w)?w.filter(($)=>typeof $==="string"):[w].filter(($)=>typeof $==="string")).forEach(($)=>{if(!this.middlewares.has($))this.middlewares.set($,[]);if(F)(Array.isArray(F)?F:[F]).forEach((L)=>{this.middlewares.get($)?.push(L)})}),this}get(w,...F){return this.addRoute("GET",w,F),this}post(w,...F){return this.addRoute("POST",w,F),this}put(w,...F){return this.addRoute("PUT",w,F),this}patch(w,...F){return this.addRoute("PATCH",w,F),this}delete(w,...F){return this.addRoute("DELETE",w,F),this}any(w,...F){return this.addRoute("ANY",w,F),this}head(w,...F){return this.addRoute("HEAD",w,F),this}options(w,...F){return this.addRoute("OPTIONS",w,F),this}propfind(w,...F){return this.addRoute("PROPFIND",w,F),this}}export{_ as default};
|
|
1
|
+
class Q{children;isEndOfWord;handler;isDynamic;pattern;path;method;constructor(){this.children={},this.isEndOfWord=!1,this.handler=[],this.isDynamic=!1,this.pattern="",this.path="",this.method=[]}}class _{root;constructor(){this.root=new Q}insert(z,A){let J=this.root,G=z.split("/").filter(Boolean);if(z==="/"){J.isEndOfWord=!0,J.handler.push(A.handler),J.path=z,J.method.push(A.method);return}for(let K of G){let L=!1,X=K;if(K.startsWith(":"))L=!0,X=":";if(!J.children[X])J.children[X]=new Q;J=J.children[X],J.isDynamic=L,J.pattern=K,J.method.push(A.method),J.handler.push(A.handler),J.path=z}J.isEndOfWord=!0,J.method.push(A.method),J.handler.push(A.handler),J.path=z}search(z,A){let J=this.root,G=z.split("/").filter(Boolean),K=G.length;for(let $ of G){let Z=$;if(!J.children[Z])if(J.children[":"])J=J.children[":"];else return null;else J=J.children[Z]}let L=J.path.split("/").filter(Boolean);if(K!==L.length)return null;let X=J.method.indexOf(A);if(X!==-1)return{path:J.path,handler:J.handler[X],isDynamic:J.isDynamic,pattern:J.pattern,method:J.method[X]};return{path:J.path,handler:J.handler,isDynamic:J.isDynamic,pattern:J.pattern,method:J.method[X]}}}function I(z){let{time:A=60000,max:J=100,message:G="Rate limit exceeded. Please try again later."}=z,K=new Map;return(L)=>{let X=new Date,$=L.ip;if(!K.has($))K.set($,{count:0,startTime:X});let Z=K.get($);if(Z)if(X-Z.startTime>A)Z.count=1,Z.startTime=X;else Z.count++;if(Z&&Z.count>J)return L.json({error:G},429)}}function E(z){switch(z.split(".").pop()?.toLowerCase()){case"js":return"application/javascript";case"css":return"text/css";case"html":return"text/html";case"json":return"application/json";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";case"gif":return"image/gif";case"woff":return"font/woff";case"woff2":return"font/woff2";default:return"application/octet-stream"}}var D=(z,A,J,G)=>{if(J>G)return!1;let K=J+(G-J)/2;if(z[K]==A)return!0;if(z[K]>A)return D(z,A,J,K-1);return D(z,A,K+1,G)};function j(z,A,J){let G=new Headers({"Cache-Control":"no-cache"}),K=null,L=null,X=null,$=null,Z={};return{req:z,server:A,url:J,setHeader(Y,V){return G.set(Y,V),this},removeHeader(Y){return G.delete(Y),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!K)try{K=Object.fromEntries(this.url.searchParams)}catch(Y){throw new Error("Failed to parse query parameters")}return K},get params(){if(!L&&this.req.routePattern)try{L=T(this.req.routePattern,this.url.pathname)}catch(Y){throw new Error("Failed to extract route parameters")}return L??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!$)$=(async()=>{let Y=await S(this.req);if(Y.error)throw new Error(Y.error);return Object.keys(Y).length===0?null:Y})();return $},set(Y,V){return Z[Y]=V,this},get(Y){return Z[Y]},text(Y,V=200){if(!G.has("Content-Type"))G.set("Content-Type","text/plain; charset=utf-8");return new Response(Y,{status:V,headers:G})},send(Y,V=200){let U=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),W=Y instanceof Uint8Array?"Uint8Array":Y instanceof ArrayBuffer?"ArrayBuffer":typeof Y;if(!G.has("Content-Type"))G.set("Content-Type",U.get(W)??"text/plain; charset=utf-8");let M=W==="object"&&Y!==null?JSON.stringify(Y):Y;return new Response(M,{status:V,headers:G})},json(Y,V=200){if(!G.has("Content-Type"))G.set("Content-Type","application/json; charset=utf-8");return new Response(JSON.stringify(Y),{status:V,headers:G})},file(Y,V=200,U){let W=Bun.file(Y);if(!G.has("Content-Type"))G.set("Content-Type",U??E(Y));return new Response(W,{status:V,headers:G})},redirect(Y,V=302){return G.set("Location",Y),new Response(null,{status:V,headers:G})},setCookie(Y,V,U={}){let W=`${encodeURIComponent(Y)}=${encodeURIComponent(V)}`;if(U.maxAge)W+=`; Max-Age=${U.maxAge}`;if(U.expires)W+=`; Expires=${U.expires.toUTCString()}`;if(U.path)W+=`; Path=${U.path}`;if(U.domain)W+=`; Domain=${U.domain}`;if(U.secure)W+="; Secure";if(U.httpOnly)W+="; HttpOnly";if(U.sameSite)W+=`; SameSite=${U.sameSite}`;return G.append("Set-Cookie",W),this},get cookies(){if(!X){let Y=this.req.headers.get("cookie");X=Y?O(Y):{}}return X}}}function O(z){return Object.fromEntries(z.split(";").map((A)=>{let[J,...G]=A.trim().split("=");return[J,decodeURIComponent(G.join("="))]}))}function T(z,A){let J={},G=z.split("/"),[K]=A.split("?"),L=K.split("/");if(G.length!==L.length)return null;for(let X=0;X<G.length;X++)if(G[X].startsWith(":"))J[G[X].slice(1)]=L[X];return J}async function S(z){let A=z.headers.get("Content-Type");if(!A)return{};if(z.headers.get("Content-Length")==="0"||!z.body)return{};try{if(A.startsWith("application/json"))return await z.json();if(A.startsWith("application/x-www-form-urlencoded")){let G=await z.text();return Object.fromEntries(new URLSearchParams(G))}if(A.startsWith("multipart/form-data")){let G=await z.formData(),K={};for(let[L,X]of G.entries())K[L]=X;return K}return{error:"Unknown request body type"}}catch(G){return{error:"Invalid request body format"}}}async function F(z,A,J,G){let K=j(z,A,J),L=G.trie.search(J.pathname,z.method);if(z.routePattern=L?.path,G.hasFilterEnabled){let Z=z.routePattern??J.pathname,Y=await w(G,Z,K,A);if(Y)return Y}if(G.hasMiddleware){let Z=await N(G.globalMiddlewares,K,A);if(Z)return Z;let Y=G.middlewares.get(J.pathname)||[],V=await N(Y,K,A);if(V)return V}if(!L?.handler||L.method!==z.method){if(G.staticPath){let Z=await b(G,J.pathname,K);if(Z)return Z;let Y=G.trie.search("*",z.method);if(Y?.handler)return await Y.handler(K)}if(G.hooks.routeNotFound&&!L?.handler){let Z=await G.hooks.routeNotFound(K);if(Z)return Z}if(!L||!L?.handler?.length)return B(404,`Route not found for ${J.pathname}`);if(L?.method!==z.method)return B(405,"Method not allowed")}if(G.hooks.preHandler){let Z=await G.hooks.preHandler(K);if(Z)return Z}let X=L.handler(K),$=X instanceof Promise?await X:X;if(G.hooks.postHandler)await G.hooks.postHandler(K);if(G.hooks.onSend){let Z=await G.hooks.onSend(K,$);if(Z)return Z}return $??B(204,"No response from this handler")}async function N(z,A,J){for(let G of z){let K=await G(A,J);if(K)return K}return null}async function w(z,A,J,G){if(!z.filters.has(A))if(z.filterFunction.length)for(let K of z.filterFunction){let L=await K(J,G);if(L)return L}else return J.json({error:!0,message:"Protected route, authentication required",status:401},401)}function B(z,A){return new Response(JSON.stringify({error:!0,message:A,status:z}),{status:z,headers:{"Content-Type":"application/json"}})}async function b(z,A,J){if(!z.staticPath)return null;let G=`${z.staticPath}${A}`;if(await Bun.file(G).exists()){let L=E(G);return J.file(G,200,L)}return null}class C{tempRoutes;globalMiddlewares;middlewares;trie;hasOnReqHook;hasMiddleware;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hasOnError;hooks;corsConfig;FilterRoutes;filters;filterFunction;hasFilterEnabled;serverInstance;staticPath;staticFiles;constructor(){this.tempRoutes=new Map,this.globalMiddlewares=[],this.middlewares=new Map,this.trie=new _,this.corsConfig=null,this.hasMiddleware=!1,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hasOnError=!1,this.hooks={onRequest:null,preHandler:null,postHandler:null,onSend:null,onError:null,onClose:null,routeNotFound:null},this.FilterRoutes=[],this.filters=new Set,this.filterFunction=[],this.hasFilterEnabled=!1,this.serverInstance=null,this.staticPath=null,this.staticFiles={}}setupFilter(){return this.hasFilterEnabled=!0,{routeMatcher:(...z)=>{return this.FilterRoutes=z,this.setupFilter()},permitAll:()=>{for(let z of this?.FilterRoutes)this.filters.add(z);return this.FilterRoutes=null,this.setupFilter()},authenticate:(z)=>{if(z?.length)for(let A of z)this.filterFunction.push(A)}}}redirect(z,A,J){return this.any(z,(G)=>{let K=G.params,L=A;if(K)for(let $ in K)L=L.replace(`:${$}`,K[$]);let X=G.url.search;if(X)L+=X;return G.redirect(L,J)}),this}serveStatic(z){this.staticPath=z}static(z={}){return this.staticFiles={...this.staticFiles,...z},this}addHooks(z,A){if(typeof z!=="string")throw new Error("hookName must be a string");if(typeof A!=="function")throw new Error("callback must be a instance of function");switch(z){case"onRequest":this.hooks.onRequest=A;break;case"preHandler":this.hooks.preHandler=A;break;case"postHandler":this.hooks.postHandler=A;break;case"onSend":this.hooks.onSend=A;break;case"onError":this.hooks.onError=A;break;case"onClose":this.hooks.onClose=A;break;case"routeNotFound":this.hooks.routeNotFound=A;break;default:throw new Error(`Unknown hook type: ${z}`)}return this}compile(){if(this.globalMiddlewares.length>0)this.hasMiddleware=!0;for(let[z,A]of this.middlewares.entries())if(A.length>0){this.hasMiddleware=!0;break}this.tempRoutes=null}listen(z,...A){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");let J="0.0.0.0",G=void 0,K={};for(let X of A)if(typeof X==="string")J=X;else if(typeof X==="function")G=X;else if(typeof X==="object"&&X!==null)K=X;let L={port:z,hostname:J,fetch:async(X,$)=>{let Z=new URL(X.url);try{if(this.hooks.onRequest)this.hooks.onRequest(X,Z,$);return await F(X,$,Z,this)}catch(Y){return this.hooks.onError?this.hooks.onError(Y,X,Z,$):new Response(JSON.stringify({message:"Internal Server Error",error:Y.message,status:500}),{status:500})}},static:this.staticFiles,development:!0};if(K.sslCert&&K.sslKey)L.certFile=K.sslCert,L.keyFile=K.sslKey;if(this.compile(),this.serverInstance=Bun?.serve(L),G)return G();if(K.sslCert&&K.sslKey)console.log(`HTTPS server is running on https://localhost:${z}`);else console.log(`HTTP server is running on http://localhost:${z}`);return this.serverInstance}close(z){if(this.serverInstance)this.serverInstance.stop(!0),this.serverInstance=null,z?z():console.log("Server has been stopped");else console.warn("Server is not running.")}route(z,A){if(!z||typeof z!=="string")throw new Error("Path must be a string");let J=Object.fromEntries(A.tempRoutes);return Object.entries(J).forEach(([K,L])=>{let X=K.replace(/::\w+$/,""),$=`${z}${X}`;if(!this.middlewares.has($))this.middlewares.set($,[]);L.handlers.slice(0,-1).forEach((U)=>{if(!this.middlewares.get($)?.includes(U))this.middlewares.get($)?.push(U)});let Y=L.handlers[L.handlers.length-1],V=L.method;try{this.trie.insert($,{handler:Y,method:V})}catch(U){console.error(`Error inserting ${$}:`,U)}}),A=null,this}register(z,A){return this.route(z,A)}addRoute(z,A,J){if(typeof A!=="string")throw new Error(`Error in ${J[J.length-1]}: Path must be a string. Received: ${typeof A}`);if(typeof z!=="string")throw new Error(`Error in addRoute: Method must be a string. Received: ${typeof z}`);this.tempRoutes?.set(A+"::"+z,{method:z,handlers:J});let G=J.slice(0,-1),K=J[J.length-1];if(!this.middlewares.has(A))this.middlewares.set(A,[]);G.forEach((L)=>{if(A==="/")this.globalMiddlewares=[...new Set([...this.globalMiddlewares,...G])];else if(!this.middlewares.get(A)?.includes(L))this.middlewares.get(A)?.push(L)});try{if(z==="ANY"){let L=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD","PROPFIND"];for(let X of L)this.trie.insert(A,{handler:K,method:X})}this.trie.insert(A,{handler:K,method:z})}catch(L){console.error(`Error inserting ${A}:`,L)}}use(z,A){if(Array.isArray(z))z.forEach((G)=>{if(typeof G==="function")this.globalMiddlewares.push(G)});if(typeof z==="function"){if(this.globalMiddlewares.push(z),Array.isArray(A))A.forEach((G)=>{this.globalMiddlewares.push(G)});return}return(Array.isArray(z)?z.filter((G)=>typeof G==="string"):[z].filter((G)=>typeof G==="string")).forEach((G)=>{if(!this.middlewares.has(G))this.middlewares.set(G,[]);if(A)(Array.isArray(A)?A:[A]).forEach((L)=>{this.middlewares.get(G)?.push(L)})}),this}get(z,...A){return this.addRoute("GET",z,A),this}post(z,...A){return this.addRoute("POST",z,A),this}put(z,...A){return this.addRoute("PUT",z,A),this}patch(z,...A){return this.addRoute("PATCH",z,A),this}delete(z,...A){return this.addRoute("DELETE",z,A),this}any(z,...A){return this.addRoute("ANY",z,A),this}head(z,...A){return this.addRoute("HEAD",z,A),this}options(z,...A){return this.addRoute("OPTIONS",z,A),this}propfind(z,...A){return this.addRoute("PROPFIND",z,A),this}}export{C as default};
|