burger-api 0.3.1 → 0.4.0

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/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  [![Under Development](https://img.shields.io/badge/under%20development-red.svg)](https://github.com/isfhan/burger-api)
6
6
  [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
7
7
  [![Bun](https://img.shields.io/badge/Bun-1.2.20-black?logo=bun)](https://bun.sh)
8
- [![Version](https://img.shields.io/badge/version-0.3.0-green.svg)](https://github.com/isfhan/burger-api/releases)
8
+ [![Version](https://img.shields.io/badge/version-0.4.0-green.svg)](https://github.com/isfhan/burger-api/releases)
9
9
 
10
10
  **burger-api** is a modern, open source API framework built on
11
11
  [Bun.js](https://bun.sh). It combines the simplicity of file-based routing with
@@ -59,7 +59,17 @@ burger-api is built to offer a robust developer experience through:
59
59
 
60
60
  ## 📣 Changelog
61
61
 
62
- ### Latest Version: 0.3.0 (August 15, 2025)
62
+ ### Latest Version: 0.4.0 (October 21, 2025)
63
+
64
+ - 🎯 **Wildcard Routes:**
65
+ - Added wildcard routes using `[...]` folder name - matches any path after it
66
+ - Create routes that handle multiple path segments automatically
67
+ - Access all matched path parts through `wildcardParams` in your request
68
+ - Routes are matched in order: exact paths first, then dynamic routes (like `[id]`), then wildcards last
69
+ - Works inside dynamic routes too (example: `/api/users/[userId]/[...]`)
70
+ - View wildcard routes in OpenAPI docs and Swagger UI
71
+
72
+ ### Version 0.3.0 (August 15, 2025)
63
73
 
64
74
  - 🔧 **Updated Zod to version 4:**
65
75
  - Updated Zod version from 3.x to 4.x
@@ -2,8 +2,8 @@ import type { RouteDefinition, TrieNode } from '@burgerTypes';
2
2
  /**
3
3
  * ApiRouter class for handling file-based routing.
4
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.
5
+ * Supports dynamic segments (e.g., [id] ,(group),[...]) and HTTP method handlers.
6
+ * Routes are sorted to prioritize static routes over dynamic and wildcard ones to prevent overlapping route issues.
7
7
  */
8
8
  export declare class ApiRouter {
9
9
  private routesDir;
@@ -51,20 +51,21 @@ export declare class ApiRouter {
51
51
  */
52
52
  private loadRouteModule;
53
53
  /**
54
- * Converts a file path to a route path by processing dynamic segments and applying the prefix.
55
- * @param filePath The file path to convert (e.g., "users/[id]/route.ts").
56
- * @returns {string} The converted route path (e.g., "/users/:id").
54
+ * Converts a file path to a route path by processing dynamic segments and wildcard segments applying the prefix.
55
+ * @param filePath The file path to convert (e.g., "users/[id]/route.ts" , "users/[...slug]/route.ts").
56
+ * @returns {string} The converted route path (e.g., "/users/:id" , "/users/*slug").
57
57
  */
58
58
  private convertFilePathToRoute;
59
59
  /**
60
60
  * Resolves a request to a route definition and its parameters.
61
61
  * @param pathname The normalized request pathname.
62
62
  * @param method The uppercase HTTP method.
63
- * @returns {{ route?: RouteDefinition; params: Record<string, string> }} An object containing the matched route (if any) and extracted parameters.
63
+ * @returns {{ route?: RouteDefinition; params: Record<string, string>; wildcardParams?: string[] }} An object containing the matched route (if any), extracted parameters, and wildcard segments (if applicable).
64
64
  * @throws {Error} If the request URL is malformed.
65
65
  */
66
66
  resolve(pathname: string, method: string): {
67
67
  route?: RouteDefinition;
68
68
  params: Record<string, string>;
69
+ wildcardParams?: string[];
69
70
  };
70
71
  }
@@ -6,8 +6,8 @@ import { cleanPrefix, normalizePath, ROUTE_CONSTANTS, HTTP_METHODS, } from '../u
6
6
  /**
7
7
  * ApiRouter class for handling file-based routing.
8
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.
9
+ * Supports dynamic segments (e.g., [id] ,(group),[...]) and HTTP method handlers.
10
+ * Routes are sorted to prioritize static routes over dynamic and wildcard ones to prevent overlapping route issues.
11
11
  */
12
12
  export class ApiRouter {
13
13
  routesDir;
@@ -58,13 +58,23 @@ export class ApiRouter {
58
58
  const segments = routeDef.path.split('/').filter(Boolean);
59
59
  for (const segment of segments) {
60
60
  if (segment.startsWith(':')) {
61
+ // Handle dynamic segments (:param)
61
62
  if (!node.paramChild) {
62
63
  node.paramChild = { children: new Map() };
63
64
  }
64
65
  node = node.paramChild;
65
66
  node.paramName = segment.slice(1);
66
67
  }
68
+ else if (segment.startsWith('*')) {
69
+ // Handle wildcard segments (*param)
70
+ if (!node.wildcardChild) {
71
+ node.wildcardChild = { children: new Map() };
72
+ }
73
+ node = node.wildcardChild;
74
+ node.isWildcard = true; // Mark as wildcard route
75
+ }
67
76
  else {
77
+ // Handle static segments
68
78
  if (!node.children.has(segment)) {
69
79
  node.children.set(segment, { children: new Map() });
70
80
  }
@@ -81,22 +91,42 @@ export class ApiRouter {
81
91
  * @throws {Error} If multiple dynamic folders are found at the same level or if directory access fails.
82
92
  */
83
93
  async scanDirectory(dir, basePath = '') {
84
- // Track if a dynamic folder has been found at this directory level
94
+ // Track route types at this directory level to prevent conflicts
85
95
  let dynamicFolderFound = false;
96
+ let wildcardFolderFound = false;
86
97
  try {
87
98
  const entries = await readdir(dir, { withFileTypes: true });
88
99
  for (const entry of entries) {
89
100
  const entryPath = path.join(dir, entry.name);
90
101
  const relativePath = path.join(basePath, entry.name);
91
102
  if (entry.isDirectory()) {
92
- // Handle dynamic directories (e.g., [id])
93
- if (entry.name.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
94
- entry.name.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END)) {
95
- if (dynamicFolderFound) {
96
- throw new Error(`Multiple dynamic route folders found in the same directory: '${entry.name}' conflicts with another dynamic folder in '${dir}'.`);
97
- }
98
- dynamicFolderFound = true;
103
+ // Check if this is a dynamic or wildcard directory
104
+ const isDynamic = entry.name.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
105
+ entry.name.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END) &&
106
+ entry.name !== ROUTE_CONSTANTS.WILDCARD_SIMPLE;
107
+ const isWildcard = entry.name === ROUTE_CONSTANTS.WILDCARD_SIMPLE;
108
+ // Prevent conflicts between dynamic and wildcard routes
109
+ if (isDynamic && wildcardFolderFound) {
110
+ throw new Error(`Cannot mix dynamic and wildcard route folders in the same directory. ` +
111
+ `Found dynamic folder '${entry.name}' but wildcard folder already exists in '${dir}'.`);
112
+ }
113
+ if (isWildcard && dynamicFolderFound) {
114
+ throw new Error(`Cannot mix wildcard and dynamic route folders in the same directory. ` +
115
+ `Found wildcard folder '${entry.name}' but dynamic folder already exists in '${dir}'.`);
116
+ }
117
+ if (isDynamic && dynamicFolderFound) {
118
+ throw new Error(`Multiple dynamic route folders found in the same directory: ` +
119
+ `'${entry.name}' conflicts with another dynamic folder in '${dir}'.`);
99
120
  }
121
+ if (isWildcard && wildcardFolderFound) {
122
+ throw new Error(`Multiple wildcard route folders found in the same directory: ` +
123
+ `'${entry.name}' conflicts with another wildcard folder in '${dir}'.`);
124
+ }
125
+ // Update flags
126
+ if (isDynamic)
127
+ dynamicFolderFound = true;
128
+ if (isWildcard)
129
+ wildcardFolderFound = true;
100
130
  await this.scanDirectory(entryPath, relativePath);
101
131
  }
102
132
  else if (entry.isFile() && entry.name === 'route.ts') {
@@ -141,6 +171,7 @@ export class ApiRouter {
141
171
  middleware: routeModule.middleware,
142
172
  schema: routeModule.schema,
143
173
  openapi: routeModule.openapi,
174
+ isWildcard: routePath.includes(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX),
144
175
  };
145
176
  this.insertRoute(routeDef);
146
177
  }
@@ -149,9 +180,9 @@ export class ApiRouter {
149
180
  }
150
181
  }
151
182
  /**
152
- * Converts a file path to a route path by processing dynamic segments and applying the prefix.
153
- * @param filePath The file path to convert (e.g., "users/[id]/route.ts").
154
- * @returns {string} The converted route path (e.g., "/users/:id").
183
+ * Converts a file path to a route path by processing dynamic segments and wildcard segments applying the prefix.
184
+ * @param filePath The file path to convert (e.g., "users/[id]/route.ts" , "users/[...slug]/route.ts").
185
+ * @returns {string} The converted route path (e.g., "/users/:id" , "/users/*slug").
155
186
  */
156
187
  convertFilePathToRoute(filePath) {
157
188
  // Remove the "route.ts" suffix
@@ -166,14 +197,20 @@ export class ApiRouter {
166
197
  continue; // Skip empty segments
167
198
  // Skip grouping segments (e.g., (group))
168
199
  if (segment.startsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_START) &&
169
- segment.endsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_END))
200
+ segment.endsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_END)) {
170
201
  continue;
202
+ }
171
203
  // Convert dynamic segments from [param] to :param
172
204
  if (segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
173
- segment.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END)) {
205
+ segment.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END) &&
206
+ !segment.startsWith(ROUTE_CONSTANTS.WILDCARD_START)) {
174
207
  const param = segment.slice(1, -1);
175
208
  resultSegments.push(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX + param);
176
209
  }
210
+ // Convert wildcard segments from [...] to *
211
+ else if (segment === ROUTE_CONSTANTS.WILDCARD_SIMPLE) {
212
+ resultSegments.push(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX);
213
+ }
177
214
  else {
178
215
  resultSegments.push(segment);
179
216
  }
@@ -195,7 +232,7 @@ export class ApiRouter {
195
232
  * Resolves a request to a route definition and its parameters.
196
233
  * @param pathname The normalized request pathname.
197
234
  * @param method The uppercase HTTP method.
198
- * @returns {{ route?: RouteDefinition; params: Record<string, string> }} An object containing the matched route (if any) and extracted parameters.
235
+ * @returns {{ route?: RouteDefinition; params: Record<string, string>; wildcardParams?: string[] }} An object containing the matched route (if any), extracted parameters, and wildcard segments (if applicable).
199
236
  * @throws {Error} If the request URL is malformed.
200
237
  */
201
238
  resolve(pathname, method) {
@@ -203,21 +240,39 @@ export class ApiRouter {
203
240
  const segments = pathname.split('/').filter(Boolean);
204
241
  let node = this.root;
205
242
  const params = {};
206
- for (const segment of segments) {
243
+ let wildcardSegments = [];
244
+ // Traverse the trie with proper prioritization
245
+ for (let i = 0; i < segments.length; i++) {
246
+ const segment = segments[i];
247
+ // Priority 1: Exact static match (highest priority)
207
248
  if (node.children.has(segment)) {
208
249
  node = node.children.get(segment);
209
250
  }
251
+ // Priority 2: Dynamic parameter match (medium priority)
210
252
  else if (node.paramChild) {
211
253
  node = node.paramChild;
212
254
  params[node.paramName] = segment;
213
255
  }
256
+ // Priority 3: Collect remaining segments for wildcard (lowest priority)
214
257
  else {
215
- return { params: {} };
258
+ wildcardSegments = segments.slice(i);
259
+ break;
216
260
  }
217
261
  }
218
- if (node.route && node.route.handlers[method]) {
262
+ // Check if we have a route at the current node
263
+ if (node.route?.handlers[method]) {
219
264
  return { route: node.route, params };
220
265
  }
266
+ // If no route found but we have wildcard segments, check for wildcard route
267
+ if (wildcardSegments.length > 0 &&
268
+ node.wildcardChild?.route?.handlers[method]) {
269
+ // Return wildcard segments so they can be added to req.wildcardParams
270
+ return {
271
+ route: node.wildcardChild.route,
272
+ params,
273
+ wildcardParams: wildcardSegments,
274
+ };
275
+ }
221
276
  return { params: {} };
222
277
  }
223
278
  catch (error) {
@@ -84,13 +84,24 @@ function buildRequestBody(zodSchema) {
84
84
  }
85
85
  /**
86
86
  * Converts a route path from colon-based dynamic segments to OpenAPI's curly brace syntax.
87
+ * Also handles wildcard routes.
87
88
  *
88
- * @param routePath The original route path with colon-based dynamic segments (e.g., "/user/:id").
89
- * @returns The converted route path with curly brace syntax (e.g., "/user/{id}").
89
+ * @param routePath The original route path with colon-based dynamic segments (e.g., "/user/:id") or wildcards (e.g., "/files/*").
90
+ * @returns The converted route path with curly brace syntax (e.g., "/user/{id}") or wildcard format (e.g., "/files/*").
90
91
  */
91
92
  function convertPathForOpenAPI(routePath) {
93
+ // Fast path: if no special chars, return as-is
94
+ if (routePath.indexOf(':') === -1 && routePath.indexOf('*') === -1) {
95
+ return routePath;
96
+ }
92
97
  // Replace occurrences of :param with {param}
93
- return routePath.replace(/:([a-zA-Z0-9_]+)/g, '{$1}');
98
+ let converted = routePath.replace(/:([a-zA-Z0-9_]+)/g, '{$1}');
99
+ // Handle wildcard routes
100
+ // OpenAPI 3.0 doesn't have official wildcard syntax, so we keep /* as-is
101
+ // This will display in Swagger as /api/files/* which is intuitive and common
102
+ // Alternative: convert to {path*} format if preferred
103
+ // converted = converted.replace(/\/\*$/g, '/{path*}');
104
+ return converted;
94
105
  }
95
106
  export function generateOpenAPIDocument(apiRoutes, options) {
96
107
  const openapiDoc = {
package/dist/src/index.js CHANGED
@@ -147,7 +147,80 @@ export class Burger {
147
147
  // Create optimized route handler
148
148
  if (totalMiddlewareCount === 0) {
149
149
  // Ultra-fast path: no middleware
150
+ // Pre-compute wildcard segment count for faster extraction
151
+ const isWildcard = route.isWildcard;
152
+ // Calculate how many segments come before the wildcard
153
+ // E.g., "/api/users/:userId/*" has 3 segments before wildcard (api, users, :userId)
154
+ const baseSegmentCount = isWildcard
155
+ ? path.split('/').filter(Boolean).length - 1 // Subtract 1 for the * itself
156
+ : 0;
150
157
  routes[path] = (request) => {
158
+ // Extract wildcard params if this is a wildcard route
159
+ if (isWildcard) {
160
+ // Step 1: Get the pathname from the URL
161
+ // Example: "http://localhost:4000/api/users/123/profile?id=1" → "/api/users/123/profile"
162
+ const url = request.url;
163
+ // Find where the path starts (after protocol and domain)
164
+ // Example: "http://localhost:4000/api/..." → protocolEnd = 4 (after "http")
165
+ const protocolEnd = url.indexOf('://');
166
+ // Find first "/" after the domain
167
+ // Example: "http://localhost:4000/api/..." → pathStart = 21 (the "/" before "api")
168
+ const pathStart = url.indexOf('/', protocolEnd + 3);
169
+ // Find where query parameters start (if any)
170
+ // Example: "/api/users/123?id=1" → pathEnd = 15 (at the "?")
171
+ const pathEnd = url.indexOf('?', pathStart);
172
+ // Extract just the pathname without query parameters
173
+ // Example: "/api/users/123/profile"
174
+ const pathname = pathEnd === -1
175
+ ? url.substring(pathStart) // No query params
176
+ : url.substring(pathStart, pathEnd); // Has query params, stop at "?"
177
+ // Step 2: Extract wildcard segments efficiently
178
+ // Example route: "/api/users/:userId/*" has baseSegmentCount = 3
179
+ // - Segment 0: "api"
180
+ // - Segment 1: "users"
181
+ // - Segment 2: ":userId" (or "123" in actual URL)
182
+ // - Segment 3+: wildcard segments we want!
183
+ if (baseSegmentCount === 0) {
184
+ // Fast path: The entire path is wildcard
185
+ // Example: "/api/docs/*" where all segments after domain are wildcards
186
+ // Just split everything and we're done!
187
+ request.wildcardParams = pathname
188
+ .split('/')
189
+ .filter(Boolean);
190
+ }
191
+ else {
192
+ // Optimized path: Skip base segments and only collect wildcard segments
193
+ // Example: "/api/users/123/settings/privacy"
194
+ // - We need to skip 3 segments (api, users, 123)
195
+ // - Only collect: ["settings", "privacy"]
196
+ const wildcardParams = [];
197
+ let segmentCount = 0; // Counts how many segments we've seen
198
+ let start = pathname[0] === '/' ? 1 : 0; // Start after leading "/" if present
199
+ // Loop through each character in the pathname
200
+ // When we hit "/" or end of string, we know we found a segment
201
+ for (let i = start; i <= pathname.length; i++) {
202
+ // Found end of a segment (either "/" or end of string)
203
+ if (i === pathname.length ||
204
+ pathname[i] === '/') {
205
+ // Make sure it's not an empty segment (from double slashes)
206
+ if (i > start) {
207
+ // Only save segments AFTER we've skipped the base segments
208
+ // Example: If baseSegmentCount=3, save segment 3, 4, 5, etc.
209
+ if (segmentCount >= baseSegmentCount) {
210
+ // Extract this segment from the pathname
211
+ // Example: pathname.substring(5, 13) might give "settings"
212
+ wildcardParams.push(pathname.substring(start, i));
213
+ }
214
+ segmentCount++; // Increment count for next segment
215
+ }
216
+ start = i + 1; // Move start position to character after "/"
217
+ }
218
+ }
219
+ // Done! wildcardParams now contains only the wildcard segments
220
+ // Example: ["settings", "privacy"] instead of ["api", "users", "123", "settings", "privacy"]
221
+ request.wildcardParams = wildcardParams;
222
+ }
223
+ }
151
224
  const handler = handlers[request.method];
152
225
  return handler ? handler(request) : this.METHOD_NOT_ALLOWED;
153
226
  };
@@ -176,14 +249,99 @@ export class Burger {
176
249
  * Pre-compute the required functionality end
177
250
  * ================================================
178
251
  */
252
+ // Pre-compute wildcard segment count for faster extraction
253
+ const isWildcard = route.isWildcard;
254
+ // Calculate how many segments come before the wildcard
255
+ // E.g., "/api/users/:userId/*" has 3 segments before wildcard (api, users, :userId)
256
+ const baseSegmentCount = isWildcard
257
+ ? path.split('/').filter(Boolean).length - 1 // Subtract 1 for the * itself
258
+ : 0;
179
259
  // Create handler with middleware
180
260
  routes[path] = (request) => {
261
+ // Extract wildcard params if this is a wildcard route
262
+ if (isWildcard) {
263
+ // Step 1: Get the pathname from the URL
264
+ // Example: "http://localhost:4000/api/users/123/profile?id=1" → "/api/users/123/profile"
265
+ const url = request.url;
266
+ // Find where the path starts (after protocol and domain)
267
+ // Example: "http://localhost:4000/api/..." → protocolEnd = 4 (after "http")
268
+ const protocolEnd = url.indexOf('://');
269
+ // Find first "/" after the domain
270
+ // Example: "http://localhost:4000/api/..." → pathStart = 21 (the "/" before "api")
271
+ const pathStart = url.indexOf('/', protocolEnd + 3);
272
+ // Find where query parameters start (if any)
273
+ // Example: "/api/users/123?id=1" → pathEnd = 15 (at the "?")
274
+ const pathEnd = url.indexOf('?', pathStart);
275
+ // Extract just the pathname without query parameters
276
+ // Example: "/api/users/123/profile"
277
+ const pathname = pathEnd === -1
278
+ ? url.substring(pathStart) // No query params
279
+ : url.substring(pathStart, pathEnd); // Has query params, stop at "?"
280
+ // Step 2: Extract wildcard segments efficiently
281
+ // Example route: "/api/users/:userId/*" has baseSegmentCount = 3
282
+ // - Segment 0: "api"
283
+ // - Segment 1: "users"
284
+ // - Segment 2: ":userId" (or "123" in actual URL)
285
+ // - Segment 3+: wildcard segments we want!
286
+ if (baseSegmentCount === 0) {
287
+ // Fast path: The entire path is wildcard
288
+ // Example: "/api/docs/*" where all segments after domain are wildcards
289
+ // Just split everything and we're done!
290
+ request.wildcardParams = pathname
291
+ .split('/')
292
+ .filter(Boolean);
293
+ }
294
+ else {
295
+ // Optimized path: Skip base segments and only collect wildcard segments
296
+ // Example: "/api/users/123/settings/privacy"
297
+ // - We need to skip 3 segments (api, users, 123)
298
+ // - Only collect: ["settings", "privacy"]
299
+ const wildcardParams = [];
300
+ let segmentCount = 0; // Counts how many segments we've seen
301
+ let start = pathname[0] === '/' ? 1 : 0; // Start after leading "/" if present
302
+ // Loop through each character in the pathname
303
+ // When we hit "/" or end of string, we know we found a segment
304
+ for (let i = start; i <= pathname.length; i++) {
305
+ // Found end of a segment (either "/" or end of string)
306
+ if (i === pathname.length ||
307
+ pathname[i] === '/') {
308
+ // Make sure it's not an empty segment (from double slashes)
309
+ if (i > start) {
310
+ // Only save segments AFTER we've skipped the base segments
311
+ // Example: If baseSegmentCount=3, save segment 3, 4, 5, etc.
312
+ if (segmentCount >= baseSegmentCount) {
313
+ // Extract this segment from the pathname
314
+ // Example: pathname.substring(5, 13) might give "settings"
315
+ wildcardParams.push(pathname.substring(start, i));
316
+ }
317
+ segmentCount++; // Increment count for next segment
318
+ }
319
+ start = i + 1; // Move start position to character after "/"
320
+ }
321
+ }
322
+ // Done! wildcardParams now contains only the wildcard segments
323
+ // Example: ["settings", "privacy"] instead of ["api", "users", "123", "settings", "privacy"]
324
+ request.wildcardParams = wildcardParams;
325
+ }
326
+ }
181
327
  const handler = handlers[request.method];
182
328
  if (!handler)
183
329
  return this.METHOD_NOT_ALLOWED;
184
330
  return this.processMiddleware(request, middlewares, handler);
185
331
  };
186
332
  }
333
+ // For wildcard routes, also register the base path
334
+ // Bun's /* wildcard may not match the base path itself, so we register both
335
+ if (route.isWildcard && path.endsWith('/*')) {
336
+ const basePath = path.slice(0, -2); // Remove "/*" to get base path
337
+ // Only register base path if no static route exists (preserve priority)
338
+ // Static routes have highest priority: Static > Dynamic > Wildcard
339
+ if (!routes[basePath]) {
340
+ // No static route found, register wildcard for base path
341
+ routes[basePath] = routes[path];
342
+ }
343
+ // If static route exists, it takes priority (correct behavior)
344
+ }
187
345
  }
188
346
  // Add special routes for OpenAPI
189
347
  routes['/openapi.json'] = () => this.openApiDoc
@@ -253,7 +411,7 @@ export class Burger {
253
411
  for (let i = afterCount - 1; i >= 0; i--) {
254
412
  response = await afterStack[i](response);
255
413
  }
256
- // Return the responseF
414
+ // Return the response
257
415
  return response;
258
416
  }
259
417
  /**
@@ -10,6 +10,9 @@ export declare const ROUTE_CONSTANTS: {
10
10
  DYNAMIC_FOLDER_END: string;
11
11
  GROUPING_FOLDER_START: string;
12
12
  GROUPING_FOLDER_END: string;
13
+ WILDCARD_SEGMENT_PREFIX: string;
14
+ WILDCARD_SIMPLE: string;
15
+ WILDCARD_START: string;
13
16
  };
14
17
  /**
15
18
  * Supported HTTP methods
@@ -18,12 +21,14 @@ export declare const HTTP_METHODS: string[];
18
21
  /**
19
22
  * Calculates the specificity of a route path based on the number of static segments.
20
23
  * Static segments increase the score, while dynamic segments (:param) do not.
24
+ * Wildcard segments (*) have the lowest specificity (highest penalty).
21
25
  * @param path The route path to evaluate.
22
- * @returns The specificity score (higher means more static segments).
26
+ * @returns The specificity score (higher means more static segments, lower priority for wildcard).
23
27
  */
24
28
  export declare const getRouteSpecificity: (path: string) => number;
25
29
  /**
26
30
  * Compares two routes for sorting, prioritizing those with higher specificity (more static segments).
31
+ * Route prioritization: Static > Dynamic > Wildcard.
27
32
  * If specificity is equal, sorts alphabetically by path.
28
33
  * @param a The first route to compare.
29
34
  * @param b The second route to compare.
@@ -2,13 +2,21 @@
2
2
  * Constants for route handling.
3
3
  */
4
4
  export const ROUTE_CONSTANTS = {
5
+ // Supported page extensions
5
6
  SUPPORTED_PAGE_EXTENSIONS: ['.tsx', '.html'],
7
+ // Page index files
6
8
  PAGE_INDEX_FILES: ['index.tsx', 'index.html'],
9
+ // Dynamic route constants
7
10
  DYNAMIC_SEGMENT_PREFIX: ':',
8
11
  DYNAMIC_FOLDER_START: '[',
9
12
  DYNAMIC_FOLDER_END: ']',
13
+ // Grouping folder constants
10
14
  GROUPING_FOLDER_START: '(',
11
15
  GROUPING_FOLDER_END: ')',
16
+ // Wildcard route constants
17
+ WILDCARD_SEGMENT_PREFIX: '*',
18
+ WILDCARD_SIMPLE: '[...]',
19
+ WILDCARD_START: '[...',
12
20
  };
13
21
  /**
14
22
  * Supported HTTP methods
@@ -25,19 +33,24 @@ export const HTTP_METHODS = [
25
33
  /**
26
34
  * Calculates the specificity of a route path based on the number of static segments.
27
35
  * Static segments increase the score, while dynamic segments (:param) do not.
36
+ * Wildcard segments (*) have the lowest specificity (highest penalty).
28
37
  * @param path The route path to evaluate.
29
- * @returns The specificity score (higher means more static segments).
38
+ * @returns The specificity score (higher means more static segments, lower priority for wildcard).
30
39
  */
31
40
  export const getRouteSpecificity = (path) => {
32
41
  const segments = path.split('/').filter(Boolean);
33
42
  return segments.reduce((score, segment) => {
43
+ if (segment.startsWith(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX)) {
44
+ return score + 1000; // Wildcard routes get highest penalty (lowest priority)
45
+ }
34
46
  return segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX)
35
- ? score
36
- : score + 1;
47
+ ? score + 100 // Dynamic routes get medium penalty
48
+ : score + 1; // Static routes get minimal penalty
37
49
  }, 0);
38
50
  };
39
51
  /**
40
52
  * Compares two routes for sorting, prioritizing those with higher specificity (more static segments).
53
+ * Route prioritization: Static > Dynamic > Wildcard.
41
54
  * If specificity is equal, sorts alphabetically by path.
42
55
  * @param a The first route to compare.
43
56
  * @param b The second route to compare.
@@ -76,5 +89,11 @@ export function collectRoutes(node, currentPath = '', routes = []) {
76
89
  const paramPath = `${currentPath}/:${node.paramChild.paramName}`;
77
90
  collectRoutes(node.paramChild, paramPath, routes);
78
91
  }
92
+ // Traverse wildcard child if exists (lowest priority)
93
+ if (node.wildcardChild) {
94
+ // const wildcardPath = `${currentPath}/${node.wildcardChild.wildcardParamName}`;
95
+ const wildcardPath = `${currentPath}/${ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX}`;
96
+ collectRoutes(node.wildcardChild, wildcardPath, routes);
97
+ }
79
98
  return routes;
80
99
  }
package/package.json CHANGED
@@ -1,89 +1,89 @@
1
- {
2
- "name": "burger-api",
3
- "version": "0.3.1",
4
- "author": "Isfhan Ahmed",
5
- "type": "module",
6
- "module": "dist/src/index.js",
7
- "types": "dist/src/index.d.ts",
8
- "files": [
9
- "dist"
10
- ],
11
- "scripts": {
12
- "typecheck": "tsc --noEmit",
13
- "build": "tsc --project tsconfig.build.json && tsc-alias -p tsconfig.build.json",
14
- "test": "bun test",
15
- "dev": "bun run examples/file-base-static-page-routing-app/index.ts"
16
- },
17
- "keywords": [
18
- "burger-api",
19
- "burger-api-framework",
20
- "bun",
21
- "bunjs",
22
- "bun-framework",
23
- "fast-backend",
24
- "javascript-backend",
25
- "high-performance",
26
- "esm",
27
- "typescript",
28
- "openapi",
29
- "swagger-ui",
30
- "declarative-routing",
31
- "api-framework",
32
- "modern-backend",
33
- "backend-framework",
34
- "server",
35
- "bun-native",
36
- "js-backend",
37
- "fast-api",
38
- "scalable-backend",
39
- "backend-development",
40
- "modern-api",
41
- "api-development",
42
- "backend-engine",
43
- "efficient",
44
- "minimalist-backend",
45
- "bun-powered",
46
- "open-source",
47
- "typescript-backend",
48
- "performance",
49
- "rapid-development",
50
- "web-framework",
51
- "api-server",
52
- "dynamic-routing",
53
- "backend-routing",
54
- "extensible",
55
- "modular",
56
- "declarative-api",
57
- "lightweight",
58
- "contemporary-backend",
59
- "fast-javascript",
60
- "bun-js-framework",
61
- "bun-backend",
62
- "bun-api-framework",
63
- "pakistan-backend",
64
- "pakistan-api-framework",
65
- "pakistan-api-server",
66
- "pakistan-backend-framework",
67
- "pakistan-bunjs-framework",
68
- "pakistan-javascript-framework"
69
- ],
70
- "license": "MIT",
71
- "repository": {
72
- "type": "git",
73
- "url": "git+https://github.com/isfhan/burger-api.git"
74
- },
75
- "bugs": {
76
- "url": "https://github.com/isfhan/burger-api/issues"
77
- },
78
- "homepage": "https://burger-api.com",
79
- "dependencies": {
80
- "zod": "^4.0.17"
81
- },
82
- "devDependencies": {
83
- "@types/bun": "latest",
84
- "tsc-alias": "^1.8.16"
85
- },
86
- "peerDependencies": {
87
- "typescript": "^5.7.3"
88
- }
1
+ {
2
+ "name": "burger-api",
3
+ "version": "0.4.0",
4
+ "author": "Isfhan Ahmed",
5
+ "type": "module",
6
+ "module": "dist/src/index.js",
7
+ "types": "dist/src/index.d.ts",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "scripts": {
12
+ "typecheck": "tsc --noEmit",
13
+ "build": "tsc --project tsconfig.build.json && tsc-alias -p tsconfig.build.json",
14
+ "test": "bun test",
15
+ "dev": "bun run examples/file-base-static-page-routing-app/index.ts"
16
+ },
17
+ "keywords": [
18
+ "burger-api",
19
+ "burger-api-framework",
20
+ "bun",
21
+ "bunjs",
22
+ "bun-framework",
23
+ "fast-backend",
24
+ "javascript-backend",
25
+ "high-performance",
26
+ "esm",
27
+ "typescript",
28
+ "openapi",
29
+ "swagger-ui",
30
+ "declarative-routing",
31
+ "api-framework",
32
+ "modern-backend",
33
+ "backend-framework",
34
+ "server",
35
+ "bun-native",
36
+ "js-backend",
37
+ "fast-api",
38
+ "scalable-backend",
39
+ "backend-development",
40
+ "modern-api",
41
+ "api-development",
42
+ "backend-engine",
43
+ "efficient",
44
+ "minimalist-backend",
45
+ "bun-powered",
46
+ "open-source",
47
+ "typescript-backend",
48
+ "performance",
49
+ "rapid-development",
50
+ "web-framework",
51
+ "api-server",
52
+ "dynamic-routing",
53
+ "backend-routing",
54
+ "extensible",
55
+ "modular",
56
+ "declarative-api",
57
+ "lightweight",
58
+ "contemporary-backend",
59
+ "fast-javascript",
60
+ "bun-js-framework",
61
+ "bun-backend",
62
+ "bun-api-framework",
63
+ "pakistan-backend",
64
+ "pakistan-api-framework",
65
+ "pakistan-api-server",
66
+ "pakistan-backend-framework",
67
+ "pakistan-bunjs-framework",
68
+ "pakistan-javascript-framework"
69
+ ],
70
+ "license": "MIT",
71
+ "repository": {
72
+ "type": "git",
73
+ "url": "git+https://github.com/isfhan/burger-api.git"
74
+ },
75
+ "bugs": {
76
+ "url": "https://github.com/isfhan/burger-api/issues"
77
+ },
78
+ "homepage": "https://burger-api.com",
79
+ "dependencies": {
80
+ "zod": "^4.0.17"
81
+ },
82
+ "devDependencies": {
83
+ "@types/bun": "latest",
84
+ "tsc-alias": "^1.8.16"
85
+ },
86
+ "peerDependencies": {
87
+ "typescript": "^5.7.3"
88
+ }
89
89
  }