diesel-core 1.1.7 → 1.1.9
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/ctx.js +1 -1
- package/dist/handleRequest.d.ts +2 -2
- package/dist/handleRequest.js +1 -1
- package/dist/main.d.ts +4 -2
- package/dist/main.js +3 -3
- package/dist/middlewares/jwt/index.d.ts +18 -0
- package/dist/middlewares/jwt/index.js +1 -0
- package/dist/middlewares/logger/logger.js +3 -3
- package/dist/middlewares/powered-by/index.d.ts +29 -0
- package/dist/middlewares/powered-by/index.js +1 -0
- package/dist/middlewares/ratelimit/rate-limit.d.ts +1 -1
- package/dist/types.d.ts +2 -0
- package/dist/utils/jwt.d.ts +4 -0
- package/dist/utils/jwt.js +1 -0
- package/dist/utils/mimeType.d.ts +1 -0
- package/dist/utils/mimeType.js +1 -0
- package/dist/utils.js +1 -1
- package/package.json +11 -1
package/dist/ctx.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var j=Object.create;var{getPrototypeOf:I,defineProperty:X,getOwnPropertyNames:M}=Object;var N=Object.prototype.hasOwnProperty;var R=(w,A,E)=>{E=w!=null?j(I(w)):{};let z=A||!w||!w.__esModule?X(E,"default",{value:w,enumerable:!0}):E;for(let F of M(w))if(!N.call(z,F))X(z,F,{get:()=>w[F],enumerable:!0});return z};var U=((w)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(w,{get:(A,E)=>(typeof require!=="undefined"?require:A)[E]}):w)(function(w){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+w+'" is not supported')});function Y(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"}}function V(w,A,E){let z=null,F=null,J=null,G=null,O={};return{req:w,server:A,url:E,status:200,headers:new Headers({"Cache-Control":"no-cache"}),setHeader(f,x){return this.headers.set(f,x),this},removeHeader(f){return this.headers.delete(f),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!z)try{z=Object.fromEntries(this.url.searchParams)}catch(f){throw new Error("Failed to parse query parameters")}return z},get params(){if(!F&&this.req.routePattern)try{F=_(this.req.routePattern,this.url.pathname)}catch(f){throw new Error("Failed to extract route parameters")}return F??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!G)G=(async()=>{let f=await B(this.req);if(f.error)throw new Error(f.error);return Object.keys(f).length===0?null:f})();return G},set(f,x){return O[f]=x,this},get(f){return O[f]},text(f,x){if(x)this.status=x;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","text/plain; charset=utf-8");return new Response(f,{status:this.status,headers:this.headers})},send(f,x){if(x)this.status=x;let g=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),L=f instanceof Uint8Array?"Uint8Array":f instanceof ArrayBuffer?"ArrayBuffer":typeof f;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",g.get(L)??"text/plain; charset=utf-8");let K=L==="object"&&f!==null?JSON.stringify(f):f;return new Response(K,{status:this.status,headers:this.headers})},json(f,x){if(x)this.status=x;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return Response.json(f,{status:this.status,headers:this.headers})},file(f,x,g){if(g)this.status=g;let L=Bun.file(f);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",x??Y(f));return new Response(L,{status:this.status,headers:this.headers})},async ejs(f,x={},g){if(g)this.status=g;let L;try{L=await import("ejs"),L=L.default||L}catch(K){return console.error("EJS not installed! Please run `bun add ejs`"),new Response("EJS not installed! Please run `bun add ejs`",{status:500})}try{let K=await Bun.file(f).text(),Z=L.render(K,x),$=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(Z,{status:this.status,headers:$})}catch(K){return console.error("EJS Rendering Error:",K),new Response("Error rendering template",{status:500})}},redirect(f,x){if(x)this.status=x;else this.status=302;return this.headers.set("Location",f),new Response(null,{status:this.status,headers:this.headers})},stream(f){let x=new Headers(this.headers),g=new ReadableStream({async start(L){await f(L),L.close()}});return new Response(g,{headers:x})},yieldStream(f){return new Response({async*[Symbol.asyncIterator](){yield*f()}},{headers:this.headers})},setCookie(f,x,g={}){let L=`${encodeURIComponent(f)}=${encodeURIComponent(x)}`;if(g.maxAge)L+=`; Max-Age=${g.maxAge}`;if(g.expires)L+=`; Expires=${g.expires.toUTCString()}`;if(g.path)L+=`; Path=${g.path}`;if(g.domain)L+=`; Domain=${g.domain}`;if(g.secure)L+="; Secure";if(g.httpOnly)L+="; HttpOnly";if(g.sameSite)L+=`; SameSite=${g.sameSite}`;return this.headers.append("Set-Cookie",L),this},get cookies(){if(!J){let f=this.req.headers.get("cookie");J=f?W(f):{}}return J}}}function W(w){return Object.fromEntries(w.split(";").map((A)=>{let[E,...z]=A.trim().split("=");return[E,decodeURIComponent(z.join("="))]}))}function _(w,A){let E={},z=w.split("/"),[F]=A.split("?"),J=F.split("/");if(z.length!==J.length)return null;for(let G=0;G<z.length;G++)if(z[G].startsWith(":"))E[z[G].slice(1)]=J[G];return E}async function B(w){let A=w.headers.get("Content-Type");if(!A)return{};if(w.headers.get("Content-Length")==="0"||!w.body)return{};try{if(A.startsWith("application/json"))return await w.json();if(A.startsWith("application/x-www-form-urlencoded")){let z=await w.text();return Object.fromEntries(new URLSearchParams(z))}if(A.startsWith("multipart/form-data")){let z=await w.formData(),F={};for(let[J,G]of z.entries())F[J]=G;return F}return{error:"Unknown request body type"}}catch(z){return{error:"Invalid request body format"}}}export{V as default};
|
package/dist/handleRequest.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { Server } from "bun";
|
|
1
|
+
import { BunRequest, Server } from "bun";
|
|
2
2
|
import type { ContextType, DieselT } from "./types";
|
|
3
|
-
export default function handleRequest(req:
|
|
3
|
+
export default function handleRequest(req: BunRequest, server: Server, url: URL, diesel: DieselT): Promise<any>;
|
|
4
4
|
export declare function handleFilterRequest(diesel: DieselT, path: string, ctx: ContextType, server: Server): Promise<Response | undefined>;
|
|
5
5
|
export declare function generateErrorResponse(status: number, message: string): Response;
|
|
6
6
|
export declare function handleStaticFiles(diesel: DieselT, pathname: string, ctx: ContextType): Promise<Response | null>;
|
package/dist/handleRequest.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var T=Object.create;var{getPrototypeOf:C,defineProperty:m,getOwnPropertyNames:H}=Object;var N=Object.prototype.hasOwnProperty;var $=(f,o,h)=>{h=f!=null?T(C(f)):{};let r=o||!f||!f.__esModule?m(h,"default",{value:f,enumerable:!0}):h;for(let e of H(f))if(!N.call(r,e))m(r,e,{get:()=>f[e],enumerable:!0});return r};var p=((f)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(f,{get:(o,h)=>(typeof require!=="undefined"?require:o)[h]}):f)(function(f){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+f+'" is not supported')});function g(f){switch(f.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"}}function F(f,o,h){let r=null,e=null,c=null,w=null,u={};return{req:f,server:o,url:h,status:200,headers:new Headers({"Cache-Control":"no-cache"}),setHeader(n,t){return this.headers.set(n,t),this},removeHeader(n){return this.headers.delete(n),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!r)try{r=Object.fromEntries(this.url.searchParams)}catch(n){throw new Error("Failed to parse query parameters")}return r},get params(){if(!e&&this.req.routePattern)try{e=L(this.req.routePattern,this.url.pathname)}catch(n){throw new Error("Failed to extract route parameters")}return e??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!w)w=(async()=>{let n=await a(this.req);if(n.error)throw new Error(n.error);return Object.keys(n).length===0?null:n})();return w},set(n,t){return u[n]=t,this},get(n){return u[n]},text(n,t){if(t)this.status=t;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","text/plain; charset=utf-8");return new Response(n,{status:this.status,headers:this.headers})},send(n,t){if(t)this.status=t;let i=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),l=n instanceof Uint8Array?"Uint8Array":n instanceof ArrayBuffer?"ArrayBuffer":typeof n;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",i.get(l)??"text/plain; charset=utf-8");let R=l==="object"&&n!==null?JSON.stringify(n):n;return new Response(R,{status:this.status,headers:this.headers})},json(n,t){if(t)this.status=t;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return Response.json(n,{status:this.status,headers:this.headers})},file(n,t,i){if(i)this.status=i;let l=Bun.file(n);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",t??g(n));return new Response(l,{status:this.status,headers:this.headers})},async ejs(n,t={},i){if(i)this.status=i;let l;try{l=await import("ejs"),l=l.default||l}catch(R){return console.error("EJS not installed! Please run `bun add ejs`"),new Response("EJS not installed! Please run `bun add ejs`",{status:500})}try{let R=await Bun.file(n).text(),E=l.render(R,t),M=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(E,{status:this.status,headers:M})}catch(R){return console.error("EJS Rendering Error:",R),new Response("Error rendering template",{status:500})}},redirect(n,t){if(t)this.status=t;else this.status=302;return this.headers.set("Location",n),new Response(null,{status:this.status,headers:this.headers})},stream(n){let t=new Headers(this.headers),i=new ReadableStream({async start(l){await n(l),l.close()}});return new Response(i,{headers:t})},yieldStream(n){return new Response({async*[Symbol.asyncIterator](){yield*n()}},{headers:this.headers})},setCookie(n,t,i={}){let l=`${encodeURIComponent(n)}=${encodeURIComponent(t)}`;if(i.maxAge)l+=`; Max-Age=${i.maxAge}`;if(i.expires)l+=`; Expires=${i.expires.toUTCString()}`;if(i.path)l+=`; Path=${i.path}`;if(i.domain)l+=`; Domain=${i.domain}`;if(i.secure)l+="; Secure";if(i.httpOnly)l+="; HttpOnly";if(i.sameSite)l+=`; SameSite=${i.sameSite}`;return this.headers.append("Set-Cookie",l),this},get cookies(){if(!c){let n=this.req.headers.get("cookie");c=n?s(n):{}}return c}}}function s(f){return Object.fromEntries(f.split(";").map((o)=>{let[h,...r]=o.trim().split("=");return[h,decodeURIComponent(r.join("="))]}))}function L(f,o){let h={},r=f.split("/"),[e]=o.split("?"),c=e.split("/");if(r.length!==c.length)return null;for(let w=0;w<r.length;w++)if(r[w].startsWith(":"))h[r[w].slice(1)]=c[w];return h}async function a(f){let o=f.headers.get("Content-Type");if(!o)return{};if(f.headers.get("Content-Length")==="0"||!f.body)return{};try{if(o.startsWith("application/json"))return await f.json();if(o.startsWith("application/x-www-form-urlencoded")){let r=await f.text();return Object.fromEntries(new URLSearchParams(r))}if(o.startsWith("multipart/form-data")){let r=await f.formData(),e={};for(let[c,w]of r.entries())e[c]=w;return e}return{error:"Unknown request body type"}}catch(r){return{error:"Invalid request body format"}}}async function j(f,o,h,r){let e=F(f,o,h),c=r.trie.search(h.pathname,f.method);f.routePattern=c?.path;try{if(h.pathname.startsWith("/favicon"))return;if(r.hasFilterEnabled){let n=f.routePattern??h.pathname,t=await J(r,n,e,o);if(t)return t}if(r.hasMiddleware){if(r.globalMiddlewares.length){let t=await A(r.globalMiddlewares,e,o);if(t)return t}let n=r.middlewares.get(h.pathname)||[];if(n?.length){let t=await A(n,e,o);if(t)return t}}if(!c?.handler||c.method!==f.method){if(r.staticPath){let n=await O(r,h.pathname,e);if(n)return n;let t=r.trie.search("*",f.method);if(t?.handler)return await t.handler(e)}if(r.hooks.routeNotFound&&Array.isArray(r.hooks.routeNotFound)&&!c?.handler){let n=r.hooks.routeNotFound;for(let t=0;t<n.length;t++){let i=await n[t](e);if(i)return i}}if(!c||!c?.handler?.length)return x(404,`Route not found for ${h.pathname}`);if(c?.method!==f.method)return x(405,"Method not allowed")}if(r.hooks.preHandler?.length&&Array.isArray(r.hooks.preHandler)){let n=r.hooks.preHandler;for(let t=0;t<n.length;t++){let i=await n[t](e);if(i)return i}}let w=c.handler(e);return(w instanceof Promise?await w:w)??x(204,"")}catch(w){if(r.hooks.onError&&Array.isArray(r.hooks.onError)){let u=r.hooks.onError;for(let n=0;n<u.length;n++){let t=r.hooks.onError[n](w,f,h,o);if(t)return t}}return x(500,"Internal Server Error")}finally{if(r.hooks.onSend&&Array.isArray(r.hooks.onSend)){let w=r.hooks.onSend;for(let u=0;u<w.length;u++){let n=await w[u](e);if(n)return n}}}}async function A(f,o,h){for(let r of f){let e=await r(o,h);if(e)return e}return null}async function J(f,o,h,r){if(!f.filters.has(o))if(f.filterFunction.length)for(let e of f.filterFunction){let c=await e(h,r);if(c)return c}else return h.json({error:!0,message:"Protected route, authentication required",status:401},401)}function x(f,o){return new Response(JSON.stringify({error:!0,message:o,status:f}),{status:f,headers:{"Content-Type":"application/json"}})}async function O(f,o,h){if(!f.staticPath)return null;let r=`${f.staticPath}${o}`;if(await Bun.file(r).exists()){let c=g(r);return h.file(r,c,200)}return null}export{O as handleStaticFiles,J as handleFilterRequest,x as generateErrorResponse,j as default};
|
package/dist/main.d.ts
CHANGED
|
@@ -21,13 +21,15 @@ export default class Diesel {
|
|
|
21
21
|
private serverInstance;
|
|
22
22
|
staticPath: any;
|
|
23
23
|
staticFiles: any;
|
|
24
|
-
|
|
24
|
+
user_jwt_secret: string;
|
|
25
25
|
private baseApiUrl;
|
|
26
26
|
private enableFileRouter;
|
|
27
|
-
|
|
27
|
+
idleTimeOut: number;
|
|
28
|
+
constructor({ jwtSecret, baseApiUrl, enableFileRouting, idleTimeOut, }?: {
|
|
28
29
|
jwtSecret?: string;
|
|
29
30
|
baseApiUrl?: string;
|
|
30
31
|
enableFileRouting?: boolean;
|
|
32
|
+
idleTimeOut?: number;
|
|
31
33
|
});
|
|
32
34
|
setupFilter(): FilterMethods;
|
|
33
35
|
redirect(incomingPath: string, redirectPath: string, statusCode?: 302): this;
|
package/dist/main.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var j=Object.create;var{getPrototypeOf:q,defineProperty:Z,getOwnPropertyNames:k}=Object;var P=Object.prototype.hasOwnProperty;var e=(n,r,f)=>{f=n!=null?j(q(n)):{};let g=r||!n||!n.__esModule?Z(f,"default",{value:n,enumerable:!0}):f;for(let u of k(n))if(!P.call(g,u))Z(g,u,{get:()=>n[u],enumerable:!0});return g};var h=((n)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(n,{get:(r,f)=>(typeof require!=="undefined"?require:r)[f]}):n)(function(n){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});class D{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 t{root;constructor(){this.root=new D}insert(n,r){let f=this.root,g=n.split("/").filter(Boolean);if(n==="/"){f.isEndOfWord=!0,f.handler.push(r.handler),f.path=n,f.method.push(r.method);return}for(let u of g){let C=!1,o=u;if(u.startsWith(":"))C=!0,o=":";if(!f.children[o])f.children[o]=new D;f=f.children[o],f.isDynamic=C,f.pattern=u}f.isEndOfWord=!0,f.path=n,f.method.push(r.method),f.handler.push(r.handler)}search(n,r){let f=this.root,g=n.split("/").filter(Boolean),u=g.length;for(let m of g){let i=m;if(!f.children[i])if(f.children[":"])f=f.children[":"];else return null;else f=f.children[i]}let C=f.path.split("/").filter(Boolean);if(u!==C.length)return null;let o=f.method.indexOf(r);if(o!==-1)return{path:f.path,handler:f.handler[o],isDynamic:f.isDynamic,pattern:f.pattern,method:f.method[o]};return{path:f.path,handler:f.handler,isDynamic:f.isDynamic,pattern:f.pattern,method:f.method[o]}}}function O(n){switch(n.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"}}function U(n,r){if(!n)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(f)=>{try{let g=f.cookies?.accessToken||f.req?.headers?.get("Authorization");if(!g)return f.json({message:"Unauthorized: No token provided"},401);if(g.startsWith("Bearer "))g=g.slice(7);let u=n?.verify(g,r);if(!u)return f.json({message:"Unauthorized: Invalid token"},401);f.set("user",u);return}catch(g){return f.json({message:"Unauthorized: Invalid token",error:g?.message},401)}}}function V(n,r,f){if(!n)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!r)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(g)=>{try{let u=g.cookies?.accessToken||g.req?.headers?.get("Authorization");if(!u)return g.json({message:"Unauthorized: No token provided"},401);if(u.startsWith("Bearer "))u=u.slice(7);let C=n?.verify(u,f);if(!C)return g.json({message:"Unauthorized: Invalid token"},401);let o=await r.findById(C._id).select("-password -refreshToken");if(!o)return g.json({message:"Unauthorized: User not found"},401);g.set("user",o);return}catch(u){return g.json({message:"Unauthorized: Authentication failed",error:u?.message},401)}}}function G(n,r,f){let g=null,u=null,C=null,o=null,m={};return{req:n,server:r,url:f,status:200,headers:new Headers({"Cache-Control":"no-cache"}),setHeader(i,v){return this.headers.set(i,v),this},removeHeader(i){return this.headers.delete(i),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!g)try{g=Object.fromEntries(this.url.searchParams)}catch(i){throw new Error("Failed to parse query parameters")}return g},get params(){if(!u&&this.req.routePattern)try{u=d(this.req.routePattern,this.url.pathname)}catch(i){throw new Error("Failed to extract route parameters")}return u??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!o)o=(async()=>{let i=await a(this.req);if(i.error)throw new Error(i.error);return Object.keys(i).length===0?null:i})();return o},set(i,v){return m[i]=v,this},get(i){return m[i]},text(i,v){if(v)this.status=v;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","text/plain; charset=utf-8");return new Response(i,{status:this.status,headers:this.headers})},send(i,v){if(v)this.status=v;let b=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),A=i instanceof Uint8Array?"Uint8Array":i instanceof ArrayBuffer?"ArrayBuffer":typeof i;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",b.get(A)??"text/plain; charset=utf-8");let $=A==="object"&&i!==null?JSON.stringify(i):i;return new Response($,{status:this.status,headers:this.headers})},json(i,v){if(v)this.status=v;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return new Response(JSON.stringify(i),{status:this.status,headers:this.headers})},file(i,v,b){if(b)this.status=b;let A=Bun.file(i);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",v??O(i));return new Response(A,{status:this.status,headers:this.headers})},async ejs(i,v={},b){if(b)this.status=b;let A;try{A=await import("ejs"),A=A.default||A}catch($){return console.error("EJS not installed! Please run `bun add ejs`"),new Response("EJS not installed! Please run `bun add ejs`",{status:500})}try{let $=await Bun.file(i).text(),c=A.render($,v),y=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(c,{status:this.status,headers:y})}catch($){return console.error("EJS Rendering Error:",$),new Response("Error rendering template",{status:500})}},redirect(i,v){if(v)this.status=v;else this.status=302;return this.headers.set("Location",i),new Response(null,{status:this.status,headers:this.headers})},setCookie(i,v,b={}){let A=`${encodeURIComponent(i)}=${encodeURIComponent(v)}`;if(b.maxAge)A+=`; Max-Age=${b.maxAge}`;if(b.expires)A+=`; Expires=${b.expires.toUTCString()}`;if(b.path)A+=`; Path=${b.path}`;if(b.domain)A+=`; Domain=${b.domain}`;if(b.secure)A+="; Secure";if(b.httpOnly)A+="; HttpOnly";if(b.sameSite)A+=`; SameSite=${b.sameSite}`;return this.headers.append("Set-Cookie",A),this},get cookies(){if(!C){let i=this.req.headers.get("cookie");C=i?p(i):{}}return C}}}function p(n){return Object.fromEntries(n.split(";").map((r)=>{let[f,...g]=r.trim().split("=");return[f,decodeURIComponent(g.join("="))]}))}function d(n,r){let f={},g=n.split("/"),[u]=r.split("?"),C=u.split("/");if(g.length!==C.length)return null;for(let o=0;o<g.length;o++)if(g[o].startsWith(":"))f[g[o].slice(1)]=C[o];return f}async function a(n){let r=n.headers.get("Content-Type");if(!r)return{};if(n.headers.get("Content-Length")==="0"||!n.body)return{};try{if(r.startsWith("application/json"))return await n.json();if(r.startsWith("application/x-www-form-urlencoded")){let g=await n.text();return Object.fromEntries(new URLSearchParams(g))}if(r.startsWith("multipart/form-data")){let g=await n.formData(),u={};for(let[C,o]of g.entries())u[C]=o;return u}return{error:"Unknown request body type"}}catch(g){return{error:"Invalid request body format"}}}async function R(n,r,f,g){let u=G(n,r,f),C=g.trie.search(f.pathname,n.method);n.routePattern=C?.path;try{if(g.hasFilterEnabled){let i=n.routePattern??f.pathname,v=await nn(g,i,u,r);if(v)return v}if(g.hasMiddleware){if(g.globalMiddlewares.length){let v=await s(g.globalMiddlewares,u,r);if(v)return v}let i=g.middlewares.get(f.pathname)||[];if(i?.length){let v=await s(i,u,r);if(v)return v}}if(!C?.handler||C.method!==n.method){if(g.staticPath){let i=await rn(g,f.pathname,u);if(i)return i;let v=g.trie.search("*",n.method);if(v?.handler)return await v.handler(u)}if(g.hooks.routeNotFound?.length&&Array.isArray(g.hooks.routeNotFound)&&!C?.handler){let i=g.hooks.routeNotFound;for(let v=0;v<i.length;v++){let b=await i[v](u);if(b)return b}}if(!C||!C?.handler?.length)return l(404,`Route not found for ${f.pathname}`);if(C?.method!==n.method)return l(405,"Method not allowed")}if(g.hooks.preHandler?.length&&Array.isArray(g.hooks.preHandler)){let i=g.hooks.preHandler;for(let v=0;v<i.length;v++){let b=await i[v](u);if(b)return b}}let o=C.handler(u),m=o instanceof Promise?await o:o;if(g.hooks.onSend?.length&&Array.isArray(g.hooks.onSend)){let i=g.hooks.onSend;for(let v=0;v<i.length;v++){let b=await i[v](u);if(b)return b}}return m??l(204,"No response from this handler")}catch(o){return g.hooks.onError?.length&&Array.isArray(g.hooks.onError)?g.hooks.onError[0](o,n,f,r):l(500,"Internal Server Error")}finally{if(g.hooks.postHandler?.length&&Array.isArray(g.hooks.postHandler)){let o=g.hooks.postHandler;for(let m=0;m<o.length;m++){let i=await o[m](u);if(i)return i}}}}async function s(n,r,f){for(let g of n){let u=await g(r,f);if(u)return u}return null}async function nn(n,r,f,g){if(!n.filters.has(r))if(n.filterFunction.length)for(let u of n.filterFunction){let C=await u(f,g);if(C)return C}else return f.json({error:!0,message:"Protected route, authentication required",status:401},401)}function l(n,r){return new Response(JSON.stringify({error:!0,message:r,status:n}),{status:n,headers:{"Content-Type":"application/json"}})}async function rn(n,r,f){if(!n.staticPath)return null;let g=`${n.staticPath}${r}`;if(await Bun.file(g).exists()){let C=O(g);return f.file(g,C,200)}return null}var{create:on,defineProperty:W,getOwnPropertyDescriptor:fn,getOwnPropertyNames:gn,getPrototypeOf:mn}=Object,vn=Object.prototype.hasOwnProperty,un=(n,r)=>()=>(r||n((r={exports:{}}).exports,r),r.exports),An=(n,r,f,g)=>{if(r&&typeof r=="object"||typeof r=="function")for(let u of gn(r))!vn.call(n,u)&&u!==f&&W(n,u,{get:()=>r[u],enumerable:!(g=fn(r,u))||g.enumerable});return n},Cn=(n,r,f)=>(f=n!=null?on(mn(n)):{},An(r||!n||!n.__esModule?W(f,"default",{value:n,enumerable:!0}):f,n)),bn=un((n,r)=>{function f(o){if(typeof o!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(o))}function g(o,m){for(var i="",v=0,b=-1,A=0,$,c=0;c<=o.length;++c){if(c<o.length)$=o.charCodeAt(c);else{if($===47)break;$=47}if($===47){if(!(b===c-1||A===1))if(b!==c-1&&A===2){if(i.length<2||v!==2||i.charCodeAt(i.length-1)!==46||i.charCodeAt(i.length-2)!==46){if(i.length>2){var y=i.lastIndexOf("/");if(y!==i.length-1){y===-1?(i="",v=0):(i=i.slice(0,y),v=i.length-1-i.lastIndexOf("/")),b=c,A=0;continue}}else if(i.length===2||i.length===1){i="",v=0,b=c,A=0;continue}}m&&(i.length>0?i+="/..":i="..",v=2)}else i.length>0?i+="/"+o.slice(b+1,c):i=o.slice(b+1,c),v=c-b-1;b=c,A=0}else $===46&&A!==-1?++A:A=-1}return i}function u(o,m){var i=m.dir||m.root,v=m.base||(m.name||"")+(m.ext||"");return i?i===m.root?i+v:i+o+v:v}var C={resolve:function(){for(var o="",m=!1,i,v=arguments.length-1;v>=-1&&!m;v--){var b;v>=0?b=arguments[v]:(i===void 0&&(i=process.cwd()),b=i),f(b),b.length!==0&&(o=b+"/"+o,m=b.charCodeAt(0)===47)}return o=g(o,!m),m?o.length>0?"/"+o:"/":o.length>0?o:"."},normalize:function(o){if(f(o),o.length===0)return".";var m=o.charCodeAt(0)===47,i=o.charCodeAt(o.length-1)===47;return o=g(o,!m),o.length===0&&!m&&(o="."),o.length>0&&i&&(o+="/"),m?"/"+o:o},isAbsolute:function(o){return f(o),o.length>0&&o.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var o,m=0;m<arguments.length;++m){var i=arguments[m];f(i),i.length>0&&(o===void 0?o=i:o+="/"+i)}return o===void 0?".":C.normalize(o)},relative:function(o,m){if(f(o),f(m),o===m||(o=C.resolve(o),m=C.resolve(m),o===m))return"";for(var i=1;i<o.length&&o.charCodeAt(i)===47;++i);for(var v=o.length,b=v-i,A=1;A<m.length&&m.charCodeAt(A)===47;++A);for(var $=m.length,c=$-A,y=b<c?b:c,F=-1,L=0;L<=y;++L){if(L===y){if(c>y){if(m.charCodeAt(A+L)===47)return m.slice(A+L+1);if(L===0)return m.slice(A+L)}else b>y&&(o.charCodeAt(i+L)===47?F=L:L===0&&(F=0));break}var Y=o.charCodeAt(i+L),H=m.charCodeAt(A+L);if(Y!==H)break;Y===47&&(F=L)}var w="";for(L=i+F+1;L<=v;++L)(L===v||o.charCodeAt(L)===47)&&(w.length===0?w+="..":w+="/..");return w.length>0?w+m.slice(A+F):(A+=F,m.charCodeAt(A)===47&&++A,m.slice(A))},_makeLong:function(o){return o},dirname:function(o){if(f(o),o.length===0)return".";for(var m=o.charCodeAt(0),i=m===47,v=-1,b=!0,A=o.length-1;A>=1;--A)if(m=o.charCodeAt(A),m===47){if(!b){v=A;break}}else b=!1;return v===-1?i?"/":".":i&&v===1?"//":o.slice(0,v)},basename:function(o,m){if(m!==void 0&&typeof m!="string")throw new TypeError('"ext" argument must be a string');f(o);var i=0,v=-1,b=!0,A;if(m!==void 0&&m.length>0&&m.length<=o.length){if(m.length===o.length&&m===o)return"";var $=m.length-1,c=-1;for(A=o.length-1;A>=0;--A){var y=o.charCodeAt(A);if(y===47){if(!b){i=A+1;break}}else c===-1&&(b=!1,c=A+1),$>=0&&(y===m.charCodeAt($)?--$===-1&&(v=A):($=-1,v=c))}return i===v?v=c:v===-1&&(v=o.length),o.slice(i,v)}else{for(A=o.length-1;A>=0;--A)if(o.charCodeAt(A)===47){if(!b){i=A+1;break}}else v===-1&&(b=!1,v=A+1);return v===-1?"":o.slice(i,v)}},extname:function(o){f(o);for(var m=-1,i=0,v=-1,b=!0,A=0,$=o.length-1;$>=0;--$){var c=o.charCodeAt($);if(c===47){if(!b){i=$+1;break}continue}v===-1&&(b=!1,v=$+1),c===46?m===-1?m=$:A!==1&&(A=1):m!==-1&&(A=-1)}return m===-1||v===-1||A===0||A===1&&m===v-1&&m===i+1?"":o.slice(m,v)},format:function(o){if(o===null||typeof o!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof o);return u("/",o)},parse:function(o){f(o);var m={root:"",dir:"",base:"",ext:"",name:""};if(o.length===0)return m;var i=o.charCodeAt(0),v=i===47,b;v?(m.root="/",b=1):b=0;for(var A=-1,$=0,c=-1,y=!0,F=o.length-1,L=0;F>=b;--F){if(i=o.charCodeAt(F),i===47){if(!y){$=F+1;break}continue}c===-1&&(y=!1,c=F+1),i===46?A===-1?A=F:L!==1&&(L=1):A!==-1&&(L=-1)}return A===-1||c===-1||L===0||L===1&&A===c-1&&A===$+1?c!==-1&&($===0&&v?m.base=m.name=o.slice(1,c):m.base=m.name=o.slice($,c)):($===0&&v?(m.name=o.slice(1,A),m.base=o.slice(1,c)):(m.name=o.slice($,A),m.base=o.slice($,c)),m.ext=o.slice(A,c)),$>0?m.dir=o.slice(0,$-1):v&&(m.dir="/"),m},sep:"/",delimiter:":",win32:null,posix:null};C.posix=C,r.exports=C}),I=Cn(bn()),E=I,cn=I,J=function(n){return n},S=function(){throw new Error("Not implemented")};E.parse??=S;cn.parse??=S;var T={resolve:E.resolve.bind(E),normalize:E.normalize.bind(E),isAbsolute:E.isAbsolute.bind(E),join:E.join.bind(E),relative:E.relative.bind(E),toNamespacedPath:J,dirname:E.dirname.bind(E),basename:E.basename.bind(E),extname:E.extname.bind(E),format:E.format.bind(E),parse:E.parse.bind(E),sep:"/",delimiter:":",win32:void 0,posix:void 0,_makeLong:J},M={sep:"\\",delimiter:";",win32:void 0,...T,posix:T};T.win32=M.win32=M;T.posix=T;var z=T;var{default:X}=(()=>({}));var N={reset:"\x1B[0m",info:"\x1B[34m",warn:"\x1B[33m",error:"\x1B[31m",method:{GET:"\x1B[32m",POST:"\x1B[36m",PUT:"\x1B[35m",DELETE:"\x1B[31m"}},K=(n,r,f)=>{let g=N[n]||N.reset,u=f?.method?N.method[f.method]||N.reset:N.reset;console.log(`
|
|
2
|
-
${g}[${n.toUpperCase()}]${
|
|
3
|
-
`)},B=(n)=>{n.addHooks("onRequest",async(r,
|
|
1
|
+
var H=Object.create;var{getPrototypeOf:l,defineProperty:M,getOwnPropertyNames:q}=Object;var P=Object.prototype.hasOwnProperty;var k=(n,r,o)=>{o=n!=null?H(l(n)):{};let g=r||!n||!n.__esModule?M(o,"default",{value:n,enumerable:!0}):o;for(let m of q(n))if(!P.call(g,m))M(g,m,{get:()=>n[m],enumerable:!0});return g};var p=((n)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(n,{get:(r,o)=>(typeof require!=="undefined"?require:r)[o]}):n)(function(n){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});class O{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 T{root;constructor(){this.root=new O}insert(n,r){let o=this.root,g=n.split("/").filter(Boolean);if(n==="/"){o.isEndOfWord=!0,o.handler.push(r.handler),o.path=n,o.method.push(r.method);return}for(let m of g){let s=!1,i=m;if(m.startsWith(":"))s=!0,i=":";if(!o.children[i])o.children[i]=new O;o=o.children[i],o.isDynamic=s,o.pattern=m}o.isEndOfWord=!0,o.path=n,o.method.push(r.method),o.handler.push(r.handler)}search(n,r){let o=this.root,g=n.split("/").filter(Boolean),m=g.length;for(let u of g){let f=u;if(!o.children[f])if(o.children[":"])o=o.children[":"];else return null;else o=o.children[f]}let s=o.path.split("/").filter(Boolean);if(m!==s.length)return null;let i=o.method.indexOf(r);if(i!==-1)return{path:o.path,handler:o.handler[i],isDynamic:o.isDynamic,pattern:o.pattern,method:o.method[i]};return{path:o.path,handler:o.handler,isDynamic:o.isDynamic,pattern:o.pattern,method:o.method[i]}}}function x(n){switch(n.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"}}function D(n,r,o){let g=null,m=null,s=null,i=null,u={};return{req:n,server:r,url:o,status:200,headers:new Headers({"Cache-Control":"no-cache"}),setHeader(f,t){return this.headers.set(f,t),this},removeHeader(f){return this.headers.delete(f),this},get ip(){return this.server.requestIP(this.req)?.address??null},get query(){if(!g)try{g=Object.fromEntries(this.url.searchParams)}catch(f){throw new Error("Failed to parse query parameters")}return g},get params(){if(!m&&this.req.routePattern)try{m=d(this.req.routePattern,this.url.pathname)}catch(f){throw new Error("Failed to extract route parameters")}return m??{}},get body(){if(this.req.method==="GET")return Promise.resolve({});if(!i)i=(async()=>{let f=await a(this.req);if(f.error)throw new Error(f.error);return Object.keys(f).length===0?null:f})();return i},set(f,t){return u[f]=t,this},get(f){return u[f]},text(f,t){if(t)this.status=t;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","text/plain; charset=utf-8");return new Response(f,{status:this.status,headers:this.headers})},send(f,t){if(t)this.status=t;let C=new Map([["string","text/plain; charset=utf-8"],["object","application/json; charset=utf-8"],["Uint8Array","application/octet-stream"],["ArrayBuffer","application/octet-stream"]]),v=f instanceof Uint8Array?"Uint8Array":f instanceof ArrayBuffer?"ArrayBuffer":typeof f;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",C.get(v)??"text/plain; charset=utf-8");let $=v==="object"&&f!==null?JSON.stringify(f):f;return new Response($,{status:this.status,headers:this.headers})},json(f,t){if(t)this.status=t;if(!this.headers.has("Content-Type"))this.headers.set("Content-Type","application/json; charset=utf-8");return Response.json(f,{status:this.status,headers:this.headers})},file(f,t,C){if(C)this.status=C;let v=Bun.file(f);if(!this.headers.has("Content-Type"))this.headers.set("Content-Type",t??x(f));return new Response(v,{status:this.status,headers:this.headers})},async ejs(f,t={},C){if(C)this.status=C;let v;try{v=await import("ejs"),v=v.default||v}catch($){return console.error("EJS not installed! Please run `bun add ejs`"),new Response("EJS not installed! Please run `bun add ejs`",{status:500})}try{let $=await Bun.file(f).text(),c=v.render($,t),E=new Headers({"Content-Type":"text/html; charset=utf-8"});return new Response(c,{status:this.status,headers:E})}catch($){return console.error("EJS Rendering Error:",$),new Response("Error rendering template",{status:500})}},redirect(f,t){if(t)this.status=t;else this.status=302;return this.headers.set("Location",f),new Response(null,{status:this.status,headers:this.headers})},stream(f){let t=new Headers(this.headers),C=new ReadableStream({async start(v){await f(v),v.close()}});return new Response(C,{headers:t})},yieldStream(f){return new Response({async*[Symbol.asyncIterator](){yield*f()}},{headers:this.headers})},setCookie(f,t,C={}){let v=`${encodeURIComponent(f)}=${encodeURIComponent(t)}`;if(C.maxAge)v+=`; Max-Age=${C.maxAge}`;if(C.expires)v+=`; Expires=${C.expires.toUTCString()}`;if(C.path)v+=`; Path=${C.path}`;if(C.domain)v+=`; Domain=${C.domain}`;if(C.secure)v+="; Secure";if(C.httpOnly)v+="; HttpOnly";if(C.sameSite)v+=`; SameSite=${C.sameSite}`;return this.headers.append("Set-Cookie",v),this},get cookies(){if(!s){let f=this.req.headers.get("cookie");s=f?h(f):{}}return s}}}function h(n){return Object.fromEntries(n.split(";").map((r)=>{let[o,...g]=r.trim().split("=");return[o,decodeURIComponent(g.join("="))]}))}function d(n,r){let o={},g=n.split("/"),[m]=r.split("?"),s=m.split("/");if(g.length!==s.length)return null;for(let i=0;i<g.length;i++)if(g[i].startsWith(":"))o[g[i].slice(1)]=s[i];return o}async function a(n){let r=n.headers.get("Content-Type");if(!r)return{};if(n.headers.get("Content-Length")==="0"||!n.body)return{};try{if(r.startsWith("application/json"))return await n.json();if(r.startsWith("application/x-www-form-urlencoded")){let g=await n.text();return Object.fromEntries(new URLSearchParams(g))}if(r.startsWith("multipart/form-data")){let g=await n.formData(),m={};for(let[s,i]of g.entries())m[s]=i;return m}return{error:"Unknown request body type"}}catch(g){return{error:"Invalid request body format"}}}async function G(n,r,o,g){let m=D(n,r,o),s=g.trie.search(o.pathname,n.method);n.routePattern=s?.path;try{if(o.pathname.startsWith("/favicon"))return;if(g.hasFilterEnabled){let f=n.routePattern??o.pathname,t=await nn(g,f,m,r);if(t)return t}if(g.hasMiddleware){if(g.globalMiddlewares.length){let t=await S(g.globalMiddlewares,m,r);if(t)return t}let f=g.middlewares.get(o.pathname)||[];if(f?.length){let t=await S(f,m,r);if(t)return t}}if(!s?.handler||s.method!==n.method){if(g.staticPath){let f=await rn(g,o.pathname,m);if(f)return f;let t=g.trie.search("*",n.method);if(t?.handler)return await t.handler(m)}if(g.hooks.routeNotFound&&Array.isArray(g.hooks.routeNotFound)&&!s?.handler){let f=g.hooks.routeNotFound;for(let t=0;t<f.length;t++){let C=await f[t](m);if(C)return C}}if(!s||!s?.handler?.length)return z(404,`Route not found for ${o.pathname}`);if(s?.method!==n.method)return z(405,"Method not allowed")}if(g.hooks.preHandler?.length&&Array.isArray(g.hooks.preHandler)){let f=g.hooks.preHandler;for(let t=0;t<f.length;t++){let C=await f[t](m);if(C)return C}}let i=s.handler(m);return(i instanceof Promise?await i:i)??z(204,"")}catch(i){if(g.hooks.onError&&Array.isArray(g.hooks.onError)){let u=g.hooks.onError;for(let f=0;f<u.length;f++){let t=g.hooks.onError[f](i,n,o,r);if(t)return t}}return z(500,"Internal Server Error")}finally{if(g.hooks.onSend&&Array.isArray(g.hooks.onSend)){let i=g.hooks.onSend;for(let u=0;u<i.length;u++){let f=await i[u](m);if(f)return f}}}}async function S(n,r,o){for(let g of n){let m=await g(r,o);if(m)return m}return null}async function nn(n,r,o,g){if(!n.filters.has(r))if(n.filterFunction.length)for(let m of n.filterFunction){let s=await m(o,g);if(s)return s}else return o.json({error:!0,message:"Protected route, authentication required",status:401},401)}function z(n,r){return new Response(JSON.stringify({error:!0,message:r,status:n}),{status:n,headers:{"Content-Type":"application/json"}})}async function rn(n,r,o){if(!n.staticPath)return null;let g=`${n.staticPath}${r}`;if(await Bun.file(g).exists()){let s=x(g);return o.file(g,s,200)}return null}var{create:on,defineProperty:Z,getOwnPropertyDescriptor:fn,getOwnPropertyNames:gn,getPrototypeOf:un}=Object,tn=Object.prototype.hasOwnProperty,mn=(n,r)=>()=>(r||n((r={exports:{}}).exports,r),r.exports),vn=(n,r,o,g)=>{if(r&&typeof r=="object"||typeof r=="function")for(let m of gn(r))!tn.call(n,m)&&m!==o&&Z(n,m,{get:()=>r[m],enumerable:!(g=fn(r,m))||g.enumerable});return n},sn=(n,r,o)=>(o=n!=null?on(un(n)):{},vn(r||!n||!n.__esModule?Z(o,"default",{value:n,enumerable:!0}):o,n)),Cn=mn((n,r)=>{function o(i){if(typeof i!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(i))}function g(i,u){for(var f="",t=0,C=-1,v=0,$,c=0;c<=i.length;++c){if(c<i.length)$=i.charCodeAt(c);else{if($===47)break;$=47}if($===47){if(!(C===c-1||v===1))if(C!==c-1&&v===2){if(f.length<2||t!==2||f.charCodeAt(f.length-1)!==46||f.charCodeAt(f.length-2)!==46){if(f.length>2){var E=f.lastIndexOf("/");if(E!==f.length-1){E===-1?(f="",t=0):(f=f.slice(0,E),t=f.length-1-f.lastIndexOf("/")),C=c,v=0;continue}}else if(f.length===2||f.length===1){f="",t=0,C=c,v=0;continue}}u&&(f.length>0?f+="/..":f="..",t=2)}else f.length>0?f+="/"+i.slice(C+1,c):f=i.slice(C+1,c),t=c-C-1;C=c,v=0}else $===46&&v!==-1?++v:v=-1}return f}function m(i,u){var f=u.dir||u.root,t=u.base||(u.name||"")+(u.ext||"");return f?f===u.root?f+t:f+i+t:t}var s={resolve:function(){for(var i="",u=!1,f,t=arguments.length-1;t>=-1&&!u;t--){var C;t>=0?C=arguments[t]:(f===void 0&&(f=process.cwd()),C=f),o(C),C.length!==0&&(i=C+"/"+i,u=C.charCodeAt(0)===47)}return i=g(i,!u),u?i.length>0?"/"+i:"/":i.length>0?i:"."},normalize:function(i){if(o(i),i.length===0)return".";var u=i.charCodeAt(0)===47,f=i.charCodeAt(i.length-1)===47;return i=g(i,!u),i.length===0&&!u&&(i="."),i.length>0&&f&&(i+="/"),u?"/"+i:i},isAbsolute:function(i){return o(i),i.length>0&&i.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var i,u=0;u<arguments.length;++u){var f=arguments[u];o(f),f.length>0&&(i===void 0?i=f:i+="/"+f)}return i===void 0?".":s.normalize(i)},relative:function(i,u){if(o(i),o(u),i===u||(i=s.resolve(i),u=s.resolve(u),i===u))return"";for(var f=1;f<i.length&&i.charCodeAt(f)===47;++f);for(var t=i.length,C=t-f,v=1;v<u.length&&u.charCodeAt(v)===47;++v);for(var $=u.length,c=$-v,E=C<c?C:c,w=-1,A=0;A<=E;++A){if(A===E){if(c>E){if(u.charCodeAt(v+A)===47)return u.slice(v+A+1);if(A===0)return u.slice(v+A)}else C>E&&(i.charCodeAt(f+A)===47?w=A:A===0&&(w=0));break}var K=i.charCodeAt(f+A),j=u.charCodeAt(v+A);if(K!==j)break;K===47&&(w=A)}var F="";for(A=f+w+1;A<=t;++A)(A===t||i.charCodeAt(A)===47)&&(F.length===0?F+="..":F+="/..");return F.length>0?F+u.slice(v+w):(v+=w,u.charCodeAt(v)===47&&++v,u.slice(v))},_makeLong:function(i){return i},dirname:function(i){if(o(i),i.length===0)return".";for(var u=i.charCodeAt(0),f=u===47,t=-1,C=!0,v=i.length-1;v>=1;--v)if(u=i.charCodeAt(v),u===47){if(!C){t=v;break}}else C=!1;return t===-1?f?"/":".":f&&t===1?"//":i.slice(0,t)},basename:function(i,u){if(u!==void 0&&typeof u!="string")throw new TypeError('"ext" argument must be a string');o(i);var f=0,t=-1,C=!0,v;if(u!==void 0&&u.length>0&&u.length<=i.length){if(u.length===i.length&&u===i)return"";var $=u.length-1,c=-1;for(v=i.length-1;v>=0;--v){var E=i.charCodeAt(v);if(E===47){if(!C){f=v+1;break}}else c===-1&&(C=!1,c=v+1),$>=0&&(E===u.charCodeAt($)?--$===-1&&(t=v):($=-1,t=c))}return f===t?t=c:t===-1&&(t=i.length),i.slice(f,t)}else{for(v=i.length-1;v>=0;--v)if(i.charCodeAt(v)===47){if(!C){f=v+1;break}}else t===-1&&(C=!1,t=v+1);return t===-1?"":i.slice(f,t)}},extname:function(i){o(i);for(var u=-1,f=0,t=-1,C=!0,v=0,$=i.length-1;$>=0;--$){var c=i.charCodeAt($);if(c===47){if(!C){f=$+1;break}continue}t===-1&&(C=!1,t=$+1),c===46?u===-1?u=$:v!==1&&(v=1):u!==-1&&(v=-1)}return u===-1||t===-1||v===0||v===1&&u===t-1&&u===f+1?"":i.slice(u,t)},format:function(i){if(i===null||typeof i!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof i);return m("/",i)},parse:function(i){o(i);var u={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return u;var f=i.charCodeAt(0),t=f===47,C;t?(u.root="/",C=1):C=0;for(var v=-1,$=0,c=-1,E=!0,w=i.length-1,A=0;w>=C;--w){if(f=i.charCodeAt(w),f===47){if(!E){$=w+1;break}continue}c===-1&&(E=!1,c=w+1),f===46?v===-1?v=w:A!==1&&(A=1):v!==-1&&(A=-1)}return v===-1||c===-1||A===0||A===1&&v===c-1&&v===$+1?c!==-1&&($===0&&t?u.base=u.name=i.slice(1,c):u.base=u.name=i.slice($,c)):($===0&&t?(u.name=i.slice(1,v),u.base=i.slice(1,c)):(u.name=i.slice($,v),u.base=i.slice($,c)),u.ext=i.slice(v,c)),$>0?u.dir=i.slice(0,$-1):t&&(u.dir="/"),u},sep:"/",delimiter:":",win32:null,posix:null};s.posix=s,r.exports=s}),U=sn(Cn()),b=U,cn=U,X=function(n){return n},V=function(){throw new Error("Not implemented")};b.parse??=V;cn.parse??=V;var y={resolve:b.resolve.bind(b),normalize:b.normalize.bind(b),isAbsolute:b.isAbsolute.bind(b),join:b.join.bind(b),relative:b.relative.bind(b),toNamespacedPath:X,dirname:b.dirname.bind(b),basename:b.basename.bind(b),extname:b.extname.bind(b),format:b.format.bind(b),parse:b.parse.bind(b),sep:"/",delimiter:":",win32:void 0,posix:void 0,_makeLong:X},Y={sep:"\\",delimiter:";",win32:void 0,...y,posix:y};y.win32=Y.win32=Y;y.posix=y;var N=y;var{default:e}=(()=>({}));var L={reset:"\x1B[0m",info:"\x1B[34m",warn:"\x1B[33m",error:"\x1B[31m",method:{GET:"\x1B[32m",POST:"\x1B[36m",PUT:"\x1B[35m",DELETE:"\x1B[31m"}},W=(n,r,o)=>{let g=L[n]||L.reset,m=o?.method?L.method[o.method]||L.reset:L.reset,s=o?.status?o.status>=500?L.error:o.status>=400?L.warn:L.info:L.reset;console.log(`
|
|
2
|
+
${g}[${n.toUpperCase()}]${L.reset} ${r} - ${m}${o?.method||""}${L.reset}`);let i={timestamp:new Date().toISOString(),...o,status:o?.status?`${s}${o.status}${L.reset}`:void 0,method:o?.method?`${m}${o.method}${L.reset}`:void 0};console.log(JSON.stringify(i,null,2)+`
|
|
3
|
+
`)},B=(n)=>{n.addHooks("onRequest",async(r,o)=>{r.startTime=Date.now(),W("info","Incoming Request",{method:r.method,url:o.toString(),headers:{"user-agent":r.headers.get("user-agent"),"content-type":r.headers.get("Content-Type")}})}),n.addHooks("onSend",(r)=>{let o=`${Date.now()-r.req.startTime}ms`;W("info","Response Sent",{method:r.req.method,url:r.url,status:r.status,duration:o,headers:{"content-type":r.headers.get("Content-Type")}})})},R=(n,r,o,g=0,m)=>{let s=L.method[r]||L.reset,i=g>=500?L.error:g>=400?L.warn:L.info,u=n==="<--"?`${n} ${s}${r}${L.reset} ${o}`:`${n} ${s}${r}${L.reset} ${o} ${i}${g}${L.reset} ${m||""}`;console.log(u)},$n=(n)=>{let r=Date.now()-n;return r<1000?`${r}ms`:`${Math.round(r/1000)}s`},J=(n)=>{n.addHooks("onRequest",(r,o)=>{r.startTime=Date.now(),R("<--",r.method,new URL(o).pathname)}),n.addHooks("onSend",async(r)=>{let{method:o,url:g}=r.req,m=new URL(g).pathname;R("-->",o,m,r.status,$n(r.req.startTime))}),n.addHooks("routeNotFound",(r)=>{R("[routeNotFound]",r.req.method,r.url.pathname,404)}),n.addHooks("onError",(r,o,g)=>{R(r?.message,o.method,g.toString(),500)})};function I(n,r){if(!n)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(o)=>{try{let g=o.cookies?.accessToken||o.req?.headers?.get("Authorization");if(!g)return o.json({message:"Unauthorized: No token provided"},401);if(g.startsWith("Bearer "))g=g.slice(7);let m=n?.verify(g,r);if(!m)return o.json({message:"Unauthorized: Invalid token"},401);o.set("user",m)}catch(g){return console.error("JWT verification error:",g),o.json({message:"Unauthorized: Invalid token",error:g?.message},401)}}}function Q(n,r,o){if(!n)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!r)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(g)=>{try{let m=g.cookies?.accessToken||g.req?.headers?.get("Authorization");if(!m)return g.json({message:"Unauthorized: No token provided"},401);if(m.startsWith("Bearer "))m=m.slice(7);let s=n?.verify(m,o);if(!s)return g.json({message:"Unauthorized: Invalid token"},401);let i=await r.findById(s._id).select("-password -refreshToken");if(!i)return g.json({message:"Unauthorized: User not found"},401);g.set("user",i);return}catch(m){return g.json({message:"Unauthorized: Authentication failed",error:m?.message},401)}}}class _{tempRoutes;globalMiddlewares;middlewares;trie;hasOnReqHook;hasMiddleware;hasPreHandlerHook;hasPostHandlerHook;hasOnSendHook;hasOnError;hooks;corsConfig;FilterRoutes;filters;filterFunction;hasFilterEnabled;serverInstance;staticPath;staticFiles;user_jwt_secret;baseApiUrl;enableFileRouter;idleTimeOut;constructor({jwtSecret:n,baseApiUrl:r,enableFileRouting:o,idleTimeOut:g}={}){this.idleTimeOut=g??10,this.enableFileRouter=o??!1,this.baseApiUrl=r||"",this.user_jwt_secret=n||process.env.DIESEL_JWT_SECRET||"feault_diesel_secret_for_jwt",this.tempRoutes=new Map,this.globalMiddlewares=[],this.middlewares=new Map,this.trie=new T,this.corsConfig=null,this.hasMiddleware=!1,this.hasOnReqHook=!1,this.hasPreHandlerHook=!1,this.hasPostHandlerHook=!1,this.hasOnSendHook=!1,this.hasOnError=!1,this.hooks={onRequest:[],preHandler:[],postHandler:[],onSend:[],onError:[],onClose:[],routeNotFound:[]},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:(...n)=>{return this.FilterRoutes=n,this.setupFilter()},permitAll:()=>{for(let n of this?.FilterRoutes)this.filters.add(n);return this.FilterRoutes=null,this.setupFilter()},authenticate:(n)=>{if(n?.length)for(let r of n)this.filterFunction.push(r)},authenticateJwt:(n)=>{this.filterFunction.push(I(n,this.user_jwt_secret))},authenticateJwtDB:(n,r)=>{this.filterFunction.push(Q(n,r,this.user_jwt_secret))}}}redirect(n,r,o){return this.any(n,(g)=>{let m=g.params,s=r;if(m)for(let u in m)s=s.replace(`:${u}`,m[u]);let i=g.url.search;if(i)s+=i;return g.redirect(s,o)}),this}serveStatic(n){return this.staticPath=n,this}static(n){return this.staticFiles={...this.staticFiles,...n},this}addHooks(n,r){if(typeof n!=="string")throw new Error("hookName must be a string");if(typeof r!=="function")throw new Error("callback must be a instance of function");switch(n){case"onRequest":this.hooks.onRequest?.push(r);break;case"preHandler":this.hooks.preHandler?.push(r);break;case"postHandler":this.hooks.postHandler?.push(r);break;case"onSend":this.hooks.onSend?.push(r);break;case"onError":this.hooks.onError?.push(r);break;case"onClose":this.hooks.onClose?.push(r);break;case"routeNotFound":this.hooks.routeNotFound?.push(r);break;default:throw new Error(`Unknown hook type: ${n}`)}return this}compile(){if(this.globalMiddlewares.length>0)this.hasMiddleware=!0;for(let[n,r]of this.middlewares.entries())if(r.length>0){this.hasMiddleware=!0;break}if(this.enableFileRouter){let n=process.cwd(),r=N.join(n,"src","routes");if(e?.existsSync(r))this.loadRoutes(r,"")}setTimeout(()=>{this.tempRoutes=null},2000)}async registerFileRoutes(n,r,o){let g=await import(n),m;if(o===".ts")m=N.basename(n,".ts");else if(o===".js")m=N.basename(n,".js");let s=r+"/"+m;if(s.endsWith("/index"))s=r;else if(s.endsWith("/api"))s=r;s=s.replace(/\[(.*?)\]/g,":$1");let i=["GET","POST","PUT","PATCH","DELETE","ANY","HEAD","OPTIONS","PROPFIND"];for(let u of i)if(g[u]){let f=u.toLowerCase(),t=g[u];this[f](`${this.baseApiUrl}${s}`,t)}}async loadRoutes(n,r){let o=await e.promises.readdir(n);for(let g of o){let m=N.join(n,g);if((await e.promises.stat(m)).isDirectory())this.loadRoutes(m,r+"/"+g);else if(g.endsWith(".ts"))this.registerFileRoutes(m,r,".ts");else if(g.endsWith(".js"))this.registerFileRoutes(m,r,".js")}}useLogger(n){return J(n),this}useAdvancedLogger(n){return B(n),this}listen(n,...r){if(typeof Bun==="undefined")throw new Error(".listen() is designed to run on Bun only...");let o="0.0.0.0",g=void 0,m={};for(let i of r)if(typeof i==="string")o=i;else if(typeof i==="function")g=i;else if(typeof i==="object"&&i!==null)m=i;this.compile();let s={port:n,hostname:o,idleTimeOut:this.idleTimeOut,fetch:async(i,u)=>{let f=new URL(i.url);if(this.hooks.onRequest){let t=this.hooks.onRequest;for(let C=0;C<t.length;C++)await t[C](i,f,u)}return G(i,u,f,this)},static:this.staticFiles};if(m.sslCert&&m.sslKey)s.certFile=m.sslCert,s.keyFile=m.sslKey;if(this.serverInstance=Bun?.serve(s),m.sslCert&&m.sslKey)console.log(`HTTPS server is running on https://localhost:${n}`);if(g)return g();return this.serverInstance}close(n){if(this.serverInstance)this.serverInstance.stop(!0),this.serverInstance=null,n?n():console.log("Server has been stopped");else console.warn("Server is not running.")}route(n,r){if(!n||typeof n!=="string")throw new Error("Path must be a string");let o=Object.fromEntries(r.tempRoutes);return Object.entries(o).forEach(([m,s])=>{let i=m.replace(/::\w+$/,""),u=`${n}${i}`;if(!this.middlewares.has(u))this.middlewares.set(u,[]);s.handlers.slice(0,-1).forEach((v)=>{if(!this.middlewares.get(u)?.includes(v))this.middlewares.get(u)?.push(v)});let t=s.handlers[s.handlers.length-1],C=s.method;try{this.trie.insert(u,{handler:t,method:C})}catch(v){console.error(`Error inserting ${u}:`,v)}}),r=null,this}register(n,r){return this.route(n,r)}addRoute(n,r,o){if(typeof r!=="string")throw new Error(`Error in ${o[o.length-1]}: Path must be a string. Received: ${typeof r}`);if(typeof n!=="string")throw new Error(`Error in addRoute: Method must be a string. Received: ${typeof n}`);this.tempRoutes?.set(r+"::"+n,{method:n,handlers:o});let g=o.slice(0,-1),m=o[o.length-1];if(!this.middlewares.has(r))this.middlewares.set(r,[]);g.forEach((s)=>{if(r==="/")this.globalMiddlewares=[...new Set([...this.globalMiddlewares,...g])];else if(!this.middlewares.get(r)?.includes(s))this.middlewares.get(r)?.push(s)});try{if(n==="ANY"){let s=["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD","PROPFIND"];for(let i of s)this.trie.insert(r,{handler:m,method:i})}this.trie.insert(r,{handler:m,method:n})}catch(s){console.error(`Error inserting ${r}:`,s)}}use(n,r){if(Array.isArray(n))n.forEach((g)=>{if(typeof g==="function")this.globalMiddlewares.push(g)});if(typeof n==="function"){if(this.globalMiddlewares.push(n),Array.isArray(r))r.forEach((g)=>{this.globalMiddlewares.push(g)});return}return(Array.isArray(n)?n.filter((g)=>typeof g==="string"):[n].filter((g)=>typeof g==="string")).forEach((g)=>{if(!this.middlewares.has(g))this.middlewares.set(g,[]);if(r)(Array.isArray(r)?r:[r]).forEach((s)=>{this.middlewares.get(g)?.push(s)})}),this}get(n,...r){return this.addRoute("GET",n,r),this}post(n,...r){return this.addRoute("POST",n,r),this}put(n,...r){return this.addRoute("PUT",n,r),this}patch(n,...r){return this.addRoute("PATCH",n,r),this}delete(n,...r){return this.addRoute("DELETE",n,r),this}any(n,...r){return this.addRoute("ANY",n,r),this}head(n,...r){return this.addRoute("HEAD",n,r),this}options(n,...r){return this.addRoute("OPTIONS",n,r),this}propfind(n,...r){return this.addRoute("PROPFIND",n,r),this}}export{_ as default};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import Diesel from "../../main";
|
|
2
|
+
import { ContextType } from "../../types";
|
|
3
|
+
type authenticateJwtT = {
|
|
4
|
+
app: Diesel;
|
|
5
|
+
jwt: any;
|
|
6
|
+
jwtSecret?: string;
|
|
7
|
+
routes?: string[];
|
|
8
|
+
};
|
|
9
|
+
type authenticateJwtDBT = {
|
|
10
|
+
app: Diesel;
|
|
11
|
+
userModel: any;
|
|
12
|
+
jwt: any;
|
|
13
|
+
jwtSecret?: string;
|
|
14
|
+
routes?: string[];
|
|
15
|
+
};
|
|
16
|
+
export declare const authenticateJwt: (options: authenticateJwtT) => (ctx: ContextType) => Response | undefined;
|
|
17
|
+
export declare const authenticateJwtDB: (options: authenticateJwtDBT) => (ctx: ContextType) => Promise<Response | undefined> | undefined;
|
|
18
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function G(f,z){if(!f)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(A)=>{try{let q=A.cookies?.accessToken||A.req?.headers?.get("Authorization");if(!q)return A.json({message:"Unauthorized: No token provided"},401);if(q.startsWith("Bearer "))q=q.slice(7);let v=f?.verify(q,z);if(!v)return A.json({message:"Unauthorized: Invalid token"},401);A.set("user",v)}catch(q){return console.error("JWT verification error:",q),A.json({message:"Unauthorized: Invalid token",error:q?.message},401)}}}function H(f,z,A){if(!f)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!z)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(q)=>{try{let v=q.cookies?.accessToken||q.req?.headers?.get("Authorization");if(!v)return q.json({message:"Unauthorized: No token provided"},401);if(v.startsWith("Bearer "))v=v.slice(7);let E=f?.verify(v,A);if(!E)return q.json({message:"Unauthorized: Invalid token"},401);let C=await z.findById(E._id).select("-password -refreshToken");if(!C)return q.json({message:"Unauthorized: User not found"},401);q.set("user",C);return}catch(v){return q.json({message:"Unauthorized: Authentication failed",error:v?.message},401)}}}var L=(f)=>{if(!f.app)throw new Error("Diesel app is not defined, please provide app to authenticateJwt Function");if(!f.jwt)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");if(!f.jwtSecret)f.jwtSecret=f.app.user_jwt_secret;let{routes:z,app:A,jwt:q,jwtSecret:v}=f,E=G(q,v);return(C)=>{if(z?.length===0||z?.includes(C.url.pathname))return E(C)}},N=(f)=>{if(!f.app)throw new Error("Diesel app is not defined, please provide app to authenticateJwt Function");if(!f.userModel)throw new Error("User model is not defined, please provide userModel to authenticateJwt Function");if(!f.jwt)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");if(!f.jwtSecret)f.jwtSecret=f.app.user_jwt_secret;let{routes:z,app:A,jwt:q,jwtSecret:v,userModel:E}=f,C=H(q,E,v);return(F)=>{if(z?.length===0||z?.includes(F.url.pathname))return C(F)}};export{N as authenticateJwtDB,L as authenticateJwt};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
${
|
|
3
|
-
`)},
|
|
1
|
+
var o={reset:"\x1B[0m",info:"\x1B[34m",warn:"\x1B[33m",error:"\x1B[31m",method:{GET:"\x1B[32m",POST:"\x1B[36m",PUT:"\x1B[35m",DELETE:"\x1B[31m"}},m=(n,e,t)=>{let s=o[n]||o.reset,r=t?.method?o.method[t.method]||o.reset:o.reset,d=t?.status?t.status>=500?o.error:t.status>=400?o.warn:o.info:o.reset;console.log(`
|
|
2
|
+
${s}[${n.toUpperCase()}]${o.reset} ${e} - ${r}${t?.method||""}${o.reset}`);let g={timestamp:new Date().toISOString(),...t,status:t?.status?`${d}${t.status}${o.reset}`:void 0,method:t?.method?`${r}${t.method}${o.reset}`:void 0};console.log(JSON.stringify(g,null,2)+`
|
|
3
|
+
`)},h=(n)=>{n.addHooks("onRequest",async(e,t)=>{e.startTime=Date.now(),m("info","Incoming Request",{method:e.method,url:t.toString(),headers:{"user-agent":e.headers.get("user-agent"),"content-type":e.headers.get("Content-Type")}})}),n.addHooks("onSend",(e)=>{let t=`${Date.now()-e.req.startTime}ms`;m("info","Response Sent",{method:e.req.method,url:e.url,status:e.status,duration:t,headers:{"content-type":e.headers.get("Content-Type")}})})},a=(n,e,t,s=0,r)=>{let d=o.method[e]||o.reset,g=s>=500?o.error:s>=400?o.warn:o.info,i=n==="<--"?`${n} ${d}${e}${o.reset} ${t}`:`${n} ${d}${e}${o.reset} ${t} ${g}${s}${o.reset} ${r||""}`;console.log(i)},u=(n)=>{let e=Date.now()-n;return e<1000?`${e}ms`:`${Math.round(e/1000)}s`},$=(n)=>{n.addHooks("onRequest",(e,t)=>{e.startTime=Date.now(),a("<--",e.method,new URL(t).pathname)}),n.addHooks("onSend",async(e)=>{let{method:t,url:s}=e.req,r=new URL(s).pathname;a("-->",t,r,e.status,u(e.req.startTime))}),n.addHooks("routeNotFound",(e)=>{a("[routeNotFound]",e.req.method,e.url.pathname,404)}),n.addHooks("onError",(e,t,s)=>{a(e?.message,t.method,s.toString(),500)})};export{$ as logger,h as advancedLogger};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module
|
|
3
|
+
* Powered By Middleware for Diesel.
|
|
4
|
+
*/
|
|
5
|
+
import { middlewareFunc } from "../../types";
|
|
6
|
+
type PoweredByOptions = {
|
|
7
|
+
/**
|
|
8
|
+
* The value for X-Powered-By header.
|
|
9
|
+
* @default Diesel
|
|
10
|
+
*/
|
|
11
|
+
serverName?: string;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Powered By Middleware for Diesel.
|
|
15
|
+
*
|
|
16
|
+
* @param options - The options for the Powered By Middleware.
|
|
17
|
+
* @returns {MiddlewareHandler} The middleware handler function.
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* ```ts
|
|
21
|
+
* import { poweredBy } from 'diesel-core/powered-by'
|
|
22
|
+
*
|
|
23
|
+
* const app = new Diesel()
|
|
24
|
+
*
|
|
25
|
+
* app.use(poweredBy()) // With options: poweredBy({ serverName: "My Server" })
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
export declare const poweredBy: (options?: PoweredByOptions) => middlewareFunc;
|
|
29
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var q=(g)=>{return async function k(j){j.setHeader("X-Powered-By",g?.serverName??"Diesel")}};export{q as poweredBy};
|
package/dist/types.d.ts
CHANGED
|
@@ -42,6 +42,8 @@ export interface ContextType {
|
|
|
42
42
|
cookies: any;
|
|
43
43
|
removeHeader: (key: string) => this;
|
|
44
44
|
ejs: (viewPath: string, data: {}) => Response | Promise<Response>;
|
|
45
|
+
stream: (callback: () => void) => Response;
|
|
46
|
+
yieldStream: (callback: () => AsyncIterable<any>) => Response;
|
|
45
47
|
}
|
|
46
48
|
export interface CookieOptions {
|
|
47
49
|
maxAge?: number;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { ContextType } from "../types";
|
|
2
|
+
declare function authenticateJwtMiddleware(jwt: any, user_jwt_secret: string): (ctx: ContextType) => Response | undefined;
|
|
3
|
+
declare function authenticateJwtDbMiddleware(jwt: any, User: any, user_jwt_secret: string): (ctx: ContextType) => Promise<Response | undefined>;
|
|
4
|
+
export { authenticateJwtMiddleware, authenticateJwtDbMiddleware };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function F(z,A){if(!z)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(v)=>{try{let f=v.cookies?.accessToken||v.req?.headers?.get("Authorization");if(!f)return v.json({message:"Unauthorized: No token provided"},401);if(f.startsWith("Bearer "))f=f.slice(7);let q=z?.verify(f,A);if(!q)return v.json({message:"Unauthorized: Invalid token"},401);v.set("user",q)}catch(f){return console.error("JWT verification error:",f),v.json({message:"Unauthorized: Invalid token",error:f?.message},401)}}}function G(z,A,v){if(!z)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!A)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(f)=>{try{let q=f.cookies?.accessToken||f.req?.headers?.get("Authorization");if(!q)return f.json({message:"Unauthorized: No token provided"},401);if(q.startsWith("Bearer "))q=q.slice(7);let C=z?.verify(q,v);if(!C)return f.json({message:"Unauthorized: Invalid token"},401);let E=await A.findById(C._id).select("-password -refreshToken");if(!E)return f.json({message:"Unauthorized: User not found"},401);f.set("user",E);return}catch(q){return f.json({message:"Unauthorized: Authentication failed",error:q?.message},401)}}}export{F as authenticateJwtMiddleware,G as authenticateJwtDbMiddleware};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function getMimeType(filePath: string): string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function r(e){switch(e.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"}}export{r as getMimeType};
|
package/dist/utils.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var H=Object.create;var{getPrototypeOf:I,defineProperty:G,getOwnPropertyNames:K}=Object;var L=Object.prototype.hasOwnProperty;var N=(q,C,z)=>{z=q!=null?H(I(q)):{};let v=C||!q||!q.__esModule?G(z,"default",{value:q,enumerable:!0}):z;for(let A of K(q))if(!L.call(v,A))G(v,A,{get:()=>q[A],enumerable:!0});return v};var O=((q)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(q,{get:(C,z)=>(typeof require!=="undefined"?require:C)[z]}):q)(function(q){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+q+'" is not supported')});function R(q){switch(q.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"}}function S(q,C){if(!q)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(z)=>{try{let v=z.cookies?.accessToken||z.req?.headers?.get("Authorization");if(!v)return z.json({message:"Unauthorized: No token provided"},401);if(v.startsWith("Bearer "))v=v.slice(7);let A=q?.verify(v,C);if(!A)return z.json({message:"Unauthorized: Invalid token"},401);z.set("user",A)
|
|
1
|
+
var H=Object.create;var{getPrototypeOf:I,defineProperty:G,getOwnPropertyNames:K}=Object;var L=Object.prototype.hasOwnProperty;var N=(q,C,z)=>{z=q!=null?H(I(q)):{};let v=C||!q||!q.__esModule?G(z,"default",{value:q,enumerable:!0}):z;for(let A of K(q))if(!L.call(v,A))G(v,A,{get:()=>q[A],enumerable:!0});return v};var O=((q)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(q,{get:(C,z)=>(typeof require!=="undefined"?require:C)[z]}):q)(function(q){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+q+'" is not supported')});function R(q){switch(q.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"}}function S(q,C){if(!q)throw new Error("JWT library is not defined, please provide jwt to authenticateJwt Function");return(z)=>{try{let v=z.cookies?.accessToken||z.req?.headers?.get("Authorization");if(!v)return z.json({message:"Unauthorized: No token provided"},401);if(v.startsWith("Bearer "))v=v.slice(7);let A=q?.verify(v,C);if(!A)return z.json({message:"Unauthorized: Invalid token"},401);z.set("user",A)}catch(v){return console.error("JWT verification error:",v),z.json({message:"Unauthorized: Invalid token",error:v?.message},401)}}}function V(q,C,z){if(!q)throw new Error("JWT library is not defined, please provide jwt to authenticateJwtDB Function");if(!C)throw new Error("User model is not defined, please provide UserModel to authenticateJwtDB Function");return async(v)=>{try{let A=v.cookies?.accessToken||v.req?.headers?.get("Authorization");if(!A)return v.json({message:"Unauthorized: No token provided"},401);if(A.startsWith("Bearer "))A=A.slice(7);let E=q?.verify(A,z);if(!E)return v.json({message:"Unauthorized: Invalid token"},401);let F=await C.findById(E._id).select("-password -refreshToken");if(!F)return v.json({message:"Unauthorized: User not found"},401);v.set("user",F);return}catch(A){return v.json({message:"Unauthorized: Authentication failed",error:A?.message},401)}}}export{R as getMimeType,S as authenticateJwtMiddleware,V as authenticateJwtDbMiddleware};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "diesel-core",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.9",
|
|
4
4
|
"description": "Web framework built on Web Standards",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"types": "index.d.ts",
|
|
@@ -49,6 +49,16 @@
|
|
|
49
49
|
"types": "./dist/middlewares/ratelimit/implementation.d.ts",
|
|
50
50
|
"import": "./dist/middlewares/ratelimit/implementation.js",
|
|
51
51
|
"require": "./dist/middlewares/ratelimit/implementation.js"
|
|
52
|
+
},
|
|
53
|
+
"./jwt":{
|
|
54
|
+
"types": "./dist/middlewares/jwt/index.d.ts",
|
|
55
|
+
"import": "./dist/middlewares/jwt/index.js",
|
|
56
|
+
"require": "./dist/middlewares/jwt/index.js"
|
|
57
|
+
},
|
|
58
|
+
"./powered-by":{
|
|
59
|
+
"types": "./dist/middlewares/powered-by/index.d.ts",
|
|
60
|
+
"import": "./dist/middlewares/powered-by/index.js",
|
|
61
|
+
"require": "./dist/middlewares/powered-by/index.js"
|
|
52
62
|
}
|
|
53
63
|
},
|
|
54
64
|
"scripts": {
|