burger-api 0.2.2 → 0.3.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
@@ -4,8 +4,8 @@
4
4
 
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
- [![Bun](https://img.shields.io/badge/Bun-1.2.4-black?logo=bun)](https://bun.sh)
8
- [![Version](https://img.shields.io/badge/version-0.2.0-green.svg)](https://github.com/isfhan/burger-api/releases)
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)
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,13 +59,13 @@ burger-api is built to offer a robust developer experience through:
59
59
 
60
60
  ## 📣 Changelog
61
61
 
62
- ### Latest Version: 0.2.0 (April 26, 2025)
62
+ ### Latest Version: 0.3.0 (August 15, 2025)
63
63
 
64
- - ⚡ **Performance & Core Improvements:**
65
- - Optimized framework core and improved middleware handling
66
- - Enhanced OpenAPI documentation and route tracking
67
- - Updated ID preprocessing logic in schema validation
68
- - Improved type definitions across the framework
64
+ - 🔧 **Updated Zod to version 4:**
65
+ - Updated Zod version from 3.x to 4.x
66
+ - Updated built-in request validation middleware to use Zod 4
67
+ - Updated and better request validation middleware error handling
68
+ - Removed Zod-to-json-schema dependency and use Zod 4 directly
69
69
 
70
70
  For a complete list of changes, please check the [Changelog](CHANGELOG.md) file.
71
71
 
@@ -2,7 +2,7 @@
2
2
  import { readdir } from 'fs/promises';
3
3
  import * as path from 'path';
4
4
  // Import utils
5
- import { cleanPrefix, normalizePath, ROUTE_CONSTANTS, HTTP_METHODS, } from '../utils/index.js';
5
+ import { cleanPrefix, normalizePath, ROUTE_CONSTANTS, HTTP_METHODS, } from '@utils';
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.
@@ -1,4 +1,4 @@
1
- import { zodToJsonSchema } from 'zod-to-json-schema';
1
+ import { zodToJsonSchema } from '../utils/zod-to-json.js';
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
@@ -46,6 +46,7 @@ function buildParameters(zodSchema, location) {
46
46
  function buildRequestBody(zodSchema) {
47
47
  if (!zodSchema)
48
48
  return undefined;
49
+ // Use our custom Zod to JSON schema converter
49
50
  const jsonSchema = zodToJsonSchema(zodSchema);
50
51
  return {
51
52
  content: {
@@ -2,7 +2,7 @@
2
2
  import { readdirSync } from 'fs';
3
3
  import * as path from 'path';
4
4
  // Import utils
5
- import { cleanPrefix, normalizePath, compareRoutes, ROUTE_CONSTANTS, } from '../utils/index.js';
5
+ import { cleanPrefix, normalizePath, compareRoutes, ROUTE_CONSTANTS, } from '@utils';
6
6
  /**
7
7
  * PageRouter class for handling file-based page routing.
8
8
  * Loads pages from a directory structure and matches requests to the appropriate page handlers.
@@ -1,7 +1,7 @@
1
1
  // Import stuff from Bun
2
2
  import { serve } from 'bun';
3
3
  // Import stuff from utils
4
- import { errorResponse } from '../utils/error.js';
4
+ import { errorResponse } from '@utils/error.js';
5
5
  export class Server {
6
6
  options;
7
7
  server = null;
@@ -73,5 +73,5 @@ export declare class Burger {
73
73
  */
74
74
  serve(port?: number, cb?: () => void): Promise<void>;
75
75
  }
76
- export { setDir } from './utils/index.js';
76
+ export { setDir } from '@utils';
77
77
  export type { ServerOptions, RequestHandler, BurgerRequest, BurgerNext, Middleware, openapi, } from '@burgerTypes';
package/dist/src/index.js CHANGED
@@ -1,14 +1,14 @@
1
1
  // Import stuff from core
2
- import { Server } from './core/server.js';
3
- import { ApiRouter } from './core/api-router.js';
4
- import { PageRouter } from './core/page-router.js';
5
- import { generateOpenAPIDocument } from './core/openapi.js';
6
- import { swaggerHtml } from './core/swagger-ui.js';
2
+ import { Server } from '@core/server.js';
3
+ import { ApiRouter } from '@core/api-router.js';
4
+ import { PageRouter } from '@core/page-router.js';
5
+ import { generateOpenAPIDocument } from '@core/openapi.js';
6
+ import { swaggerHtml } from '@core/swagger-ui.js';
7
7
  // Import utils
8
- import { collectRoutes } from './utils/index.js';
9
- import { METHOD_NOT_ALLOWED, NOT_FOUND, OPENAPI_ERROR } from './utils/response';
8
+ import { collectRoutes } from '@utils';
9
+ import { METHOD_NOT_ALLOWED, NOT_FOUND, OPENAPI_ERROR } from '@utils/response';
10
10
  // Import middleware
11
- import { createValidationMiddleware } from './middleware/validator.js';
11
+ import { createValidationMiddleware } from '@middleware/validator.js';
12
12
  export class Burger {
13
13
  options;
14
14
  /**
@@ -284,4 +284,4 @@ export class Burger {
284
284
  }
285
285
  }
286
286
  // Export utils
287
- export { setDir } from './utils/index.js';
287
+ export { setDir } from '@utils';
@@ -1,4 +1,4 @@
1
- import { normalizePath } from './index.js';
1
+ import { normalizePath } from '@utils';
2
2
  /**
3
3
  * Generates an HTTP error response based on the request's "Accept" header.
4
4
  *
@@ -1,4 +1,4 @@
1
- export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, collectRoutes, } from './routing.js';
1
+ export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, collectRoutes, } from '@utils/routing.js';
2
2
  /**
3
3
  * Resolves the given path to the specified directory.
4
4
  * @param directory the directory to resolve to
@@ -1,6 +1,6 @@
1
1
  import { resolve } from 'path';
2
2
  // Export constants
3
- export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, collectRoutes, } from './routing.js';
3
+ export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, collectRoutes, } from '@utils/routing.js';
4
4
  /**
5
5
  * Resolves the given path to the specified directory.
6
6
  * @param directory the directory to resolve to
@@ -0,0 +1,11 @@
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;
@@ -0,0 +1,117 @@
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
+ }
package/package.json CHANGED
@@ -1,90 +1,89 @@
1
- {
2
- "name": "burger-api",
3
- "version": "0.2.2",
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": "^3.24.3",
81
- "zod-to-json-schema": "^3.24.5"
82
- },
83
- "devDependencies": {
84
- "@types/bun": "latest",
85
- "tsc-alias": "^1.8.15"
86
- },
87
- "peerDependencies": {
88
- "typescript": "^5.7.3"
89
- }
1
+ {
2
+ "name": "burger-api",
3
+ "version": "0.3.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
+ }
90
89
  }
@@ -1,40 +0,0 @@
1
- export declare class HttpRequest {
2
- private _request;
3
- private _query?;
4
- /**
5
- * Creates a new HttpRequest object from the given Request object.
6
- * @param request - The Request object to wrap.
7
- */
8
- constructor(request: Request);
9
- /**
10
- * Retrieves the query parameters from the request URL.
11
- * Initializes the query parameters if they are not already set.
12
- * @returns The URLSearchParams object containing the query parameters.
13
- */
14
- get query(): URLSearchParams;
15
- /**
16
- * Gets the URL of the request.
17
- * @returns The URL as a string.
18
- */
19
- get url(): string;
20
- /**
21
- * Gets the HTTP method of the request.
22
- * @returns The HTTP method as a string.
23
- */
24
- get method(): string;
25
- /**
26
- * Gets the headers of the request.
27
- * @returns The headers as a Headers object.
28
- */
29
- get headers(): Headers;
30
- /**
31
- * Gets the body of the request as JSON.
32
- * @returns The body as a Promise of the parsed JSON.
33
- */
34
- json<T = any>(): Promise<T>;
35
- /**
36
- * Returns the original Request object.
37
- * @returns The original Request object.
38
- */
39
- get original(): Request;
40
- }
@@ -1,58 +0,0 @@
1
- export class HttpRequest {
2
- _request;
3
- _query;
4
- /**
5
- * Creates a new HttpRequest object from the given Request object.
6
- * @param request - The Request object to wrap.
7
- */
8
- constructor(request) {
9
- this._request = request;
10
- this._query = new URL(request.url).searchParams;
11
- }
12
- /**
13
- * Retrieves the query parameters from the request URL.
14
- * Initializes the query parameters if they are not already set.
15
- * @returns The URLSearchParams object containing the query parameters.
16
- */
17
- get query() {
18
- if (!this._query) {
19
- this._query = new URL(this._request.url).searchParams;
20
- }
21
- return this._query;
22
- }
23
- /**
24
- * Gets the URL of the request.
25
- * @returns The URL as a string.
26
- */
27
- get url() {
28
- return this._request.url;
29
- }
30
- /**
31
- * Gets the HTTP method of the request.
32
- * @returns The HTTP method as a string.
33
- */
34
- get method() {
35
- return this._request.method;
36
- }
37
- /**
38
- * Gets the headers of the request.
39
- * @returns The headers as a Headers object.
40
- */
41
- get headers() {
42
- return this._request.headers;
43
- }
44
- /**
45
- * Gets the body of the request as JSON.
46
- * @returns The body as a Promise of the parsed JSON.
47
- */
48
- async json() {
49
- return this._request.json();
50
- }
51
- /**
52
- * Returns the original Request object.
53
- * @returns The original Request object.
54
- */
55
- get original() {
56
- return this._request;
57
- }
58
- }
@@ -1,92 +0,0 @@
1
- export declare class HttpResponse {
2
- /**
3
- * The status code of the response, which defaults to 200 (OK). This
4
- * property can be modified before calling build() to construct the
5
- * Response object.
6
- */
7
- private _status;
8
- /**
9
- * The headers of the response, which can be modified before calling build()
10
- * to construct the Response object.
11
- */
12
- private _headers;
13
- /**
14
- * The body of the response, which can be any valid BodyInit type or null.
15
- */
16
- private _body;
17
- /**
18
- * Set a header on the response.
19
- * @param name - The header name.
20
- * @param value - The header value.
21
- * @returns The response object.
22
- */
23
- header(name: string, value: string): this;
24
- /**
25
- * Remove a header from the response.
26
- * @param name - The header name.
27
- * @returns The response object.
28
- */
29
- removeHeader(name: string): this;
30
- /**
31
- * Sets the HTTP status code of the response.
32
- * @param status - The status code.
33
- * @returns The response object.
34
- */
35
- status(status: number): this;
36
- /**
37
- * Sets the body of the response.
38
- * @param body - The content to be used as the response body.
39
- * @returns The response object for method chaining.
40
- */
41
- body(body: BodyInit): this;
42
- /**
43
- * Sets the content type to "application/json" and serializes the provided data
44
- * into a JSON string to set as the response body.
45
- * @param data - The data to be serialized and sent as the response body.
46
- * @returns The finalized Response object after building.
47
- */
48
- json(data: unknown): Response;
49
- /**
50
- * Sets the content type to "text/plain" and assigns the provided text data
51
- * as the response body.
52
- * @param data - The text to be sent as the response body.
53
- * @returns The finalized Response object after building.
54
- */
55
- text(data: string): Response;
56
- /**
57
- * Sets the content type to "text/html" and assigns the provided HTML data
58
- * as the response body.
59
- * @param data - The HTML string to be sent as the response body.
60
- * @returns The finalized Response object after building.
61
- */
62
- html(data: string): Response;
63
- /**
64
- * Sets the HTTP status code and removes the "Location" header from the
65
- * response.
66
- * @param status - The status code.
67
- * @returns The response object.
68
- */
69
- redirect(url: string, status?: number): this;
70
- /**
71
- * Convenience method to send a file response using Bun.file.
72
- * Attempts to serve the specified file and set it as the response body.
73
- * If the file cannot be found or an error occurs, logs the error and
74
- * returns a 404 response with "File not found" as the body.
75
- * @param filePath - The file path to serve.
76
- * @returns The finalized Response object.
77
- */
78
- file(filePath: string): Response;
79
- /**
80
- * Returns a Response directly using the provided body and init settings.
81
- * This bypasses the mutable state.
82
- * @param body - The response body.
83
- * @param init - Optional ResponseInit settings.
84
- * @returns A new Response object.
85
- */
86
- original(body?: BodyInit | null, init?: ResponseInit): Response;
87
- /**
88
- * Builds the final Response object using the current state.
89
- * @returns The finalized Response object.
90
- */
91
- build(): Response;
92
- }
@@ -1,140 +0,0 @@
1
- export class HttpResponse {
2
- /**
3
- * The status code of the response, which defaults to 200 (OK). This
4
- * property can be modified before calling build() to construct the
5
- * Response object.
6
- */
7
- _status = 200;
8
- /**
9
- * The headers of the response, which can be modified before calling build()
10
- * to construct the Response object.
11
- */
12
- _headers = new Headers();
13
- /**
14
- * The body of the response, which can be any valid BodyInit type or null.
15
- */
16
- _body = null;
17
- /**
18
- * Set a header on the response.
19
- * @param name - The header name.
20
- * @param value - The header value.
21
- * @returns The response object.
22
- */
23
- header(name, value) {
24
- this._headers.set(name, value);
25
- return this;
26
- }
27
- /**
28
- * Remove a header from the response.
29
- * @param name - The header name.
30
- * @returns The response object.
31
- */
32
- removeHeader(name) {
33
- this._headers.delete(name);
34
- return this;
35
- }
36
- /**
37
- * Sets the HTTP status code of the response.
38
- * @param status - The status code.
39
- * @returns The response object.
40
- */
41
- status(status) {
42
- this._status = status;
43
- return this;
44
- }
45
- /**
46
- * Sets the body of the response.
47
- * @param body - The content to be used as the response body.
48
- * @returns The response object for method chaining.
49
- */
50
- body(body) {
51
- this._body = body;
52
- return this;
53
- }
54
- /**
55
- * Sets the content type to "application/json" and serializes the provided data
56
- * into a JSON string to set as the response body.
57
- * @param data - The data to be serialized and sent as the response body.
58
- * @returns The finalized Response object after building.
59
- */
60
- json(data) {
61
- this.header('Content-Type', 'application/json');
62
- this._body = JSON.stringify(data);
63
- return this.build();
64
- }
65
- /**
66
- * Sets the content type to "text/plain" and assigns the provided text data
67
- * as the response body.
68
- * @param data - The text to be sent as the response body.
69
- * @returns The finalized Response object after building.
70
- */
71
- text(data) {
72
- this.header('Content-Type', 'text/plain');
73
- this._body = data;
74
- return this.build();
75
- }
76
- /**
77
- * Sets the content type to "text/html" and assigns the provided HTML data
78
- * as the response body.
79
- * @param data - The HTML string to be sent as the response body.
80
- * @returns The finalized Response object after building.
81
- */
82
- html(data) {
83
- this.header('Content-Type', 'text/html');
84
- this._body = data;
85
- return this.build();
86
- }
87
- /**
88
- * Sets the HTTP status code and removes the "Location" header from the
89
- * response.
90
- * @param status - The status code.
91
- * @returns The response object.
92
- */
93
- redirect(url, status = 302) {
94
- this.status(status);
95
- this.header('Location', url);
96
- this._body = null;
97
- return this;
98
- }
99
- /**
100
- * Convenience method to send a file response using Bun.file.
101
- * Attempts to serve the specified file and set it as the response body.
102
- * If the file cannot be found or an error occurs, logs the error and
103
- * returns a 404 response with "File not found" as the body.
104
- * @param filePath - The file path to serve.
105
- * @returns The finalized Response object.
106
- */
107
- file(filePath) {
108
- try {
109
- const file = Bun.file(filePath);
110
- this._body = file;
111
- return this.build();
112
- }
113
- catch (error) {
114
- console.error('Error serving file:', error);
115
- this.status(404);
116
- this._body = 'File not found';
117
- return this.build();
118
- }
119
- }
120
- /**
121
- * Returns a Response directly using the provided body and init settings.
122
- * This bypasses the mutable state.
123
- * @param body - The response body.
124
- * @param init - Optional ResponseInit settings.
125
- * @returns A new Response object.
126
- */
127
- original(body, init) {
128
- return new Response(body, init);
129
- }
130
- /**
131
- * Builds the final Response object using the current state.
132
- * @returns The finalized Response object.
133
- */
134
- build() {
135
- return new Response(this._body, {
136
- status: this._status,
137
- headers: this._headers,
138
- });
139
- }
140
- }