burger-api 0.0.39 → 0.1.4

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,17 +1,17 @@
1
- import type { RouteDefinition } from "../types/index.js";
1
+ import type { RouteDefinition } from '../types/index.js';
2
2
  /**
3
- * Router class for handling file-based routing.
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
5
  * Supports dynamic segments (e.g., [id]) and HTTP method handlers.
6
6
  * Routes are sorted to prioritize static routes over dynamic ones to prevent overlapping route issues.
7
7
  */
8
- export declare class Router {
8
+ export declare class ApiRouter {
9
9
  private routesDir;
10
10
  private prefix;
11
11
  /** Array of loaded route definitions */
12
12
  routes: RouteDefinition[];
13
13
  /**
14
- * Constructor for the Router class.
14
+ * Constructor for the ApiRouter class.
15
15
  * @param routesDir The directory path where route modules are located.
16
16
  * @param prefix Optional prefix to prepend to all routes (e.g., "api" becomes "/api/...").
17
17
  */
@@ -20,14 +20,22 @@ export declare class Router {
20
20
  * Loads route modules from the specified directory and adds them to the routes array.
21
21
  * After loading, sorts the routes to prioritize static routes over dynamic ones based on specificity.
22
22
  * @returns A promise that resolves when all route modules have been loaded and sorted.
23
+ * @throws Error if the routes directory doesn't exist or can't be accessed
23
24
  */
24
25
  loadRoutes(): Promise<void>;
25
26
  /**
26
27
  * Recursively scans the directory for route modules and adds them to the routes array.
27
28
  * @param dir The current directory to scan.
28
29
  * @param basePath The base path for constructing the route path.
30
+ * @throws Error if multiple dynamic folders are found at the same level or if directory access fails
29
31
  */
30
32
  private scanDirectory;
33
+ /**
34
+ * Loads a route module and adds it to the routes array
35
+ * @param entryPath Full path to the route file
36
+ * @param relativePath Relative path used to construct the route
37
+ */
38
+ private loadRouteModule;
31
39
  /**
32
40
  * Converts a file path to a route path by processing dynamic segments,
33
41
  * removing certain directory indicators, and applying a prefix if specified.
@@ -51,19 +59,4 @@ export declare class Router {
51
59
  * @returns A record of dynamic parameters if matched, otherwise null.
52
60
  */
53
61
  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
62
  }
@@ -0,0 +1,209 @@
1
+ // Import stuff from node
2
+ import { readdirSync } from 'fs';
3
+ import * as path from 'path';
4
+ // Import utils
5
+ import { cleanPrefix, normalizePath, compareRoutes, ROUTE_CONSTANTS, HTTP_METHODS, } from '../utils/index.js';
6
+ /**
7
+ * ApiRouter 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 ApiRouter {
13
+ routesDir;
14
+ prefix;
15
+ /** Array of loaded route definitions */
16
+ routes = [];
17
+ /**
18
+ * Constructor for the ApiRouter 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
+ if (!routesDir) {
26
+ throw new Error('Routes directory path is required');
27
+ }
28
+ }
29
+ /**
30
+ * Loads route modules from the specified directory and adds them to the routes array.
31
+ * After loading, sorts the routes to prioritize static routes over dynamic ones based on specificity.
32
+ * @returns A promise that resolves when all route modules have been loaded and sorted.
33
+ * @throws Error if the routes directory doesn't exist or can't be accessed
34
+ */
35
+ async loadRoutes() {
36
+ try {
37
+ this.routes = [];
38
+ await this.scanDirectory(this.routesDir);
39
+ // Sort routes to ensure static routes are matched before dynamic ones
40
+ this.routes.sort((a, b) => compareRoutes(a, b));
41
+ }
42
+ catch (error) {
43
+ const errorMessage = error instanceof Error ? error.message : String(error);
44
+ throw new Error(`Failed to load routes: ${errorMessage}`);
45
+ }
46
+ }
47
+ /**
48
+ * Recursively scans the directory for route modules and adds them to the routes array.
49
+ * @param dir The current directory to scan.
50
+ * @param basePath The base path for constructing the route path.
51
+ * @throws Error if multiple dynamic folders are found at the same level or if directory access fails
52
+ */
53
+ async scanDirectory(dir, basePath = '') {
54
+ // Track if a dynamic folder has been found at this directory level
55
+ let dynamicFolderFound = false;
56
+ try {
57
+ const entries = readdirSync(dir, { withFileTypes: true });
58
+ for (const entry of entries) {
59
+ const entryPath = path.join(dir, entry.name);
60
+ const relativePath = path.join(basePath, entry.name);
61
+ if (entry.isDirectory()) {
62
+ // Handle dynamic directories (e.g., [id])
63
+ if (entry.name.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
64
+ entry.name.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END)) {
65
+ if (dynamicFolderFound) {
66
+ throw new Error(`Multiple dynamic route folders found in the same directory: '${entry.name}' conflicts with another dynamic folder in '${dir}'.`);
67
+ }
68
+ dynamicFolderFound = true;
69
+ }
70
+ await this.scanDirectory(entryPath, relativePath);
71
+ }
72
+ else if (entry.isFile() && entry.name === 'route.ts') {
73
+ await this.loadRouteModule(entryPath, relativePath);
74
+ }
75
+ }
76
+ }
77
+ catch (error) {
78
+ if (error instanceof Error) {
79
+ throw error; // Re-throw specific errors we created
80
+ }
81
+ throw new Error(`Failed to scan directory '${dir}': ${String(error)}`);
82
+ }
83
+ }
84
+ /**
85
+ * Loads a route module and adds it to the routes array
86
+ * @param entryPath Full path to the route file
87
+ * @param relativePath Relative path used to construct the route
88
+ */
89
+ async loadRouteModule(entryPath, relativePath) {
90
+ try {
91
+ // Convert file path to route path and load the module
92
+ const routePath = this.convertFilePathToRoute(relativePath);
93
+ const modulePath = path.resolve(entryPath);
94
+ const routeModule = await import(modulePath);
95
+ // Collect HTTP method handlers from the module
96
+ const handlers = {};
97
+ for (const method of HTTP_METHODS) {
98
+ if (typeof routeModule[method] === 'function') {
99
+ handlers[method] = routeModule[method];
100
+ }
101
+ }
102
+ // Create route definition
103
+ const routeDef = {
104
+ path: routePath,
105
+ handlers,
106
+ middleware: routeModule.middleware,
107
+ schema: routeModule.schema,
108
+ openapi: routeModule.openapi,
109
+ };
110
+ this.routes.push(routeDef);
111
+ }
112
+ catch (error) {
113
+ throw new Error(`Failed to load route module '${entryPath}': ${String(error)}`);
114
+ }
115
+ }
116
+ /**
117
+ * Converts a file path to a route path by processing dynamic segments,
118
+ * removing certain directory indicators, and applying a prefix if specified.
119
+ * @param filePath The file path to convert into a route path.
120
+ * @returns The converted route path string.
121
+ */
122
+ convertFilePathToRoute(filePath) {
123
+ // Remove the "route.ts" suffix
124
+ if (filePath.endsWith('route.ts')) {
125
+ filePath = filePath.slice(0, -'route.ts'.length);
126
+ }
127
+ // Split path into segments
128
+ const segments = filePath.split(path.sep);
129
+ const resultSegments = [];
130
+ for (let segment of segments) {
131
+ if (!segment)
132
+ continue; // Skip empty segments
133
+ // Skip grouping segments (e.g., (group))
134
+ if (segment.startsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_START) &&
135
+ segment.endsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_END))
136
+ continue;
137
+ // Convert dynamic segments from [param] to :param
138
+ if (segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
139
+ segment.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END)) {
140
+ const param = segment.slice(1, -1);
141
+ resultSegments.push(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX + param);
142
+ }
143
+ else {
144
+ resultSegments.push(segment);
145
+ }
146
+ }
147
+ // Construct the route with leading slash
148
+ let route = '/' + resultSegments.join('/');
149
+ // Apply prefix if provided
150
+ if (this.prefix) {
151
+ const cleanPrefixStr = cleanPrefix(this.prefix);
152
+ route = '/' + cleanPrefixStr + route;
153
+ }
154
+ // Remove trailing slash unless it's the root
155
+ if (route !== '/' && route.endsWith('/')) {
156
+ route = route.slice(0, -1);
157
+ }
158
+ return route;
159
+ }
160
+ /**
161
+ * Resolves the given request by finding a matching route and extracting dynamic parameters.
162
+ * @param request The request to resolve.
163
+ * @returns An object containing the matched route and parameters, or an empty params object if no match.
164
+ */
165
+ resolve(request) {
166
+ try {
167
+ const url = new URL(request.url);
168
+ const reqPath = normalizePath(url.pathname);
169
+ const method = request.method.toUpperCase();
170
+ for (const route of this.routes) {
171
+ const match = this.matchRoute(reqPath, route.path);
172
+ if (match && route.handlers[method]) {
173
+ return { route, params: match };
174
+ }
175
+ }
176
+ return { params: {} };
177
+ }
178
+ catch (error) {
179
+ // Return no match in case of URL parsing errors
180
+ return { params: {} };
181
+ }
182
+ }
183
+ /**
184
+ * Checks if the request path matches the route path, extracting dynamic parameters if matched.
185
+ * @param requestPath The request path to check.
186
+ * @param routePath The route path to match against.
187
+ * @returns A record of dynamic parameters if matched, otherwise null.
188
+ */
189
+ matchRoute(requestPath, routePath) {
190
+ const reqSegments = requestPath.split('/').filter(Boolean);
191
+ const routeSegments = routePath.split('/').filter(Boolean);
192
+ if (reqSegments.length !== routeSegments.length) {
193
+ return null;
194
+ }
195
+ const params = {};
196
+ for (let i = 0; i < reqSegments.length; i++) {
197
+ const rSegment = routeSegments[i];
198
+ const reqSegment = reqSegments[i];
199
+ if (rSegment.startsWith(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX)) {
200
+ const paramName = rSegment.slice(1);
201
+ params[paramName] = decodeURIComponent(reqSegment);
202
+ }
203
+ else if (rSegment !== reqSegment) {
204
+ return null;
205
+ }
206
+ }
207
+ return params;
208
+ }
209
+ }
@@ -1,12 +1,12 @@
1
- import type { Router } from "./router.js";
2
- import type { ServerOptions } from "../types/index.js";
1
+ import type { ApiRouter } from './api-router.js';
2
+ import type { ServerOptions } from '../types/index.js';
3
3
  /**
4
4
  * Generates an OpenAPI 3.0 document from the router's routes and global options.
5
5
  * @param router The router instance with loaded routes.
6
6
  * @param options Global options, including OpenAPI metadata.
7
7
  * @returns The OpenAPI document as a JavaScript object.
8
8
  */
