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,140 @@
1
+ export class HttpResponse {
2
+ /**
3
+ * The status code of the response, which defaults to 200 (OK). This
4
+ * property can be modified before calling build() to construct the
5
+ * Response object.
6
+ */
7
+ _status = 200;
8
+ /**
9
+ * The headers of the response, which can be modified before calling build()
10
+ * to construct the Response object.
11
+ */
12
+ _headers = new Headers();
13
+ /**
14
+ * The body of the response, which can be any valid BodyInit type or null.
15
+ */
16
+ _body = null;
17
+ /**
18
+ * Set a header on the response.
19
+ * @param name - The header name.
20
+ * @param value - The header value.
21
+ * @returns The response object.
22
+ */
23
+ header(name, value) {
24
+ this._headers.set(name, value);
25
+ return this;
26
+ }
27
+ /**
28
+ * Remove a header from the response.
29
+ * @param name - The header name.
30
+ * @returns The response object.
31
+ */
32
+ removeHeader(name) {
33
+ this._headers.delete(name);
34
+ return this;
35
+ }
36
+ /**
37
+ * Sets the HTTP status code of the response.
38
+ * @param status - The status code.
39
+ * @returns The response object.
40
+ */
41
+ status(status) {
42
+ this._status = status;
43
+ return this;
44
+ }
45
+ /**
46
+ * Sets the body of the response.
47
+ * @param body - The content to be used as the response body.
48
+ * @returns The response object for method chaining.
49
+ */
50
+ body(body) {
51
+ this._body = body;
52
+ return this;
53
+ }
54
+ /**
55
+ * Sets the content type to "application/json" and serializes the provided data
56
+ * into a JSON string to set as the response body.
57
+ * @param data - The data to be serialized and sent as the response body.
58
+ * @returns The finalized Response object after building.
59
+ */
60
+ json(data) {
61
+ this.header("Content-Type", "application/json");
62
+ this._body = JSON.stringify(data);
63
+ return this.build();
64
+ }
65
+ /**
66
+ * Sets the content type to "text/plain" and assigns the provided text data
67
+ * as the response body.
68
+ * @param data - The text to be sent as the response body.
69
+ * @returns The finalized Response object after building.
70
+ */
71
+ text(data) {
72
+ this.header("Content-Type", "text/plain");
73
+ this._body = data;
74
+ return this.build();
75
+ }
76
+ /**
77
+ * Sets the content type to "text/html" and assigns the provided HTML data
78
+ * as the response body.
79
+ * @param data - The HTML string to be sent as the response body.
80
+ * @returns The finalized Response object after building.
81
+ */
82
+ html(data) {
83
+ this.header("Content-Type", "text/html");
84
+ this._body = data;
85
+ return this.build();
86
+ }
87
+ /**
88
+ * Sets the HTTP status code and removes the "Location" header from the
89
+ * response.
90
+ * @param status - The status code.
91
+ * @returns The response object.
92
+ */
93
+ redirect(url, status = 302) {
94
+ this.status(status);
95
+ this.header("Location", url);
96
+ this._body = null;
97
+ return this;
98
+ }
99
+ /**
100
+ * Convenience method to send a file response using Bun.file.
101
+ * Attempts to serve the specified file and set it as the response body.
102
+ * If the file cannot be found or an error occurs, logs the error and
103
+ * returns a 404 response with "File not found" as the body.
104
+ * @param filePath - The file path to serve.
105
+ * @returns The finalized Response object.
106
+ */
107
+ file(filePath) {
108
+ try {
109
+ const file = Bun.file(filePath);
110
+ this._body = file;
111
+ return this.build();
112
+ }
113
+ catch (error) {
114
+ console.error("Error serving file:", error);
115
+ this.status(404);
116
+ this._body = "File not found";
117
+ return this.build();
118
+ }
119
+ }
120
+ /**
121
+ * Returns a Response directly using the provided body and init settings.
122
+ * This bypasses the mutable state.
123
+ * @param body - The response body.
124
+ * @param init - Optional ResponseInit settings.
125
+ * @returns A new Response object.
126
+ */
127
+ original(body, init) {
128
+ return new Response(body, init);
129
+ }
130
+ /**
131
+ * Builds the final Response object using the current state.
132
+ * @returns The finalized Response object.
133
+ */
134
+ build() {
135
+ return new Response(this._body, {
136
+ status: this._status,
137
+ headers: this._headers,
138
+ });
139
+ }
140
+ }
@@ -0,0 +1,69 @@
1
+ import type { RouteDefinition } from "../types/index.d";
2
+ /**
3
+ * Router class for handling file-based routing.
4
+ * Loads routes from a directory structure and matches requests to the appropriate route handlers.
5
+ * Supports dynamic segments (e.g., [id]) and HTTP method handlers.
6
+ * Routes are sorted to prioritize static routes over dynamic ones to prevent overlapping route issues.
7
+ */
8
+ export declare class Router {
9
+ private routesDir;
10
+ private prefix;
11
+ /** Array of loaded route definitions */
12
+ routes: RouteDefinition[];
13
+ /**
14
+ * Constructor for the Router class.
15
+ * @param routesDir The directory path where route modules are located.
16
+ * @param prefix Optional prefix to prepend to all routes (e.g., "api" becomes "/api/...").
17
+ */
18
+ constructor(routesDir: string, prefix?: string);
19
+ /**
20
+ * Loads route modules from the specified directory and adds them to the routes array.
21
+ * After loading, sorts the routes to prioritize static routes over dynamic ones based on specificity.
22
+ * @returns A promise that resolves when all route modules have been loaded and sorted.
23
+ */
24
+ loadRoutes(): Promise<void>;
25
+ /**
26
+ * Recursively scans the directory for route modules and adds them to the routes array.
27
+ * @param dir The current directory to scan.
28
+ * @param basePath The base path for constructing the route path.
29
+ */
30
+ private scanDirectory;
31
+ /**
32
+ * Converts a file path to a route path by processing dynamic segments,
33
+ * removing certain directory indicators, and applying a prefix if specified.
34
+ * @param filePath The file path to convert into a route path.
35
+ * @returns The converted route path string.
36
+ */
37
+ private convertFilePathToRoute;
38
+ /**
39
+ * Resolves the given request by finding a matching route and extracting dynamic parameters.
40
+ * @param request The request to resolve.
41
+ * @returns An object containing the matched route and parameters, or an empty params object if no match.
42
+ */
43
+ resolve(request: Request): {
44
+ route?: RouteDefinition;
45
+ params: Record<string, string>;
46
+ };
47
+ /**
48
+ * Checks if the request path matches the route path, extracting dynamic parameters if matched.
49
+ * @param requestPath The request path to check.
50
+ * @param routePath The route path to match against.
51
+ * @returns A record of dynamic parameters if matched, otherwise null.
52
+ */
53
+ private matchRoute;
54
+ /**
55
+ * Calculates the specificity of a route path based on the number of static segments.
56
+ * Static segments increase the score, while dynamic segments (:param) do not.
57
+ * @param path The route path to evaluate.
58
+ * @returns The specificity score (higher means more static segments).
59
+ */
60
+ private getRouteSpecificity;
61
+ /**
62
+ * Compares two routes for sorting, prioritizing those with higher specificity (more static segments).
63
+ * If specificity is equal, sorts alphabetically by path.
64
+ * @param a The first route to compare.
65
+ * @param b The second route to compare.
66
+ * @returns Negative if a comes before b, positive if b comes before a, zero if equal.
67
+ */
68
+ private compareRoutes;
69
+ }
@@ -0,0 +1,197 @@
1
+ // Import stuff from node
2
+ import { readdirSync } from "fs";
3
+ import * as path from "path";
4
+ // Import utils
5
+ import { cleanPrefix, normalizePath } from "@/utils/index";
6
+ /**
7
+ * Router class for handling file-based routing.
8
+ * Loads routes from a directory structure and matches requests to the appropriate route handlers.
9
+ * Supports dynamic segments (e.g., [id]) and HTTP method handlers.
10
+ * Routes are sorted to prioritize static routes over dynamic ones to prevent overlapping route issues.
11
+ */
12
+ export class Router {
13
+ routesDir;
14
+ prefix;
15
+ /** Array of loaded route definitions */
16
+ routes = [];
17
+ /**
18
+ * Constructor for the Router class.
19
+ * @param routesDir The directory path where route modules are located.
20
+ * @param prefix Optional prefix to prepend to all routes (e.g., "api" becomes "/api/...").
21
+ */
22
+ constructor(routesDir, prefix = "") {
23
+ this.routesDir = routesDir;
24
+ this.prefix = prefix;
25
+ }
26
+ /**
27
+ * Loads route modules from the specified directory and adds them to the routes array.
28
+ * After loading, sorts the routes to prioritize static routes over dynamic ones based on specificity.
29
+ * @returns A promise that resolves when all route modules have been loaded and sorted.
30
+ */
31
+ async loadRoutes() {
32
+ this.routes = [];
33
+ await this.scanDirectory(this.routesDir);
34
+ // Sort routes to ensure static routes are matched before dynamic ones
35
+ this.routes.sort((a, b) => this.compareRoutes(a, b));
36
+ }
37
+ /**
38
+ * Recursively scans the directory for route modules and adds them to the routes array.
39
+ * @param dir The current directory to scan.
40
+ * @param basePath The base path for constructing the route path.
41
+ */
42
+ async scanDirectory(dir, basePath = "") {
43
+ // Track if a dynamic folder has been found at this directory level
44
+ let dynamicFolderFound = false;
45
+ const entries = readdirSync(dir, { withFileTypes: true });
46
+ for (const entry of entries) {
47
+ const entryPath = path.join(dir, entry.name);
48
+ const relativePath = path.join(basePath, entry.name);
49
+ if (entry.isDirectory()) {
50
+ // Handle dynamic directories (e.g., [id])
51
+ if (entry.name.startsWith("[") && entry.name.endsWith("]")) {
52
+ if (dynamicFolderFound) {
53
+ throw new Error(`Multiple dynamic route folders found in the same directory: '${entry.name}' conflicts with another dynamic folder.`);
54
+ }
55
+ dynamicFolderFound = true;
56
+ }
57
+ await this.scanDirectory(entryPath, relativePath);
58
+ }
59
+ else if (entry.isFile() && entry.name === "route.ts") {
60
+ // Convert file path to route path and load the module
61
+ const routePath = this.convertFilePathToRoute(relativePath);
62
+ const modulePath = path.resolve(entryPath);
63
+ const routeModule = await import(modulePath);
64
+ // Collect HTTP method handlers from the module
65
+ const handlers = {};
66
+ const methods = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD"];
67
+ for (const method of methods) {
68
+ if (typeof routeModule[method] === "function") {
69
+ handlers[method] = routeModule[method];
70
+ }
71
+ }
72
+ // Create route definition
73
+ const routeDef = {
74
+ path: routePath,
75
+ handlers,
76
+ middleware: routeModule.middleware,
77
+ schema: routeModule.schema,
78
+ openapi: routeModule.openapi,
79
+ };
80
+ this.routes.push(routeDef);
81
+ }
82
+ }
83
+ }
84
+ /**
85
+ * Converts a file path to a route path by processing dynamic segments,
86
+ * removing certain directory indicators, and applying a prefix if specified.
87
+ * @param filePath The file path to convert into a route path.
88
+ * @returns The converted route path string.
89
+ */
90
+ convertFilePathToRoute(filePath) {
91
+ // Remove the "route.ts" suffix
92
+ if (filePath.endsWith("route.ts")) {
93
+ filePath = filePath.slice(0, -"route.ts".length);
94
+ }
95
+ // Split path into segments
96
+ const segments = filePath.split(path.sep);
97
+ const resultSegments = [];
98
+ for (let segment of segments) {
99
+ if (!segment)
100
+ continue; // Skip empty segments
101
+ // Skip grouping segments (e.g., (group))
102
+ if (segment.startsWith("(") && segment.endsWith(")"))
103
+ continue;
104
+ // Convert dynamic segments from [param] to :param
105
+ if (segment.startsWith("[") && segment.endsWith("]")) {
106
+ const param = segment.slice(1, -1);
107
+ resultSegments.push(":" + param);
108
+ }
109
+ else {
110
+ resultSegments.push(segment);
111
+ }
112
+ }
113
+ // Construct the route with leading slash
114
+ let route = "/" + resultSegments.join("/");
115
+ // Apply prefix if provided
116
+ if (this.prefix) {
117
+ const cleanPrefixStr = cleanPrefix(this.prefix);
118
+ route = "/" + cleanPrefixStr + route;
119
+ }
120
+ // Remove trailing slash unless it's the root
121
+ if (route !== "/" && route.endsWith("/")) {
122
+ route = route.slice(0, -1);
123
+ }
124
+ return route;
125
+ }
126
+ /**
127
+ * Resolves the given request by finding a matching route and extracting dynamic parameters.
128
+ * @param request The request to resolve.
129
+ * @returns An object containing the matched route and parameters, or an empty params object if no match.
130
+ */
131
+ resolve(request) {
132
+ const url = new URL(request.url);
133
+ const reqPath = normalizePath(url.pathname);
134
+ const method = request.method.toUpperCase();
135
+ for (const route of this.routes) {
136
+ const match = this.matchRoute(reqPath, route.path);
137
+ if (match && route.handlers[method]) {
138
+ return { route, params: match };
139
+ }
140
+ }
141
+ return { params: {} };
142
+ }
143
+ /**
144
+ * Checks if the request path matches the route path, extracting dynamic parameters if matched.
145
+ * @param requestPath The request path to check.
146
+ * @param routePath The route path to match against.
147
+ * @returns A record of dynamic parameters if matched, otherwise null.
148
+ */
149
+ matchRoute(requestPath, routePath) {
150
+ const reqSegments = requestPath.split("/").filter(Boolean);
151
+ const routeSegments = routePath.split("/").filter(Boolean);
152
+ if (reqSegments.length !== routeSegments.length) {
153
+ return null;
154
+ }
155
+ const params = {};
156
+ for (let i = 0; i < reqSegments.length; i++) {
157
+ const rSegment = routeSegments[i];
158
+ const reqSegment = reqSegments[i];
159
+ if (rSegment.startsWith(":")) {
160
+ const paramName = rSegment.slice(1);
161
+ params[paramName] = reqSegment;
162
+ }
163
+ else if (rSegment !== reqSegment) {
164
+ return null;
165
+ }
166
+ }
167
+ return params;
168
+ }
169
+ /**
170
+ * Calculates the specificity of a route path based on the number of static segments.
171
+ * Static segments increase the score, while dynamic segments (:param) do not.
172
+ * @param path The route path to evaluate.
173
+ * @returns The specificity score (higher means more static segments).
174
+ */
175
+ getRouteSpecificity(path) {
176
+ const segments = path.split("/").filter(Boolean);
177
+ return segments.reduce((score, segment) => {
178
+ return segment.startsWith(":") ? score : score + 1;
179
+ }, 0);
180
+ }
181
+ /**
182
+ * Compares two routes for sorting, prioritizing those with higher specificity (more static segments).
183
+ * If specificity is equal, sorts alphabetically by path.
184
+ * @param a The first route to compare.
185
+ * @param b The second route to compare.
186
+ * @returns Negative if a comes before b, positive if b comes before a, zero if equal.
187
+ */
188
+ compareRoutes(a, b) {
189
+ const aSpecificity = this.getRouteSpecificity(a.path);
190
+ const bSpecificity = this.getRouteSpecificity(b.path);
191
+ if (aSpecificity > bSpecificity)
192
+ return -1;
193
+ if (aSpecificity < bSpecificity)
194
+ return 1;
195
+ return a.path.localeCompare(b.path);
196
+ }
197
+ }
@@ -0,0 +1,24 @@
1
+ import type { ServerOptions, RequestHandler } from "../types/index.d";
2
+ export declare class Server {
3
+ private options;
4
+ private server;
5
+ /**
6
+ * Initializes a new instance of the Server class with the given options.
7
+ * @param options - Configuration options for the server.
8
+ */
9
+ constructor(options: ServerOptions);
10
+ /**
11
+ * Starts the server with the given port, handler, and callback.
12
+ * @param port - The port to listen on.
13
+ * @param handler - The request handler function.
14
+ * @param cb - The callback function to be called when the server starts.
15
+ */
16
+ start(port: number, handler: RequestHandler, cb?: () => void): void;
17
+ /**
18
+ * Stops the server.
19
+ * If the server is currently running, this method will stop the server and
20
+ * log a message to the console indicating that the server has been stopped.
21
+ * If the server is not running, this method does nothing.
22
+ */
23
+ stop(): void;
24
+ }
@@ -0,0 +1,60 @@
1
+ // Import stuff from core
2
+ import { HttpRequest } from "./request";
3
+ import { HttpResponse } from "./response";
4
+ // Import stuff from utils
5
+ import { errorResponse } from "@/utils/error";
6
+ export class Server {
7
+ options;
8
+ server = null;
9
+ /**
10
+ * Initializes a new instance of the Server class with the given options.
11
+ * @param options - Configuration options for the server.
12
+ */
13
+ constructor(options) {
14
+ this.options = options;
15
+ }
16
+ /**
17
+ * Starts the server with the given port, handler, and callback.
18
+ * @param port - The port to listen on.
19
+ * @param handler - The request handler function.
20
+ * @param cb - The callback function to be called when the server starts.
21
+ */
22
+ start(port, handler, cb) {
23
+ // Start Bun's native server using Bun.serve
24
+ this.server = Bun.serve({
25
+ port,
26
+ fetch: async (request) => {
27
+ try {
28
+ // Wrap the native Request with HttpRequest to get a BurgerRequest
29
+ const burgerReq = new HttpRequest(request);
30
+ // Wrap the native Response with HttpResponse to get a BurgerResponse
31
+ const burgerRes = new HttpResponse();
32
+ // Invoke and return the handler with the wrapped requests and responses
33
+ return await handler(burgerReq, burgerRes);
34
+ }
35
+ catch (error) {
36
+ // Return a custom error response
37
+ return errorResponse(error, request, this.options.debug ?? false);
38
+ }
39
+ },
40
+ });
41
+ if (cb) {
42
+ cb();
43
+ }
44
+ else {
45
+ console.log(`✔ Server started on port: ${port}`);
46
+ }
47
+ }
48
+ /**
49
+ * Stops the server.
50
+ * If the server is currently running, this method will stop the server and
51
+ * log a message to the console indicating that the server has been stopped.
52
+ * If the server is not running, this method does nothing.
53
+ */
54
+ stop() {
55
+ if (this.server) {
56
+ this.server.stop();
57
+ console.log("Server stopped.");
58
+ }
59
+ }
60
+ }
@@ -0,0 +1 @@
1
+ export declare const swaggerHtml = "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <title>API Documentation</title>\n <link rel=\"stylesheet\" href=\"https://unpkg.com/swagger-ui-dist/swagger-ui.css\" />\n <style>\n body {\n margin: 0;\n padding: 0;\n }\n </style>\n </head>\n <body>\n <div id=\"swagger-ui\"></div>\n <script src=\"https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js\"></script>\n <script>\n window.onload = function() {\n SwaggerUIBundle({\n url: '/openapi.json',\n dom_id: '#swagger-ui',\n presets: [\n SwaggerUIBundle.presets.apis,\n SwaggerUIBundle.SwaggerUIStandalonePreset\n ],\n layout: \"BaseLayout\",\n docExpansion: \"none\",\n filter: true,\n });\n };\n </script>\n </body>\n</html>";
@@ -0,0 +1,33 @@
1
+ export const swaggerHtml = `<!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <title>API Documentation</title>
6
+ <link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist/swagger-ui.css" />
7
+ <style>
8
+ body {
9
+ margin: 0;
10
+ padding: 0;
11
+ }
12
+ </style>
13
+ </head>
14
+ <body>
15
+ <div id="swagger-ui"></div>
16
+ <script src="https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js"></script>
17
+ <script>
18
+ window.onload = function() {
19
+ SwaggerUIBundle({
20
+ url: '/openapi.json',
21
+ dom_id: '#swagger-ui',
22
+ presets: [
23
+ SwaggerUIBundle.presets.apis,
24
+ SwaggerUIBundle.SwaggerUIStandalonePreset
25
+ ],
26
+ layout: "BaseLayout",
27
+ docExpansion: "none",
28
+ filter: true,
29
+ });
30
+ };
31
+ </script>
32
+ </body>
33
+ </html>`;
@@ -0,0 +1,31 @@
1
+ import type { ServerOptions, Middleware } from "./types/index.d";
2
+ export declare class Burger {
3
+ private options;
4
+ private server;
5
+ private router?;
6
+ private globalMiddleware;
7
+ /**
8
+ * Constructor for the Burger class.
9
+ * @param options - The options for the server and router.
10
+ * The options object should contain the following properties:
11
+ * - port: The port number to listen on.
12
+ * - apiDir: The directory path to load API routes from.
13
+ * - pageDir: The directory path to load page routes from.
14
+ * - middleware: An array of global middleware functions.
15
+ */
16
+ constructor(options: ServerOptions);
17
+ /**
18
+ * Adds a global middleware function to the list of middlewares.
19
+ * @param mw - The middleware function to add.
20
+ */
21
+ addGlobalMiddleware(mw: Middleware): void;
22
+ /**
23
+ * Starts the server and begins listening for incoming requests.
24
+ * @param port - The port number to listen on. Defaults to `4000`.
25
+ * @param cb - An optional cb function to be executed when the server is listening.
26
+ * @returns A Promise that resolves when the server has started listening.
27
+ */
28
+ serve(port?: number, cb?: () => void): Promise<void>;
29
+ }
30
+ export { setDir } from "./utils/index";
31
+ export type { ServerOptions, RequestHandler, BurgerRequest, BurgerResponse, Middleware, } from "./types/index.d";