burger-api 0.4.1 → 0.5.1

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.
@@ -1,47 +1,25 @@
1
- // Import stuff from node
2
1
  import { readdirSync } from 'fs';
3
2
  import * as path from 'path';
4
- // Import utils
5
- import { cleanPrefix, normalizePath, compareRoutes, ROUTE_CONSTANTS, } from '../utils/index.js';
6
- /**
7
- * PageRouter class for handling file-based page routing.
8
- * Loads pages from a directory structure and matches requests to the appropriate page handlers.
9
- * Supports dynamic segments (e.g., [id]) and uses default exports as page handlers.
10
- */
3
+ import { cleanPrefix, normalizePath, compareRoutes, ROUTE_CONSTANTS, } from '../utils/index';
11
4
  export class PageRouter {
12
5
  pagesDir;
13
6
  prefix;
14
- /** Array of loaded page definitions */
15
7
  pages = [];
16
- /**
17
- * Constructor for the PageRouter class.
18
- * @param pagesDir The directory path where page modules are located.
19
- * @param prefix Optional prefix to prepend to all routes (e.g., "pages" becomes "/pages/...").
20
- */
21
8
  constructor(pagesDir, prefix = '') {
22
9
  this.pagesDir = pagesDir;
23
10
  this.prefix = prefix;
24
11
  if (!pagesDir) {
25
12
  throw new Error('Pages directory path must be provided');
26
13
  }
27
- // Normalize the pagesDir path
28
14
  this.pagesDir = path.normalize(pagesDir);
29
- // Normalize the prefix if provided
30
15
  if (prefix) {
31
16
  this.prefix = cleanPrefix(prefix);
32
17
  }
33
18
  }
34
- /**
35
- * Loads page modules from the specified directory and adds them to the pages array.
36
- * After loading, sorts the pages to prioritize static routes over dynamic ones based on specificity.
37
- * @returns A promise that resolves when all page modules have been loaded and sorted.
38
- */
39
19
  async loadPages() {
40
- // Clear the pages array
41
20
  this.pages = [];
42
21
  try {
43
22
  await this.scanDirectory(this.pagesDir);
44
- // Sort pages to ensure static routes are matched before dynamic ones
45
23
  this.pages.sort((a, b) => compareRoutes(a, b));
46
24
  }
47
25
  catch (error) {
@@ -49,13 +27,7 @@ export class PageRouter {
49
27
  throw new Error(`Failed to load pages: ${error instanceof Error ? error.message : String(error)}`);
50
28
  }
51
29
  }
52
- /**
53
- * Recursively scans the directory for page modules and adds them to the pages array.
54
- * @param dir The current directory to scan.
55
- * @param basePath The base path for constructing the route path.
56
- */
57
30
  async scanDirectory(dir, basePath = '') {
58
- // Track if a dynamic folder has been found at this directory level
59
31
  let dynamicFolderFound = false;
60
32
  try {
61
33
  const entries = readdirSync(dir, { withFileTypes: true });
@@ -63,7 +35,6 @@ export class PageRouter {
63
35
  const entryPath = path.join(dir, entry.name);
64
36
  const relativePath = path.join(basePath, entry.name);
65
37
  if (entry.isDirectory()) {
66
- // Handle dynamic directories (e.g., [id])
67
38
  if (entry.name.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
68
39
  entry.name.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END)) {
69
40
  if (dynamicFolderFound) {
@@ -75,33 +46,25 @@ export class PageRouter {
75
46
  }
76
47
  else if (entry.isFile() &&
77
48
  ROUTE_CONSTANTS.SUPPORTED_PAGE_EXTENSIONS.some((ext) => entry.name.endsWith(ext))) {
78
- // Convert file path to route path and load the module
79
49
  const routePath = this.convertFilePathToRoute(relativePath);
80
- // Clean the route path
81
50
  const cleanedRoutePath = this.cleanRoutePath(routePath);
82
- // Get the module path
83
51
  const modulePath = path.resolve(entryPath);
84
52
  try {
85
- // Import the module
86
53
  const pageModule = await import(modulePath);
87
- // Get the default export as the page handler
88
54
  if (entry.name.endsWith('.tsx') &&
89
55
  typeof pageModule.default !== 'function') {
90
56
  throw new Error(`Page at ${entryPath} must export a default function as its handler.`);
91
57
  }
92
- // Create page definition
93
58
  const pageDefWithSlash = {
94
59
  path: cleanedRoutePath + '/',
95
60
  handler: pageModule.default,
96
61
  middleware: pageModule.middleware,
97
62
  };
98
- // Create page definition
99
63
  const pageDef = {
100
64
  path: cleanedRoutePath,
101
65
  handler: pageModule.default,
102
66
  middleware: pageModule.middleware,
103
67
  };
104
- // Add the page definition to the pages array
105
68
  this.pages.push(pageDefWithSlash, pageDef);
106
69
  }
107
70
  catch (importError) {
@@ -115,24 +78,15 @@ export class PageRouter {
115
78
  throw error;
116
79
  }
117
80
  }
118
- /**
119
- * Converts a file path to a route path by processing dynamic segments,
120
- * removing certain directory indicators, and applying a prefix if specified.
121
- * @param filePath The file path to convert into a route path.
122
- * @returns The converted route path string (before extension cleaning).
123
- */
124
81
  convertFilePathToRoute(filePath) {
125
- // Split path into segments
126
82
  const segments = filePath.split(path.sep);
127
83
  const resultSegments = [];
128
84
  for (let segment of segments) {
129
85
  if (!segment)
130
- continue; // Skip empty segments
131
- // Skip grouping segments (e.g., (group))
86
+ continue;
132
87
  if (segment.startsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_START) &&
133
88
  segment.endsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_END))
134
89
  continue;
135
- // Convert dynamic segments from [param] to :param
136
90
  if (segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
137
91
  segment.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END)) {
138
92
  const param = segment.slice(1, -1);
@@ -142,37 +96,24 @@ export class PageRouter {
142
96
  resultSegments.push(segment);
143
97
  }
144
98
  }
145
- // Construct the route with leading slash
146
99
  let route = '/' + resultSegments.join('/');
147
- // Apply prefix if provided
148
100
  if (this.prefix) {
149
101
  const cleanPrefixStr = cleanPrefix(this.prefix);
150
102
  route = '/' + cleanPrefixStr + route;
151
103
  }
152
- // Remove trailing slash unless it's the root
153
104
  if (route !== '/' && route.endsWith('/')) {
154
105
  route = route.slice(0, -1);
155
106
  }
156
107
  return route;
157
108
  }
158
- /**
159
- * Cleans a route path by handling index files and removing extensions.
160
- * @param routePath The route path to clean
161
- * @returns The cleaned route path
162
- */
163
109
  cleanRoutePath(routePath) {
164
- // Break the route path into segments
165
110
  const pathSegments = routePath.split('/');
166
- // Get the last segment
167
111
  if (pathSegments.length > 0) {
168
112
  const lastSegment = pathSegments[pathSegments.length - 1];
169
- // Check if the last segment is an index file
170
113
  if (ROUTE_CONSTANTS.PAGE_INDEX_FILES.includes(lastSegment)) {
171
- // Remove the last segment for index files
172
114
  pathSegments.pop();
173
115
  }
174
116
  else {
175
- // Remove file extension for non-index files
176
117
  const extensionIndex = lastSegment.lastIndexOf('.');
177
118
  if (extensionIndex > 0) {
178
119
  pathSegments[pathSegments.length - 1] =
@@ -180,15 +121,9 @@ export class PageRouter {
180
121
  }
181
122
  }
182
123
  }
183
- // Join the segments back together
184
124
  const finalPath = pathSegments.join('/') === '' ? '/' : pathSegments.join('/');
185
125
  return finalPath;
186
126
  }
187
- /**
188
- * Resolves the given request by finding a matching page and extracting dynamic parameters.
189
- * @param request The request to resolve.
190
- * @returns An object containing the matched page and parameters, or an empty params object if no match.
191
- */
192
127
  resolve(request) {
193
128
  const url = new URL(request.url);
194
129
  const reqPath = normalizePath(url.pathname);
@@ -203,12 +138,6 @@ export class PageRouter {
203
138
  console.debug(`No matching route found for path: ${reqPath}`);
204
139
  return { params: {} };
205
140
  }
206
- /**
207
- * Checks if the request path matches the page path, extracting dynamic parameters if matched.
208
- * @param requestPath The request path to check.
209
- * @param pagePath The page path to match against.
210
- * @returns A record of dynamic parameters if matched, otherwise null.
211
- */
212
141
  matchRoute(requestPath, pagePath) {
213
142
  const reqSegments = requestPath.split('/').filter(Boolean);
214
143
  const pageSegments = pagePath.split('/').filter(Boolean);
@@ -1,20 +1,10 @@
1
- import type { ServerOptions, FetchHandler } from '@burgerTypes';
1
+ import type { ServerOptions, FetchHandler } from '../types/index';
2
2
  export declare class Server {
3
3
  private options;
4
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
5
  constructor(options: ServerOptions);
10
6
  start(routes: {
11
7
  [key: string]: any;
12
8
  } | undefined, handler: FetchHandler, port: number, cb?: () => void): void;
13
- /**
14
- * Stops the server.
15
- * If the server is currently running, this method will stop the server and
16
- * log a message to the console indicating that the server has been stopped.
17
- * If the server is not running, this method does nothing.
18
- */
19
9
  stop(): void;
20
10
  }
@@ -1,32 +1,22 @@
1
- // Import stuff from Bun
2
1
  import { serve } from 'bun';
3
- // Import stuff from utils
4
- import { errorResponse } from '../utils/error.js';
2
+ import { errorResponse } from '../utils/error';
5
3
  export class Server {
6
4
  options;
7
5
  server = null;
8
- /**
9
- * Initializes a new instance of the Server class with the given options.
10
- * @param options - Configuration options for the server.
11
- */
12
6
  constructor(options) {
13
7
  this.options = options;
14
8
  }
15
9
  start(routes, handler, port, cb) {
16
- // Start Bun's native server using Bun.serve
17
10
  this.server = serve({
18
11
  routes,
19
- // Bun's fetch handler
20
12
  fetch: async (request) => {
21
13
  try {
22
14
  return await handler(request);
23
15
  }
24
16
  catch (error) {
25
- // Return a custom error response
26
17
  return errorResponse(error, request, this.options.debug ?? false);
27
18
  }
28
19
  },
29
- // Global error handler
30
20
  error(error) {
31
21
  console.error(error);
32
22
  return new Response(`Internal Server Error: ${error.message}`, {
@@ -45,12 +35,6 @@ export class Server {
45
35
  console.log(`🍔 BurgerAPI is running at: http://${this.options.hostname || 'localhost'}:${port}`);
46
36
  }
47
37
  }
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
38
  stop() {
55
39
  if (this.server) {
56
40
  this.server.stop();
@@ -1,77 +1,20 @@
1
- import type { ServerOptions } from '@burgerTypes';
1
+ import type { ServerOptions } from './types/index';
2
2
  export declare class Burger {
3
3
  private options;
4
- /**
5
- * The server instance
6
- */
7
4
  private server;
8
- /**
9
- * The API router instance
10
- */
11
5
  private apiRouter?;
12
- /**
13
- * The page router instance
14
- */
15
6
  private pageRouter?;
16
- /**
17
- * The global middleware
18
- */
19
7
  private globalMiddleware;
20
- /**
21
- * The OpenAPI document
22
- */
23
8
  private openApiDoc;
24
- /**
25
- * The routes object
26
- */
27
9
  private routes;
28
- /**
29
- * Pre-computed responses for reuse
30
- */
31
10
  private readonly METHOD_NOT_ALLOWED;
32
- /**
33
- * The not found response
34
- */
35
11
  private readonly NOT_FOUND;
36
- /**
37
- * The OpenAPI error response
38
- */
39
12
  private readonly OPENAPI_ERROR;
40
- /**
41
- * Constructor for the Burger class.
42
- * @param options - The options for the server and router.
43
- * The options object should contain the following properties:
44
- * - port: The port number to listen on.
45
- * - apiDir: The directory path to load API routes from.
46
- * - pageDir: The directory path to load page routes from.
47
- * - middleware: An array of global middleware functions.
48
- */
49
13
  constructor(options: ServerOptions);
50
- /**
51
- * Process the page routes and add them to the routes object
52
- * @returns A promise that resolves to a boolean
53
- */
54
14
  private processPageRoutes;
55
- /**
56
- * Process the API routes and add them to the routes object
57
- * @returns A promise that resolves to a boolean
58
- */
59
15
  private processApiRoutes;
60
- /**
61
- * Process the middleware and handler
62
- * @param request - The request object
63
- * @param middlewares - The middleware array
64
- * @param handler - The handler function
65
- * @returns A promise that resolves to a response
66
- */
67
16
  private processMiddleware;
68
- /**
69
- * Starts the server and begins listening for incoming requests.
70
- * @param port - The port number to listen on. Defaults to `4000`.
71
- * @param cb - An optional cb function to be executed when the server is listening.
72
- * @returns A Promise that resolves when the server has started listening.
73
- */
74
17
  serve(port?: number, cb?: () => void): Promise<void>;
75
18
  }
76
- export { setDir } from './utils/index.js';
77
- export type { ServerOptions, RequestHandler, BurgerRequest, BurgerNext, Middleware, openapi, } from '@burgerTypes';
19
+ export { setDir } from './utils/index';
20
+ export type { ServerOptions, RequestHandler, BurgerRequest, BurgerNext, Middleware, openapi, } from './types/index';