9
- export declare function generateOpenAPIDocument(router: Router, options: ServerOptions): {
9
+ export declare function generateOpenAPIDocument(router: ApiRouter, options: ServerOptions): {
10
10
  openapi: string;
11
11
  info: {
12
12
  title: string;
@@ -1,4 +1,4 @@
1
- import { zodToJsonSchema } from "zod-to-json-schema";
1
+ import { zodToJsonSchema } from 'zod-to-json-schema';
2
2
  /**
3
3
  * Builds an array of OpenAPI 3.0 parameters based on the Zod schema.
4
4
  * For each property in the Zod schema, an OpenAPI parameter is constructed
@@ -12,14 +12,14 @@ function buildParameters(zodSchema, location) {
12
12
  const parameters = [];
13
13
  if (zodSchema &&
14
14
  zodSchema._def &&
15
- typeof zodSchema._def.shape === "function") {
15
+ typeof zodSchema._def.shape === 'function') {
16
16
  // Get the shape of the Zod schema
17
17
  const shape = zodSchema._def.shape();
18
18
  for (const key in shape) {
19
19
  // Get the definition of the field
20
20
  const fieldDef = shape[key];
21
21
  // Determine if the field is optional
22
- const isOptional = fieldDef._def.typeName === "ZodOptional";
22
+ const isOptional = fieldDef._def.typeName === 'ZodOptional';
23
23
  parameters.push({
24
24
  // Set the name of the parameter
25
25
  name: key,
@@ -28,7 +28,7 @@ function buildParameters(zodSchema, location) {
28
28
  // Set the required flag
29
29
  required: !isOptional,
30
30
  // Set the schema type
31
- schema: { type: "string" },
31
+ schema: { type: 'string' },
32
32
  // Description of the parameter
33
33
  description: `${location} parameter ${key}`,
34
34
  });
@@ -49,11 +49,11 @@ function buildRequestBody(zodSchema) {
49
49
  const jsonSchema = zodToJsonSchema(zodSchema);
50
50
  return {
51
51
  content: {
52
- "application/json": {
52
+ 'application/json': {
53
53
  schema: jsonSchema,
54
54
  },
55
55
  },
56
- description: "Request body",
56
+ description: 'Request body',
57
57
  required: true,
58
58
  };
59
59
  }
@@ -65,7 +65,7 @@ function buildRequestBody(zodSchema) {
65
65
  */
66
66
  function convertPathForOpenAPI(routePath) {
67
67
  // Replace occurrences of :param with {param}
68
- return routePath.replace(/:([a-zA-Z0-9_]+)/g, "{$1}");
68
+ return routePath.replace(/:([a-zA-Z0-9_]+)/g, '{$1}');
69
69
  }
70
70
  /**
71
71
  * Generates an OpenAPI 3.0 document from the router's routes and global options.
@@ -75,11 +75,11 @@ function convertPathForOpenAPI(routePath) {
75
75
  */
76
76
  export function generateOpenAPIDocument(router, options) {
77
77
  const openapiDoc = {
78
- openapi: "3.0.0",
78
+ openapi: '3.0.0',
79
79
  info: {
80
- title: options.title || "Burger API",
81
- description: options.description || "Burger API documentation",
82
- version: options.version || "1.0.0",
80
+ title: options.title || 'Burger API',
81
+ description: options.description || 'Burger API documentation',
82
+ version: options.version || '1.0.0',
83
83
  },
84
84
  paths: {},
85
85
  };
@@ -97,14 +97,14 @@ export function generateOpenAPIDocument(router, options) {
97
97
  const methodMeta = route.openapi?.[lowerMethod] || {};
98
98
  // Generate an operationId: e.g., "get_api_product"
99
99
  const operationId = methodMeta.operationId ||
100
- `${lowerMethod}_${route.path.replace(/[\/:]/g, "_")}`;
100
+ `${lowerMethod}_${route.path.replace(/[\/:]/g, '_')}`;
101
101
  // Build parameters for both path and query from the schema.
102
102
  let parameters = [];
103
103
  if (route.schema && route.schema[lowerMethod]) {
104
104
  const schemaDef = route.schema[lowerMethod];
105
105
  parameters = [
106
- ...buildParameters(schemaDef.params, "path"),
107
- ...buildParameters(schemaDef.query, "query"),
106
+ ...buildParameters(schemaDef.params, 'path'),
107
+ ...buildParameters(schemaDef.query, 'query'),
108
108
  ];
109
109
  }
110
110
  // Build requestBody if a body schema exists.
@@ -115,14 +115,14 @@ export function generateOpenAPIDocument(router, options) {
115
115
  openapiDoc.paths[openApiPath][lowerMethod] = {
116
116
  operationId,
117
117
  summary: methodMeta.summary || `Summary for ${method} ${route.path}`,
118
- description: methodMeta.description || "",
118
+ description: methodMeta.description || '',
119
119
  tags: methodMeta.tags || [],
120
120
  deprecated: methodMeta.deprecated || false,
121
121
  parameters: parameters,
122
122
  requestBody: requestBody,
123
123
  responses: methodMeta.responses || {
124
- "200": {
125
- description: "Successful response",
124
+ '200': {
125
+ description: 'Successful response',
126
126
  },
127
127
  },
128
128
  externalDocs: methodMeta.externalDocs || undefined,
@@ -0,0 +1,59 @@
1
+ import type { PageDefinition } from '../types/index.js';
2
+ /**
3
+ * PageRouter class for handling file-based page routing.
4
+ * Loads pages from a directory structure and matches requests to the appropriate page handlers.
5
+ * Supports dynamic segments (e.g., [id]) and uses default exports as page handlers.
6
+ */
7
+ export declare class PageRouter {
8
+ private pagesDir;
9
+ private prefix;
10
+ /** Array of loaded page definitions */
11
+ pages: PageDefinition[];
12
+ /**
13
+ * Constructor for the PageRouter class.
14
+ * @param pagesDir The directory path where page modules are located.
15
+ * @param prefix Optional prefix to prepend to all routes (e.g., "pages" becomes "/pages/...").
16
+ */
17
+ constructor(pagesDir: string, prefix?: string);
18
+ /**
19
+ * Loads page modules from the specified directory and adds them to the pages array.
20
+ * After loading, sorts the pages to prioritize static routes over dynamic ones based on specificity.
21
+ * @returns A promise that resolves when all page modules have been loaded and sorted.
22
+ */
23
+ loadPages(): Promise<void>;
24
+ /**
25
+ * Recursively scans the directory for page modules and adds them to the pages array.
26
+ * @param dir The current directory to scan.
27
+ * @param basePath The base path for constructing the route path.
28
+ */
29
+ private scanDirectory;
30
+ /**
31
+ * Converts a file path to a route path by processing dynamic segments,
32
+ * removing certain directory indicators, and applying a prefix if specified.
33
+ * @param filePath The file path to convert into a route path.
34
+ * @returns The converted route path string (before extension cleaning).
35
+ */
36
+ private convertFilePathToRoute;
37
+ /**
38
+ * Cleans a route path by handling index files and removing extensions.
39
+ * @param routePath The route path to clean
40
+ * @returns The cleaned route path
41
+ */
42
+ private cleanRoutePath;
43
+ /**
44
+ * Resolves the given request by finding a matching page and extracting dynamic parameters.
45
+ * @param request The request to resolve.
46
+ * @returns An object containing the matched page and parameters, or an empty params object if no match.
47
+ */
48
+ resolve(request: Request): {
49
+ page?: PageDefinition;
50
+ params: Record<string, string>;
51
+ };
52
+ /**
53
+ * Checks if the request path matches the page path, extracting dynamic parameters if matched.
54
+ * @param requestPath The request path to check.
55
+ * @param pagePath The page path to match against.
56
+ * @returns A record of dynamic parameters if matched, otherwise null.
57
+ */
58
+ private matchRoute;
59
+ }