burger-api 0.0.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,137 @@
1
+ // Import stuff from core
2
+ import { Server } from "./core/server";
3
+ import { Router } from "./core/router";
4
+ import { HttpRequest } from "./core/request";
5
+ import { HttpResponse } from "./core/response";
6
+ import { generateOpenAPIDocument } from "./core/openapi";
7
+ import { swaggerHtml } from "./core/swagger-ui";
8
+ // Import middleware
9
+ import { createValidationMiddleware } from "./middleware/validator";
10
+ export class Burger {
11
+ options;
12
+ server;
13
+ router;
14
+ globalMiddleware = [];
15
+ /**
16
+ * Constructor for the Burger class.
17
+ * @param options - The options for the server and router.
18
+ * The options object should contain the following properties:
19
+ * - port: The port number to listen on.
20
+ * - apiDir: The directory path to load API routes from.
21
+ * - pageDir: The directory path to load page routes from.
22
+ * - middleware: An array of global middleware functions.
23
+ */
24
+ constructor(options) {
25
+ this.options = options;
26
+ this.server = new Server(options);
27
+ // Initialize API router
28
+ if (options.apiDir) {
29
+ this.router = new Router(options.apiDir, "api");
30
+ }
31
+ // Add global middleware
32
+ if (options.globalMiddleware) {
33
+ options.globalMiddleware.forEach((mw) => this.addGlobalMiddleware(mw));
34
+ }
35
+ }
36
+ /**
37
+ * Adds a global middleware function to the list of middlewares.
38
+ * @param mw - The middleware function to add.
39
+ */
40
+ addGlobalMiddleware(mw) {
41
+ this.globalMiddleware.push(mw);
42
+ }
43
+ /**
44
+ * Starts the server and begins listening for incoming requests.
45
+ * @param port - The port number to listen on. Defaults to `4000`.
46
+ * @param cb - An optional cb function to be executed when the server is listening.
47
+ * @returns A Promise that resolves when the server has started listening.
48
+ */
49
+ async serve(port = 4000, cb) {
50
+ // File-based routing mode
51
+ if (this.router) {
52
+ await this.router.loadRoutes();
53
+ this.server.start(port, async (req) => {
54
+ // Wrap the native request with helper methods
55
+ const request = new HttpRequest(req);
56
+ // Create a new instance of BurgerResponse for the handler
57
+ const response = new HttpResponse();
58
+ // Create URL object
59
+ const url = new URL(request.url);
60
+ // Check if the request is for /openapi.json
61
+ if (url.pathname === "/openapi.json") {
62
+ if (this.router) {
63
+ // Generate OpenAPI document
64
+ const doc = generateOpenAPIDocument(this.router, this.options);
65
+ // Return it as JSON
66
+ return response.json(doc);
67
+ }
68
+ else {
69
+ // Return an error if router is not available
70
+ return response
71
+ .status(500)
72
+ .json({ error: "Router not available" });
73
+ }
74
+ }
75
+ // Serve the Swagger UI at /docs
76
+ if (url.pathname === "/docs") {
77
+ return response.html(swaggerHtml);
78
+ }
79
+ // Get the route and params for the current request
80
+ const { route, params } = this.router.resolve(req);
81
+ if (!route) {
82
+ // Return a 404 if no route is found
83
+ return response.status(404).json({ error: "Route not found" });
84
+ }
85
+ // Add params to the request
86
+ request.params = params;
87
+ // Get the handler for the current HTTP method
88
+ const method = req.method.toUpperCase();
89
+ const handler = route.handlers[method];
90
+ if (!handler) {
91
+ // Return a 405 if no handler is found
92
+ return response.status(405).json({ error: "Method Not Allowed" });
93
+ }
94
+ /**
95
+ * Build the middleware composition chain.
96
+ * 1. Compose the Route-Specific Chain
97
+ * 2. Insert Validation Middleware (if a schema exists)
98
+ * 3. Insert Global Middleware
99
+ * 4. Execute the handler
100
+ */
101
+ // 1. Compose the Route-Specific Chain
102
+ let routeChain = async () => handler(request, response);
103
+ if (route.middleware && route.middleware.length > 0) {
104
+ // Wrap route-specific middleware (in reverse order to preserve order of execution)
105
+ for (const mw of route.middleware.slice().reverse()) {
106
+ const next = routeChain;
107
+ routeChain = async () => mw(request, response, next);
108
+ }
109
+ }
110
+ // 2. Insert Validation Middleware (if a schema exists)
111
+ let composedChain = routeChain;
112
+ if (route.schema) {
113
+ const validationMw = createValidationMiddleware(route.schema);
114
+ composedChain = async () => validationMw(request, response, routeChain);
115
+ }
116
+ // 3. Wrap Global Middleware (in reverse order so that the first-added runs first)
117
+ let finalHandler = composedChain;
118
+ if (this.globalMiddleware.length > 0) {
119
+ for (const mw of this.globalMiddleware.slice().reverse()) {
120
+ const next = finalHandler;
121
+ finalHandler = async () => mw(request, response, next);
122
+ }
123
+ }
124
+ // Execute the full chain
125
+ return await finalHandler();
126
+ }, cb);
127
+ }
128
+ else {
129
+ // Fallback to default handler if no router is provided
130
+ this.server.start(port, async (_) => new Response("Hello from burger-api!", {
131
+ headers: { "Content-Type": "text/plain" },
132
+ }), cb);
133
+ }
134
+ }
135
+ }
136
+ // Export utils
137
+ export { setDir } from "./utils/index";
@@ -0,0 +1,11 @@
1
+ import type { Middleware, RouteSchema } from "../types/index";
2
+ /**
3
+ * Creates a middleware function that validates request data according to the
4
+ * given schema for the current HTTP method.
5
+ *
6
+ * @param schema - The route schema to validate against.
7
+ * @returns A middleware function that validates request data and attaches the
8
+ * validated data to the request if successful, or returns a 400 response with
9
+ * error details if validation fails.
10
+ */
11
+ export declare function createValidationMiddleware(schema: RouteSchema): Middleware;
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Creates a middleware function that validates request data according to the
3
+ * given schema for the current HTTP method.
4
+ *
5
+ * @param schema - The route schema to validate against.
6
+ * @returns A middleware function that validates request data and attaches the
7
+ * validated data to the request if successful, or returns a 400 response with
8
+ * error details if validation fails.
9
+ */
10
+ export function createValidationMiddleware(schema) {
11
+ return async (req, res, next) => {
12
+ // If the request has been validated, continue.
13
+ if (req.validated) {
14
+ return await next();
15
+ }
16
+ // Determine the HTTP method (in lowercase) to match the schema.
17
+ const method = req.method.toLowerCase();
18
+ // Get the schema for the current method.
19
+ const methodSchema = schema[method];
20
+ // If there's no schema for this method, continue.
21
+ if (!methodSchema) {
22
+ return await next();
23
+ }
24
+ /**
25
+ * Array to collect validation errors.
26
+ * Each error contains a `field` indicating the part of the request that failed validation,
27
+ * and an `error` providing details about the validation failure.
28
+ */
29
+ const errors = [];
30
+ /**
31
+ * Object to store validated request data. This will be attached to the
32
+ * request object if validation is successful. The object will contain
33
+ * validated data for the following fields:
34
+ *
35
+ * - `params`: Validated URL parameters.
36
+ * - `query`: Validated query parameters.
37
+ * - `body`: Validated request body (if JSON).
38
+ */
39
+ const validated = {};
40
+ // Validate URL parameters (if available and schema provided).
41
+ // (Assume that middleware upstream attaches route params to req.params.)
42
+ if (methodSchema.params && req.params) {
43
+ try {
44
+ validated.params = methodSchema.params.parse(req.params);
45
+ }
46
+ catch (e) {
47
+ errors.push({ field: "params", error: e.errors });
48
+ }
49
+ }
50
+ // Validate query parameters.
51
+ if (methodSchema.query) {
52
+ try {
53
+ validated.query = methodSchema.query.parse(Object.fromEntries(req.query.entries()));
54
+ }
55
+ catch (e) {
56
+ errors.push({ field: "query", error: e.errors });
57
+ }
58
+ }
59
+ // Validate request body.
60
+ if (methodSchema.body) {
61
+ // Check the Content-Type header.
62
+ const contentType = req.headers.get("Content-Type") || "";
63
+ if (!contentType.includes("application/json")) {
64
+ // If not JSON, push an error indicating the expected content type.
65
+ errors.push({
66
+ field: "body",
67
+ error: "Invalid Content-Type. Expected 'application/json'.",
68
+ });
69
+ }
70
+ else {
71
+ try {
72
+ // Attempt to parse the JSON body.
73
+ const bodyData = await req.json();
74
+ validated.body = methodSchema.body.parse(bodyData);
75
+ }
76
+ catch (e) {
77
+ errors.push({ field: "body", error: e.errors || e.message });
78
+ }
79
+ }
80
+ }
81
+ if (errors.length > 0) {
82
+ // If validation fails, return a 400 response with error details.
83
+ return res.status(400).json({ errors });
84
+ }
85
+ // Attach validated data to the request.
86
+ req.validated = validated;
87
+ // Continue to the next middleware or handler.
88
+ return await next();
89
+ };
90
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Generates an HTTP error response based on the request's "Accept" header.
3
+ *
4
+ * If the "Accept" header includes "text/html" and debugging is enabled, it returns
5
+ * an HTML response with the error message and stack trace.
6
+ *
7
+ * If the "Accept" header includes "application/json" or debugging is enabled, it
8
+ * returns a JSON response with the error message and optionally the stack trace.
9
+ *
10
+ * Otherwise, it returns a plain text response indicating an internal server error.
11
+ *
12
+ * @param error - The error object or message to include in the response.
13
+ * @param req - The incoming HTTP request object.
14
+ * @param debug - A boolean indicating whether debugging information should be included.
15
+ * @returns A Response object with the appropriate error details and status code.
16
+ */
17
+ export declare function errorResponse(error: any, req: Request, debug: boolean): Response;
@@ -0,0 +1,209 @@
1
+ import { normalizePath } from "./index";
2
+ /**
3
+ * Generates an HTTP error response based on the request's "Accept" header.
4
+ *
5
+ * If the "Accept" header includes "text/html" and debugging is enabled, it returns
6
+ * an HTML response with the error message and stack trace.
7
+ *
8
+ * If the "Accept" header includes "application/json" or debugging is enabled, it
9
+ * returns a JSON response with the error message and optionally the stack trace.
10
+ *
11
+ * Otherwise, it returns a plain text response indicating an internal server error.
12
+ *
13
+ * @param error - The error object or message to include in the response.
14
+ * @param req - The incoming HTTP request object.
15
+ * @param debug - A boolean indicating whether debugging information should be included.
16
+ * @returns A Response object with the appropriate error details and status code.
17
+ */
18
+ export function errorResponse(error, req, debug) {
19
+ // Extract request details
20
+ const method = req.method;
21
+ const url = req.url;
22
+ const logPrefix = `[${method} ${url}]`;
23
+ // Log detailed error context
24
+ console.error(`${logPrefix} Error:`, error);
25
+ const acceptHeader = req.headers.get("accept") || "";
26
+ if (acceptHeader.includes("text/html") && debug) {
27
+ const body = `
28
+ <!DOCTYPE html>
29
+ <html lang="en">
30
+ <head>
31
+ <meta charset="UTF-8">
32
+ <title>Error Occurred - BurgerAPI</title>
33
+ <style>
34
+ body {
35
+ margin: 0;
36
+ padding: 0;
37
+ background-color: #f4f4f4;
38
+ font-family: 'Nunito', sans-serif;
39
+ color: #333;
40
+ }
41
+
42
+ .whoops-container {
43
+ width: 80%;
44
+ margin: 5% auto;
45
+ background: #fff;
46
+ border-radius: 8px;
47
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
48
+ overflow: hidden;
49
+ }
50
+
51
+ .whoops-header {
52
+ background-color: #e74c3c;
53
+ color: white;
54
+ padding: 20px;
55
+ display: flex;
56
+ align-items: center;
57
+ justify-content: space-between;
58
+ }
59
+
60
+ .whoops-header .title-container {
61
+ display: flex;
62
+ align-items: center;
63
+ }
64
+
65
+ .whoops-header .title {
66
+ font-size: 1.5em;
67
+ margin-left: 10px;
68
+ }
69
+
70
+ .whoops-header .debug-mode {
71
+ font-weight: 600;
72
+ display: flex;
73
+ align-items: center;
74
+ padding: 10px;
75
+ background-color: #ffffff;
76
+ color: #e74c3c;
77
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
78
+ border-radius: 8px;
79
+ }
80
+
81
+ .whoops-header .debug-mode .fa-check-circle {
82
+ color: #28a745; /* Green color for the check icon */
83
+ margin-right: 5px; /* Add some spacing between icon and text */
84
+ font-size: 1.2em; /* slightly larger icon */
85
+ }
86
+
87
+ .whoops-content {
88
+ padding: 2em;
89
+ }
90
+
91
+ .tag {
92
+ font-weight: 600;
93
+ color: #4a5568;
94
+ background-color: #edf2f7;
95
+ padding: 8px 15px;
96
+ border-radius: 6px;
97
+ display: inline-block;
98
+ font-size: 14px;
99
+ }
100
+
101
+ .error-message {
102
+ font-size: 1.25em;
103
+ line-height: 1.6;
104
+ margin-bottom: 1.5em;
105
+ color: #2d3748;
106
+ }
107
+
108
+ h2 {
109
+ color: #e3342f;
110
+ font-size: 1.5em;
111
+ margin-bottom: 0.8em;
112
+ border-bottom: 1px solid #edf2f7;
113
+ padding-bottom: 0.5em;
114
+ }
115
+
116
+ pre {
117
+ background: #f9fafc;
118
+ border-left: 4px solid #e3342f;
119
+ padding: 1.5em;
120
+ border-radius: 4px;
121
+ font-family: "Source Code Pro", Menlo, Monaco, Consolas, "Courier New", monospace;
122
+ font-size: 1em;
123
+ line-height: 1.6;
124
+ overflow-x: auto;
125
+ color: #4a5568;
126
+ }
127
+
128
+ .footer {
129
+ text-align: center;
130
+ padding-top:25px;
131
+ font-size: 0.9em;
132
+ color: #718096;
133
+ border-top: 1px solid #edf2f7;
134
+ }
135
+
136
+ .error-icon {
137
+ font-size: 2em;
138
+ }
139
+
140
+ .request-info{
141
+ display: flex;
142
+ justify-content: space-between;
143
+ align-items: center;
144
+ }
145
+
146
+ /* Font Import (Google Fonts) */
147
+ @import url('https://fonts.googleapis.com/css2?family=Source+Code+Pro&display=swap');
148
+ @import url('https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap');
149
+ </style>
150
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
151
+ </head>
152
+ <body>
153
+ <div class="whoops-container">
154
+ <div class="whoops-header">
155
+ <div class="title-container">
156
+ <i class="fas fa-exclamation-triangle error-icon"></i>
157
+ <div class="title">Whoops! Something went wrong</div>
158
+ </div>
159
+ <div class="debug-mode">
160
+ <i class="fas fa-check-circle"></i> Debug Mode Enabled
161
+ </div>
162
+ </div>
163
+ <div class="whoops-content">
164
+ <div class="request-info">
165
+ <div><strong>Request:</strong> ${method} ${url}</div>
166
+ <div class="tag">
167
+ ${error.stack?.split("\n")[0].split(":")[0]}
168
+ </div>
169
+ </div>
170
+ <p class="error-message">
171
+ ${error.message}
172
+ </p>
173
+ <h2>Stack Trace</h2>
174
+ <pre>${error.stack || "No stack trace available"}</pre>
175
+ <div class="footer">
176
+ “It’s not a bug, it’s an undocumented feature.” — Anonymous
177
+ </div>
178
+ </div>
179
+ </div>
180
+ </body>
181
+ </html>`;
182
+ // Return the html response
183
+ return new Response(body, {
184
+ status: 500,
185
+ headers: { "Content-Type": "text/html" },
186
+ });
187
+ }
188
+ else if (debug) {
189
+ // Log detailed error context
190
+ console.error(`${logPrefix} Error:`, error);
191
+ // Create a JSON response
192
+ const body = JSON.stringify({
193
+ request: `${method} ${url}`,
194
+ error: error instanceof Error ? error.message : "Unknown error",
195
+ stack: error instanceof Error ? normalizePath(error.stack || "") : "",
196
+ });
197
+ // Return the JSON response
198
+ return new Response(body, {
199
+ status: 500,
200
+ headers: { "Content-Type": "application/json" },
201
+ });
202
+ }
203
+ else {
204
+ // Log detailed error context
205
+ console.error(`${logPrefix} Error:`, error);
206
+ // Return a plain text response
207
+ return new Response("Internal Server Error", { status: 500 });
208
+ }
209
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Resolves the given path to the specified directory.
3
+ * @param directory the directory to resolve to
4
+ * @param path the path to resolve
5
+ * @returns the resolved path
6
+ */
7
+ export declare function setDir(directory: string, path: string): string;
8
+ /**
9
+ * Removes leading and trailing slashes from the given prefix.
10
+ * @param prefix the prefix to clean
11
+ * @returns the cleaned prefix
12
+ */
13
+ export declare function cleanPrefix(prefix: string): string;
14
+ /**
15
+ * Normalizes a file path by replacing multiple slashes with a single slash
16
+ * and removing any trailing slash, unless the path is the root.
17
+ * @param path The file path to normalize.
18
+ * @returns The normalized file path.
19
+ */
20
+ export declare function normalizePath(path: string): string;
@@ -0,0 +1,41 @@
1
+ import { resolve } from "path";
2
+ /**
3
+ * Resolves the given path to the specified directory.
4
+ * @param directory the directory to resolve to
5
+ * @param path the path to resolve
6
+ * @returns the resolved path
7
+ */
8
+ export function setDir(directory, path) {
9
+ return resolve(directory, path);
10
+ }
11
+ /**
12
+ * Removes leading and trailing slashes from the given prefix.
13
+ * @param prefix the prefix to clean
14
+ * @returns the cleaned prefix
15
+ */
16
+ export function cleanPrefix(prefix) {
17
+ // Remove all slashes from the beginning
18
+ while (prefix.startsWith("/")) {
19
+ prefix = prefix.slice(1);
20
+ }
21
+ // Remove all slashes from the end
22
+ while (prefix.endsWith("/")) {
23
+ prefix = prefix.slice(0, -1);
24
+ }
25
+ return prefix;
26
+ }
27
+ /**
28
+ * Normalizes a file path by replacing multiple slashes with a single slash
29
+ * and removing any trailing slash, unless the path is the root.
30
+ * @param path The file path to normalize.
31
+ * @returns The normalized file path.
32
+ */
33
+ export function normalizePath(path) {
34
+ // Replace multiple slashes with a single slash
35
+ let normalized = path.replace(/\/+/g, "/");
36
+ // Remove trailing slash if it's not the root
37
+ if (normalized.length > 1 && normalized.endsWith("/")) {
38
+ normalized = normalized.slice(0, -1);
39
+ }
40
+ return normalized;
41
+ }
package/package.json ADDED
@@ -0,0 +1,75 @@
1
+ {
2
+ "name": "burger-api",
3
+ "version": "0.0.28",
4
+ "author": "Isfhan Ahmed",
5
+ "type": "module",
6
+ "module": "dist/index.js",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "scripts": {
11
+ "typecheck": "tsc --noEmit",
12
+ "build": "tsc --project tsconfig.build.json",
13
+ "test": "bun test",
14
+ "dev": "bun run examples/native-server/index.ts"
15
+ },
16
+ "keywords": [
17
+ "burger-api",
18
+ "burger-api-framework",
19
+ "bun",
20
+ "bunjs",
21
+ "bun-framework",
22
+ "fast-backend",
23
+ "javascript-backend",
24
+ "high-performance",
25
+ "esm",
26
+ "typescript",
27
+ "file-based routing",
28
+ "middleware",
29
+ "zod-validation",
30
+ "openapi",
31
+ "swagger-ui",
32
+ "declarative-routing",
33
+ "api-framework",
34
+ "modern-backend",
35
+ "backend-framework",
36
+ "server",
37
+ "bun-native",
38
+ "js-backend",
39
+ "fast-api",
40
+ "scalable-backend",
41
+ "backend-development",
42
+ "modern-api",
43
+ "api-development",
44
+ "backend-engine",
45
+ "efficient",
46
+ "minimalist-backend",
47
+ "bun-powered",
48
+ "open-source",
49
+ "typescript-backend",
50
+ "performance",
51
+ "rapid-development",
52
+ "web-framework",
53
+ "api-server",
54
+ "dynamic-routing",
55
+ "backend-routing",
56
+ "extensible",
57
+ "modular",
58
+ "declarative-api",
59
+ "lightweight",
60
+ "contemporary-backend",
61
+ "fast-javascript",
62
+ "bun-js-framework",
63
+ "bun-backend"
64
+ ],
65
+ "dependencies": {
66
+ "zod": "^3.24.2",
67
+ "zod-to-json-schema": "^3.24.2"
68
+ },
69
+ "devDependencies": {
70
+ "@types/bun": "latest"
71
+ },
72
+ "peerDependencies": {
73
+ "typescript": "^5.0.0"
74
+ }
75
+ }