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.
- package/README.md +47 -7
- package/dist/src/core/api-router.d.ts +1 -54
- package/dist/src/core/api-router.js +15 -87
- package/dist/src/core/openapi.d.ts +1 -1
- package/dist/src/core/openapi.js +1 -58
- package/dist/src/core/page-router.d.ts +1 -44
- package/dist/src/core/page-router.js +2 -73
- package/dist/src/core/server.d.ts +1 -11
- package/dist/src/core/server.js +1 -17
- package/dist/src/index.d.ts +3 -60
- package/dist/src/index.js +27 -286
- package/dist/src/middleware/validator.d.ts +1 -13
- package/dist/src/middleware/validator.js +9 -59
- package/dist/src/types/index.d.ts +73 -0
- package/dist/src/types/index.js +1 -0
- package/dist/src/utils/error.d.ts +0 -16
- package/dist/src/utils/error.js +1 -25
- package/dist/src/utils/index.d.ts +1 -18
- package/dist/src/utils/index.js +1 -23
- package/dist/src/utils/response.d.ts +0 -9
- package/dist/src/utils/response.js +0 -9
- package/dist/src/utils/routing.d.ts +1 -29
- package/dist/src/utils/routing.js +3 -41
- package/dist/src/utils/wildcard.d.ts +3 -0
- package/dist/src/utils/wildcard.js +30 -0
- package/package.json +3 -4
- package/dist/src/utils/zod-to-json.d.ts +0 -11
- package/dist/src/utils/zod-to-json.js +0 -117
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import type { BunRequest, Server } from 'bun';
|
|
2
|
+
import type { ServeOptions as BunServerOptions } from 'bun';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
export interface ServerOptions extends Omit<BunServerOptions, 'fetch' | 'port' | 'reusePort' | 'ipv6Only' | 'unix' | 'error' | 'id' | 'development'> {
|
|
5
|
+
title?: string;
|
|
6
|
+
description?: string;
|
|
7
|
+
apiDir?: string;
|
|
8
|
+
apiPrefix?: string;
|
|
9
|
+
pageDir?: string;
|
|
10
|
+
pagePrefix?: string;
|
|
11
|
+
globalMiddleware?: Middleware[];
|
|
12
|
+
version?: string;
|
|
13
|
+
debug?: boolean;
|
|
14
|
+
}
|
|
15
|
+
type DefaultRequestProperties = {
|
|
16
|
+
params?: Record<string, unknown>;
|
|
17
|
+
query?: Record<string, unknown>;
|
|
18
|
+
body?: Record<string, unknown>;
|
|
19
|
+
};
|
|
20
|
+
export interface BurgerRequest<RequestValidatedProperties extends DefaultRequestProperties = DefaultRequestProperties> extends Omit<BunRequest<string>, 'params'> {
|
|
21
|
+
params?: Record<string, string>;
|
|
22
|
+
validated: RequestValidatedProperties;
|
|
23
|
+
wildcardParams?: string[];
|
|
24
|
+
}
|
|
25
|
+
export type BurgerNext = Response | ((response: Response) => Promise<Response>) | undefined;
|
|
26
|
+
export type Middleware = ((request: BurgerRequest) => Promise<BurgerNext>) | ((request: BurgerRequest) => BurgerNext);
|
|
27
|
+
export type RequestHandler = (request: BurgerRequest) => Promise<Response> | Response;
|
|
28
|
+
export type FetchHandler = (request: Request, server?: Server) => Promise<Response> | Response;
|
|
29
|
+
export interface RouteDefinition {
|
|
30
|
+
path: string;
|
|
31
|
+
handlers: {
|
|
32
|
+
[method: string]: RequestHandler;
|
|
33
|
+
};
|
|
34
|
+
middleware?: Middleware[];
|
|
35
|
+
schema?: RouteSchema;
|
|
36
|
+
openapi?: openapi;
|
|
37
|
+
isWildcard?: boolean;
|
|
38
|
+
}
|
|
39
|
+
export type RouteSchema = {
|
|
40
|
+
[method: string]: {
|
|
41
|
+
params?: z.ZodObject<any, any>;
|
|
42
|
+
query?: z.ZodObject<any, any>;
|
|
43
|
+
body?: z.ZodObject<any, any>;
|
|
44
|
+
};
|
|
45
|
+
};
|
|
46
|
+
export type openapi = {
|
|
47
|
+
[method: string]: {
|
|
48
|
+
summary?: string;
|
|
49
|
+
description?: string;
|
|
50
|
+
tags?: string[];
|
|
51
|
+
operationId?: string;
|
|
52
|
+
deprecated?: boolean;
|
|
53
|
+
responses?: Record<string, any>;
|
|
54
|
+
externalDocs?: {
|
|
55
|
+
description?: string;
|
|
56
|
+
url?: string;
|
|
57
|
+
};
|
|
58
|
+
};
|
|
59
|
+
};
|
|
60
|
+
export interface PageDefinition {
|
|
61
|
+
path: string;
|
|
62
|
+
handler: RequestHandler;
|
|
63
|
+
middleware?: Middleware[];
|
|
64
|
+
}
|
|
65
|
+
export interface TrieNode {
|
|
66
|
+
children: Map<string, TrieNode>;
|
|
67
|
+
paramChild?: TrieNode;
|
|
68
|
+
paramName?: string;
|
|
69
|
+
wildcardChild?: TrieNode;
|
|
70
|
+
isWildcard?: boolean;
|
|
71
|
+
route?: RouteDefinition;
|
|
72
|
+
}
|
|
73
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
@@ -1,17 +1 @@
|
|
|
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
1
|
export declare function errorResponse(error: any, req: Request, debug: boolean): Response;
|
package/dist/src/utils/error.js
CHANGED
|
@@ -1,56 +1,32 @@
|
|
|
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
|
-
*/
|
|
1
|
+
import { normalizePath } from './index';
|
|
18
2
|
export function errorResponse(error, req, debug) {
|
|
19
|
-
// Extract request details
|
|
20
3
|
const method = req.method;
|
|
21
4
|
const url = req.url;
|
|
22
5
|
const logPrefix = `[${method} ${url}]`;
|
|
23
|
-
// Log detailed error context
|
|
24
6
|
console.error(`${logPrefix} Error:`, error);
|
|
25
7
|
const acceptHeader = req.headers.get('accept') || '';
|
|
26
8
|
if (acceptHeader.includes('text/html') && debug) {
|
|
27
9
|
const body = `<!doctype html><html lang="en"><meta charset="UTF-8"><title>Error Occurred - BurgerAPI</title><style>body{margin:0;padding:0;background-color:#f4f4f4;font-family:Nunito,sans-serif;color:#333}.whoops-container{width:80%;margin:5% auto;background:#fff;border-radius:8px;box-shadow:0 4px 12px rgba(0,0,0,.15);overflow:hidden}.whoops-header{background-color:#e74c3c;color:#fff;padding:20px;display:flex;align-items:center;justify-content:space-between}.whoops-header .title-container{display:flex;align-items:center}.whoops-header .title{font-size:1.5em;margin-left:10px}.whoops-header .debug-mode{font-weight:600;display:flex;align-items:center;padding:10px;background-color:#fff;color:#e74c3c;box-shadow:0 4px 12px rgba(0,0,0,.15);border-radius:8px}.whoops-header .debug-mode .fa-check-circle{color:#28a745;margin-right:5px;font-size:1.2em}.whoops-content{padding:2em}.tag{font-weight:600;color:#4a5568;background-color:#edf2f7;padding:8px 15px;border-radius:6px;display:inline-block;font-size:14px}.error-message{font-size:1.25em;line-height:1.6;margin-bottom:1.5em;color:#2d3748}h2{color:#e3342f;font-size:1.5em;margin-bottom:.8em;border-bottom:1px solid #edf2f7;padding-bottom:.5em}pre{background:#f9fafc;border-left:4px solid #e3342f;padding:1.5em;border-radius:4px;font-family:"Source Code Pro",Menlo,Monaco,Consolas,"Courier New",monospace;font-size:1em;line-height:1.6;overflow-x:auto;color:#4a5568}.footer{text-align:center;padding-top:25px;font-size:.9em;color:#718096;border-top:1px solid #edf2f7}.error-icon{font-size:2em}.request-info{display:flex;justify-content:space-between;align-items:center}</style><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"rel="stylesheet"><div class="whoops-container"><div class="whoops-header"><div class="title-container"><i class="fas error-icon fa-exclamation-triangle"></i><div class="title">Whoops! Something went wrong</div></div><div class="debug-mode"><i class="fas fa-check-circle"></i> Debug Mode Enabled</div></div><div class="whoops-content"><div class="request-info"><div><strong>Request:</strong> ${method} ${url}</div><div class="tag">${error.stack?.split('\n')[0].split(':')[0]}</div></div><p class="error-message">${error.message}<h2>Stack Trace</h2><pre>${error.stack || 'No stack trace available'}</pre><div class="footer">“It’s not a bug, it’s an undocumented feature.” — Anonymous</div></div></div>
|
|
28
10
|
`;
|
|
29
|
-
// Return the html response
|
|
30
11
|
return new Response(body, {
|
|
31
12
|
status: 500,
|
|
32
13
|
headers: { 'Content-Type': 'text/html' },
|
|
33
14
|
});
|
|
34
15
|
}
|
|
35
16
|
else if (debug) {
|
|
36
|
-
// Log detailed error context
|
|
37
17
|
console.error(`${logPrefix} Error:`, error);
|
|
38
|
-
// Create a JSON response
|
|
39
18
|
const body = JSON.stringify({
|
|
40
19
|
request: `${method} ${url}`,
|
|
41
20
|
error: error instanceof Error ? error.message : 'Unknown error',
|
|
42
21
|
stack: error instanceof Error ? normalizePath(error.stack || '') : '',
|
|
43
22
|
});
|
|
44
|
-
// Return the JSON response
|
|
45
23
|
return new Response(body, {
|
|
46
24
|
status: 500,
|
|
47
25
|
headers: { 'Content-Type': 'application/json' },
|
|
48
26
|
});
|
|
49
27
|
}
|
|
50
28
|
else {
|
|
51
|
-
// Log detailed error context
|
|
52
29
|
console.error(`${logPrefix} Error:`, error);
|
|
53
|
-
// Return a plain text response
|
|
54
30
|
return new Response('Internal Server Error', { status: 500 });
|
|
55
31
|
}
|
|
56
32
|
}
|
|
@@ -1,21 +1,4 @@
|
|
|
1
|
-
export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, collectRoutes, } from './routing
|
|
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
|
-
*/
|
|
1
|
+
export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, collectRoutes, } from './routing';
|
|
8
2
|
export declare function setDir(directory: string, path: string): string;
|
|
9
|
-
/**
|
|
10
|
-
* Removes leading and trailing slashes from the given prefix.
|
|
11
|
-
* @param prefix the prefix to clean
|
|
12
|
-
* @returns the cleaned prefix
|
|
13
|
-
*/
|
|
14
3
|
export declare function cleanPrefix(prefix: string): string;
|
|
15
|
-
/**
|
|
16
|
-
* Normalizes a file path by replacing multiple slashes with a single slash
|
|
17
|
-
* and removing any trailing slash, unless the path is the root.
|
|
18
|
-
* @param path The file path to normalize.
|
|
19
|
-
* @returns The normalized file path.
|
|
20
|
-
*/
|
|
21
4
|
export declare function normalizePath(path: string): string;
|
package/dist/src/utils/index.js
CHANGED
|
@@ -1,41 +1,19 @@
|
|
|
1
1
|
import { resolve } from 'path';
|
|
2
|
-
|
|
3
|
-
export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, collectRoutes, } from './routing.js';
|
|
4
|
-
/**
|
|
5
|
-
* Resolves the given path to the specified directory.
|
|
6
|
-
* @param directory the directory to resolve to
|
|
7
|
-
* @param path the path to resolve
|
|
8
|
-
* @returns the resolved path
|
|
9
|
-
*/
|
|
2
|
+
export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, collectRoutes, } from './routing';
|
|
10
3
|
export function setDir(directory, path) {
|
|
11
4
|
return resolve(directory, path);
|
|
12
5
|
}
|
|
13
|
-
/**
|
|
14
|
-
* Removes leading and trailing slashes from the given prefix.
|
|
15
|
-
* @param prefix the prefix to clean
|
|
16
|
-
* @returns the cleaned prefix
|
|
17
|
-
*/
|
|
18
6
|
export function cleanPrefix(prefix) {
|
|
19
|
-
// Remove all slashes from the beginning
|
|
20
7
|
while (prefix.startsWith('/')) {
|
|
21
8
|
prefix = prefix.slice(1);
|
|
22
9
|
}
|
|
23
|
-
// Remove all slashes from the end
|
|
24
10
|
while (prefix.endsWith('/')) {
|
|
25
11
|
prefix = prefix.slice(0, -1);
|
|
26
12
|
}
|
|
27
13
|
return prefix;
|
|
28
14
|
}
|
|
29
|
-
/**
|
|
30
|
-
* Normalizes a file path by replacing multiple slashes with a single slash
|
|
31
|
-
* and removing any trailing slash, unless the path is the root.
|
|
32
|
-
* @param path The file path to normalize.
|
|
33
|
-
* @returns The normalized file path.
|
|
34
|
-
*/
|
|
35
15
|
export function normalizePath(path) {
|
|
36
|
-
// Replace multiple slashes with a single slash
|
|
37
16
|
let normalized = path.replace(/\/+/g, '/');
|
|
38
|
-
// Remove trailing slash if it's not the root
|
|
39
17
|
if (normalized.length > 1 && normalized.endsWith('/')) {
|
|
40
18
|
normalized = normalized.slice(0, -1);
|
|
41
19
|
}
|
|
@@ -1,12 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The method not allowed response
|
|
3
|
-
*/
|
|
4
1
|
export declare const METHOD_NOT_ALLOWED: Response;
|
|
5
|
-
/**
|
|
6
|
-
* The not found response
|
|
7
|
-
*/
|
|
8
2
|
export declare const NOT_FOUND: Response;
|
|
9
|
-
/**
|
|
10
|
-
* The OpenAPI error response
|
|
11
|
-
*/
|
|
12
3
|
export declare const OPENAPI_ERROR: Response;
|
|
@@ -1,16 +1,7 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The method not allowed response
|
|
3
|
-
*/
|
|
4
1
|
export const METHOD_NOT_ALLOWED = new Response('Method Not Allowed', {
|
|
5
2
|
status: 405,
|
|
6
3
|
});
|
|
7
|
-
/**
|
|
8
|
-
* The not found response
|
|
9
|
-
*/
|
|
10
4
|
export const NOT_FOUND = new Response('Not Found', { status: 404 });
|
|
11
|
-
/**
|
|
12
|
-
* The OpenAPI error response
|
|
13
|
-
*/
|
|
14
5
|
export const OPENAPI_ERROR = Response.json({
|
|
15
6
|
error: 'API Router not configured',
|
|
16
7
|
message: 'Please provide an apiDir option when initializing the Burger instance to enable OpenAPI documentation.',
|
|
@@ -1,7 +1,4 @@
|
|
|
1
|
-
import type { PageDefinition, RouteDefinition, TrieNode } from '
|
|
2
|
-
/**
|
|
3
|
-
* Constants for route handling.
|
|
4
|
-
*/
|
|
1
|
+
import type { PageDefinition, RouteDefinition, TrieNode } from '../types/index';
|
|
5
2
|
export declare const ROUTE_CONSTANTS: {
|
|
6
3
|
SUPPORTED_PAGE_EXTENSIONS: string[];
|
|
7
4
|
PAGE_INDEX_FILES: string[];
|
|
@@ -14,32 +11,7 @@ export declare const ROUTE_CONSTANTS: {
|
|
|
14
11
|
WILDCARD_SIMPLE: string;
|
|
15
12
|
WILDCARD_START: string;
|
|
16
13
|
};
|
|
17
|
-
/**
|
|
18
|
-
* Supported HTTP methods
|
|
19
|
-
*/
|
|
20
14
|
export declare const HTTP_METHODS: string[];
|
|
21
|
-
/**
|
|
22
|
-
* Calculates the specificity of a route path based on the number of static segments.
|
|
23
|
-
* Static segments increase the score, while dynamic segments (:param) do not.
|
|
24
|
-
* Wildcard segments (*) have the lowest specificity (highest penalty).
|
|
25
|
-
* @param path The route path to evaluate.
|
|
26
|
-
* @returns The specificity score (higher means more static segments, lower priority for wildcard).
|
|
27
|
-
*/
|
|
28
15
|
export declare const getRouteSpecificity: (path: string) => number;
|
|
29
|
-
/**
|
|
30
|
-
* Compares two routes for sorting, prioritizing those with higher specificity (more static segments).
|
|
31
|
-
* Route prioritization: Static > Dynamic > Wildcard.
|
|
32
|
-
* If specificity is equal, sorts alphabetically by path.
|
|
33
|
-
* @param a The first route to compare.
|
|
34
|
-
* @param b The second route to compare.
|
|
35
|
-
* @returns Negative if a comes before b, positive if b comes before a, zero if equal.
|
|
36
|
-
*/
|
|
37
16
|
export declare const compareRoutes: (a: PageDefinition | RouteDefinition, b: PageDefinition | RouteDefinition) => number;
|
|
38
|
-
/**
|
|
39
|
-
* Collects all routes from the trie and returns them as an array of RouteDefinition objects.
|
|
40
|
-
* @param node The current node in the trie.
|
|
41
|
-
* @param currentPath The current path being traversed.
|
|
42
|
-
* @param routes The array of collected routes.
|
|
43
|
-
* @returns An array of RouteDefinition objects.
|
|
44
|
-
*/
|
|
45
17
|
export declare function collectRoutes(node: TrieNode, currentPath?: string, routes?: RouteDefinition[]): RouteDefinition[];
|
|
@@ -1,26 +1,15 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Constants for route handling.
|
|
3
|
-
*/
|
|
4
1
|
export const ROUTE_CONSTANTS = {
|
|
5
|
-
// Supported page extensions
|
|
6
2
|
SUPPORTED_PAGE_EXTENSIONS: ['.tsx', '.html'],
|
|
7
|
-
// Page index files
|
|
8
3
|
PAGE_INDEX_FILES: ['index.tsx', 'index.html'],
|
|
9
|
-
// Dynamic route constants
|
|
10
4
|
DYNAMIC_SEGMENT_PREFIX: ':',
|
|
11
5
|
DYNAMIC_FOLDER_START: '[',
|
|
12
6
|
DYNAMIC_FOLDER_END: ']',
|
|
13
|
-
// Grouping folder constants
|
|
14
7
|
GROUPING_FOLDER_START: '(',
|
|
15
8
|
GROUPING_FOLDER_END: ')',
|
|
16
|
-
// Wildcard route constants
|
|
17
9
|
WILDCARD_SEGMENT_PREFIX: '*',
|
|
18
10
|
WILDCARD_SIMPLE: '[...]',
|
|
19
11
|
WILDCARD_START: '[...',
|
|
20
12
|
};
|
|
21
|
-
/**
|
|
22
|
-
* Supported HTTP methods
|
|
23
|
-
*/
|
|
24
13
|
export const HTTP_METHODS = [
|
|
25
14
|
'GET',
|
|
26
15
|
'POST',
|
|
@@ -30,32 +19,17 @@ export const HTTP_METHODS = [
|
|
|
30
19
|
'HEAD',
|
|
31
20
|
'OPTIONS',
|
|
32
21
|
];
|
|
33
|
-
/**
|
|
34
|
-
* Calculates the specificity of a route path based on the number of static segments.
|
|
35
|
-
* Static segments increase the score, while dynamic segments (:param) do not.
|
|
36
|
-
* Wildcard segments (*) have the lowest specificity (highest penalty).
|
|
37
|
-
* @param path The route path to evaluate.
|
|
38
|
-
* @returns The specificity score (higher means more static segments, lower priority for wildcard).
|
|
39
|
-
*/
|
|
40
22
|
export const getRouteSpecificity = (path) => {
|
|
41
23
|
const segments = path.split('/').filter(Boolean);
|
|
42
24
|
return segments.reduce((score, segment) => {
|
|
43
25
|
if (segment.startsWith(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX)) {
|
|
44
|
-
return score + 1000;
|
|
26
|
+
return score + 1000;
|
|
45
27
|
}
|
|
46
28
|
return segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX)
|
|
47
|
-
? score + 100
|
|
48
|
-
: score + 1;
|
|
29
|
+
? score + 100
|
|
30
|
+
: score + 1;
|
|
49
31
|
}, 0);
|
|
50
32
|
};
|
|
51
|
-
/**
|
|
52
|
-
* Compares two routes for sorting, prioritizing those with higher specificity (more static segments).
|
|
53
|
-
* Route prioritization: Static > Dynamic > Wildcard.
|
|
54
|
-
* If specificity is equal, sorts alphabetically by path.
|
|
55
|
-
* @param a The first route to compare.
|
|
56
|
-
* @param b The second route to compare.
|
|
57
|
-
* @returns Negative if a comes before b, positive if b comes before a, zero if equal.
|
|
58
|
-
*/
|
|
59
33
|
export const compareRoutes = (a, b) => {
|
|
60
34
|
const aSpecificity = getRouteSpecificity(a.path);
|
|
61
35
|
const bSpecificity = getRouteSpecificity(b.path);
|
|
@@ -65,33 +39,21 @@ export const compareRoutes = (a, b) => {
|
|
|
65
39
|
return 1;
|
|
66
40
|
return a.path.localeCompare(b.path);
|
|
67
41
|
};
|
|
68
|
-
/**
|
|
69
|
-
* Collects all routes from the trie and returns them as an array of RouteDefinition objects.
|
|
70
|
-
* @param node The current node in the trie.
|
|
71
|
-
* @param currentPath The current path being traversed.
|
|
72
|
-
* @param routes The array of collected routes.
|
|
73
|
-
* @returns An array of RouteDefinition objects.
|
|
74
|
-
*/
|
|
75
42
|
export function collectRoutes(node, currentPath = '', routes = []) {
|
|
76
|
-
// If this node has a route definition, add it
|
|
77
43
|
if (node.route) {
|
|
78
44
|
routes.push({
|
|
79
45
|
...node.route,
|
|
80
46
|
path: currentPath,
|
|
81
47
|
});
|
|
82
48
|
}
|
|
83
|
-
// Traverse static children
|
|
84
49
|
node.children.forEach((child, segment) => {
|
|
85
50
|
collectRoutes(child, `${currentPath}/${segment}`, routes);
|
|
86
51
|
});
|
|
87
|
-
// Traverse dynamic child if exists
|
|
88
52
|
if (node.paramChild) {
|
|
89
53
|
const paramPath = `${currentPath}/:${node.paramChild.paramName}`;
|
|
90
54
|
collectRoutes(node.paramChild, paramPath, routes);
|
|
91
55
|
}
|
|
92
|
-
// Traverse wildcard child if exists (lowest priority)
|
|
93
56
|
if (node.wildcardChild) {
|
|
94
|
-
// const wildcardPath = `${currentPath}/${node.wildcardChild.wildcardParamName}`;
|
|
95
57
|
const wildcardPath = `${currentPath}/${ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX}`;
|
|
96
58
|
collectRoutes(node.wildcardChild, wildcardPath, routes);
|
|
97
59
|
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export function extractPathnameFromUrl(url) {
|
|
2
|
+
const protocolEnd = url.indexOf('://');
|
|
3
|
+
const pathStart = url.indexOf('/', protocolEnd + 3);
|
|
4
|
+
const pathEnd = url.indexOf('?', pathStart);
|
|
5
|
+
return pathEnd === -1
|
|
6
|
+
? url.substring(pathStart)
|
|
7
|
+
: url.substring(pathStart, pathEnd);
|
|
8
|
+
}
|
|
9
|
+
export function extractWildcardParams(request, pathname, baseSegmentCount) {
|
|
10
|
+
if (baseSegmentCount === 0) {
|
|
11
|
+
request.wildcardParams = pathname.split('/').filter(Boolean);
|
|
12
|
+
}
|
|
13
|
+
else {
|
|
14
|
+
const wildcardParams = [];
|
|
15
|
+
let segmentCount = 0;
|
|
16
|
+
let start = pathname[0] === '/' ? 1 : 0;
|
|
17
|
+
for (let i = start; i <= pathname.length; i++) {
|
|
18
|
+
if (i === pathname.length || pathname[i] === '/') {
|
|
19
|
+
if (i > start) {
|
|
20
|
+
if (segmentCount >= baseSegmentCount) {
|
|
21
|
+
wildcardParams.push(pathname.substring(start, i));
|
|
22
|
+
}
|
|
23
|
+
segmentCount++;
|
|
24
|
+
}
|
|
25
|
+
start = i + 1;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
request.wildcardParams = wildcardParams;
|
|
29
|
+
}
|
|
30
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "burger-api",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
4
4
|
"author": "Isfhan Ahmed",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"module": "dist/src/index.js",
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
],
|
|
11
11
|
"scripts": {
|
|
12
12
|
"typecheck": "tsc --noEmit",
|
|
13
|
-
"build": "tsc --project tsconfig.build.json
|
|
13
|
+
"build": "tsc --project tsconfig.build.json",
|
|
14
14
|
"prepare": "bun run build",
|
|
15
15
|
"test": "bun test",
|
|
16
16
|
"dev": "bun run examples/file-base-static-page-routing-app/index.ts"
|
|
@@ -81,8 +81,7 @@
|
|
|
81
81
|
"zod": "^4.0.17"
|
|
82
82
|
},
|
|
83
83
|
"devDependencies": {
|
|
84
|
-
"@types/bun": "latest"
|
|
85
|
-
"tsc-alias": "^1.8.16"
|
|
84
|
+
"@types/bun": "latest"
|
|
86
85
|
},
|
|
87
86
|
"peerDependencies": {
|
|
88
87
|
"typescript": "^5.7.3"
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Simple Zod to JSON Schema converter for Zod 4.x
|
|
3
|
-
* This utility converts Zod schemas to JSON Schema format
|
|
4
|
-
* for use in OpenAPI documentation generation
|
|
5
|
-
*/
|
|
6
|
-
/**
|
|
7
|
-
* Converts a Zod schema to JSON Schema format
|
|
8
|
-
* @param schema - The Zod schema to convert
|
|
9
|
-
* @returns JSON Schema object
|
|
10
|
-
*/
|
|
11
|
-
export declare function zodToJsonSchema(schema: any): any;
|
|
@@ -1,117 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Simple Zod to JSON Schema converter for Zod 4.x
|
|
3
|
-
* This utility converts Zod schemas to JSON Schema format
|
|
4
|
-
* for use in OpenAPI documentation generation
|
|
5
|
-
*/
|
|
6
|
-
/**
|
|
7
|
-
* Converts a Zod schema to JSON Schema format
|
|
8
|
-
* @param schema - The Zod schema to convert
|
|
9
|
-
* @returns JSON Schema object
|
|
10
|
-
*/
|
|
11
|
-
export function zodToJsonSchema(schema) {
|
|
12
|
-
if (!schema) {
|
|
13
|
-
return { type: 'string' };
|
|
14
|
-
}
|
|
15
|
-
// Simple type detection based on schema properties
|
|
16
|
-
try {
|
|
17
|
-
// Check if it's a string schema
|
|
18
|
-
if (schema._def?.typeName === 'ZodString') {
|
|
19
|
-
return { type: 'string' };
|
|
20
|
-
}
|
|
21
|
-
// Check if it's a number schema
|
|
22
|
-
if (schema._def?.typeName === 'ZodNumber') {
|
|
23
|
-
return { type: 'number' };
|
|
24
|
-
}
|
|
25
|
-
// Check if it's a boolean schema
|
|
26
|
-
if (schema._def?.typeName === 'ZodBoolean') {
|
|
27
|
-
return { type: 'boolean' };
|
|
28
|
-
}
|
|
29
|
-
// Check if it's an array schema
|
|
30
|
-
if (schema._def?.typeName === 'ZodArray') {
|
|
31
|
-
return {
|
|
32
|
-
type: 'array',
|
|
33
|
-
items: { type: 'string' } // Default to string items
|
|
34
|
-
};
|
|
35
|
-
}
|
|
36
|
-
// Check if it's an object schema
|
|
37
|
-
if (schema._def?.typeName === 'ZodObject') {
|
|
38
|
-
const objectSchema = {
|
|
39
|
-
type: 'object',
|
|
40
|
-
properties: {},
|
|
41
|
-
required: []
|
|
42
|
-
};
|
|
43
|
-
// Try to get the shape
|
|
44
|
-
let shape = {};
|
|
45
|
-
if (schema.shape) {
|
|
46
|
-
shape = typeof schema.shape === 'function' ? schema.shape() : schema.shape;
|
|
47
|
-
}
|
|
48
|
-
for (const [key, value] of Object.entries(shape)) {
|
|
49
|
-
const fieldDef = value;
|
|
50
|
-
objectSchema.properties[key] = { type: 'string' }; // Default to string
|
|
51
|
-
// Check if field is optional
|
|
52
|
-
if (fieldDef._def?.typeName !== 'ZodOptional') {
|
|
53
|
-
objectSchema.required.push(key);
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
return objectSchema;
|
|
57
|
-
}
|
|
58
|
-
// Check if it's an optional schema
|
|
59
|
-
if (schema._def?.typeName === 'ZodOptional') {
|
|
60
|
-
return { type: 'string' };
|
|
61
|
-
}
|
|
62
|
-
// Check if it's a nullable schema
|
|
63
|
-
if (schema._def?.typeName === 'ZodNullable') {
|
|
64
|
-
return {
|
|
65
|
-
oneOf: [
|
|
66
|
-
{ type: 'string' },
|
|
67
|
-
{ type: 'null' }
|
|
68
|
-
]
|
|
69
|
-
};
|
|
70
|
-
}
|
|
71
|
-
// Check if it's a union schema
|
|
72
|
-
if (schema._def?.typeName === 'ZodUnion') {
|
|
73
|
-
return {
|
|
74
|
-
oneOf: [
|
|
75
|
-
{ type: 'string' },
|
|
76
|
-
{ type: 'number' }
|
|
77
|
-
]
|
|
78
|
-
};
|
|
79
|
-
}
|
|
80
|
-
// Check if it's an enum schema
|
|
81
|
-
if (schema._def?.typeName === 'ZodEnum') {
|
|
82
|
-
try {
|
|
83
|
-
const values = schema._def.values || [];
|
|
84
|
-
return {
|
|
85
|
-
type: 'string',
|
|
86
|
-
enum: values
|
|
87
|
-
};
|
|
88
|
-
}
|
|
89
|
-
catch {
|
|
90
|
-
return { type: 'string' };
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
// Check if it's a literal schema
|
|
94
|
-
if (schema._def?.typeName === 'ZodLiteral') {
|
|
95
|
-
try {
|
|
96
|
-
const value = schema._def.value;
|
|
97
|
-
return {
|
|
98
|
-
type: typeof value,
|
|
99
|
-
const: value
|
|
100
|
-
};
|
|
101
|
-
}
|
|
102
|
-
catch {
|
|
103
|
-
return { type: 'string' };
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
// Check if it's a default schema
|
|
107
|
-
if (schema._def?.typeName === 'ZodDefault') {
|
|
108
|
-
return { type: 'string' };
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
catch (error) {
|
|
112
|
-
// If any error occurs, fall back to string type
|
|
113
|
-
console.warn('Error processing Zod schema:', error);
|
|
114
|
-
}
|
|
115
|
-
// Fallback for unknown types
|
|
116
|
-
return { type: 'string' };
|
|
117
|
-
}
|