barejs 0.1.47 → 0.1.49

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/src/core/bare.ts CHANGED
@@ -1,318 +1,463 @@
1
- import { BareRouter } from './router';
2
- import { RadixNode } from './radix';
3
- import { Context } from './context';
4
- import { Type as typebox, Type as t } from '@sinclair/typebox';
5
- import { join } from "node:path";
6
- import { readFileSync } from "node:fs";
7
- import { bootstrapConfig } from "./loader";
8
-
9
- export interface NotFoundResponse {
10
- status: number;
11
- message: string;
12
- [key: string]: any;
13
- }
14
- export class BareJS extends BareRouter {
15
- private tree = new RadixNode();
16
- private pool: Context[] = [];
17
- // private poolIdx = 0;
18
- private hotFetch?: (req: Request) => any;
19
- private compiled = false;
20
- private poolMask: number;
21
- private _useLog: boolean = false;
22
- public useLog(enabled: boolean = true): this {
23
- this._useLog = enabled;
24
- return this;
25
- }
26
- constructor(poolSize: number = 1024) {
27
- super();
28
- bootstrapConfig();
29
- const size = Math.pow(2, Math.ceil(Math.log2(poolSize)));
30
- this.poolMask = size - 1;
31
- for (let i = 0; i < size; i++) {
32
- this.pool.push(new Context());
33
- }
34
- try {
35
- const pkgPath = join(process.cwd(), "package.json");
36
- const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
37
- if (pkg.name) {
38
- this.name = pkg.name
39
- .split(/[-_]/)
40
- .map((word: string) => word.charAt(0).toUpperCase() + word.slice(1))
41
- .join(" ");
42
- }
43
- } catch {
44
- this.name = "App";
45
- }
46
- }
47
-
48
- private notFoundHandler: () => NotFoundResponse = () => ({
49
- status: 404,
50
- message: "Route not found"
51
- });
52
- public setNotFound(handler: () => NotFoundResponse) {
53
- this.notFoundHandler = handler;
54
- }
55
-
56
-
57
- // inherited use() from BareRouter handles router merging now
58
-
59
- private compileHandler(pipeline: any[]): Function {
60
- const mws = pipeline;
61
- const len = pipeline.length;
62
-
63
- // Static ResponseInit for 200 OK (Zero Allocation)
64
- const json200 = { status: 200, headers: { "content-type": "application/json" } };
65
-
66
- // Inline Finalizer
67
- const finalizeCode = `
68
- if (res instanceof Response) {
69
- if (typeof doLog === 'function') doLog(res.status);
70
- return res;
71
- }
72
-
73
- const finalStatus = ctx._status || 200;
74
- if (typeof doLog === 'function') doLog(finalStatus);
75
-
76
- if (typeof res === 'string') {
77
- return new Response(res, {
78
- status: finalStatus,
79
- headers: ctx._headers || { "content-type": "text/plain" }
80
- });
81
- }
82
-
83
- return Response.json(res ?? null, {
84
- status: finalStatus,
85
- headers: ctx._headers && ctx._headers["content-type"] ? ctx._headers : { "content-type": "application/json" }
86
- });
87
- `;
88
-
89
- if (len === 1) {
90
- // Fast path: no middleware (just the handler)
91
- const fn0 = pipeline[0];
92
- return new Function('fn0', 'json200', `return function(ctx, doLog) {
93
- const res = fn0(ctx);
94
- if (res && res.then) return res.then(v => { const res = v; ${finalizeCode} });
95
- ${finalizeCode}
96
- }`)(fn0, json200);
97
-
98
- // return new Function('fn0', 'json200', `return function(ctx) {
99
- // const res = fn0(ctx);
100
- // if (res && res.then) return res.then(v => { const res = v; ${finalizeCode} });
101
- // ${finalizeCode}
102
- // }`)(fn0, json200);
103
- }
104
-
105
- // Check async
106
- const isAsync = pipeline.some(fn => fn.constructor.name === 'AsyncFunction');
107
- let code = '';
108
-
109
- // Middleware Hoisting: Pass functions as arguments to avoid array lookup
110
- const fnNames = pipeline.map((_, i) => `fn${i}`);
111
-
112
- if (isAsync) {
113
- // ASYNC MODE
114
- for (let i = 0; i < len - 1; i++) {
115
- // Smart Await: Optimistically assume sync execution
116
- code += `let r${i} = fn${i}(ctx, noop);\n`;
117
- code += `if (r${i}) {\n`;
118
- code += ` if (r${i}.then) r${i} = await r${i};\n`;
119
- code += ` if (r${i} instanceof Response) return r${i};\n`;
120
- code += `}\n`;
121
- }
122
- } else {
123
- // SYNC MODE
124
- for (let i = 0; i < len - 1; i++) {
125
- code += `const r${i} = fn${i}(ctx, noop);\n`;
126
- // Optim: Truthy check first
127
- code += `if (r${i} && r${i} instanceof Response) return r${i};\n`;
128
- }
129
- }
130
-
131
- // Final handler
132
- if (isAsync) {
133
- code += `
134
- let res = fn${len - 1}(ctx);
135
- if (res && res.then) res = await res;
136
- ${finalizeCode}
137
- `;
138
- } else {
139
- code += `
140
- const res = fn${len - 1}(ctx);
141
- if (res && res.then) return res.then(v => { const res = v; ${finalizeCode} });
142
- ${finalizeCode}
143
- `;
144
- }
145
-
146
- const noop = () => { };
147
-
148
- // const fnHeader = isAsync ? 'return async function(ctx)' : 'return function(ctx)';
149
- const fnHeader = pipeline.some(fn => fn.constructor.name === 'AsyncFunction')
150
- ? 'return async function(ctx, doLog)' // ⚡️ รับ doLog เข้ามา
151
- : 'return function(ctx, doLog)';
152
- // Construct Function: (...fns, noop, json200) -> return function(ctx) { ... }
153
- return new Function(...fnNames, 'noop', 'json200', `${fnHeader} { ${code} }`)(...pipeline, noop, json200);
154
- }
155
-
156
- public compile() {
157
- const isLog = this._useLog;
158
- this.tree = new RadixNode();
159
- for (const route of this.routes) {
160
- this.tree.insert(route.path, route.method, this.compileHandler(route.handlers));
161
- }
162
-
163
- const tree = this.tree;
164
- const pool = this.pool;
165
- const mask = this.poolMask;
166
- let pIdx = 0;
167
- const hNotFound = this.notFoundHandler;
168
- const hError = (err: any) => ({
169
- status: 500,
170
- message: err.message || "Internal Server Error",
171
- stack: process.env.NODE_ENV !== 'production' ? err.stack : undefined
172
- });
173
-
174
- // JIT Compiler: Create all Code instead of tree.lookup
175
- const hoistedHandlers: Function[] = [];
176
- const register = (h: Function) => {
177
- const name = `h${hoistedHandlers.length}`;
178
- hoistedHandlers.push(h);
179
- return name;
180
- };
181
-
182
- const routerCode = tree.jitCompile(register);
183
- // console.log("--- GENERATED JIT CODE ---");
184
- // console.log(routerCode);
185
- // console.log("--------------------------");
186
- // Create seamless Fetcher (JIT Edition)
187
- // We send nodes into the closure so the code can use them
188
- const EMPTY_PARAMS = Object.freeze({});
189
- const hNames = hoistedHandlers.map((_, i) => `h${i}`);
190
-
191
- const args = ['pool', 'pIdx', 'mask', 'hNotFound', 'hError', 'EMPTY_PARAMS', ...hNames];
192
- const values = [pool, pIdx, mask, hNotFound, hError, EMPTY_PARAMS, ...hoistedHandlers];
193
-
194
-
195
- // ส่วนใน compile() method (หาบรรทัดที่สร้าง fnBody)
196
-
197
- const fnBody = `
198
- return function(req) {
199
- const start = performance.now();
200
- const url = req.url + " ";
201
- const urlLen = req.url.length; // ✅ ความยาวจริงของ URL
202
-
203
- let s = url.indexOf('/', 8);
204
- if (s !== -1) s++;
205
- else s = urlLen; // ✅ เปลี่ยนจาก url.length เป็น urlLen
206
-
207
- const method = req.method;
208
- const ctx = pool[(++pIdx) & mask];
209
-
210
- const doLog = (status) => {
211
- if (!${isLog}) return;
212
- const duration = (performance.now() - start).toFixed(3);
213
- console.log(
214
- \` \\x1b[90m\${new Date().toLocaleTimeString()}\\x1b[0m \` +
215
- \`\\x1b[1m\\x1b[38;5;117m\${method.padEnd(7)}\\x1b[0m \` +
216
- \`\\x1b[38;5;250m\${req.url.substring(req.url.indexOf('/', 8))}\\x1b[0m \` +
217
- \`\${status >= 400 ? '\\x1b[33m' : '\\x1b[32m'}\${status}\\x1b[0m \` +
218
- \`\\x1b[90m(\${duration}ms)\\x1b[0m\`
219
- );
220
- };
221
-
222
- try {
223
- ctx.req = req;
224
- ctx._status = 200;
225
- ctx._headers = undefined;
226
- if (ctx.store.size > 0) ctx.store.clear();
227
- ctx.params = EMPTY_PARAMS;
228
- ctx.body = undefined;
229
-
230
- // ⚡️ รัน JIT Code (ต้อง replace url.length เป็น urlLen)
231
- ${routerCode
232
- .replace(/h(\d+)\(ctx\)/g, 'h$1(ctx, doLog)')
233
- .replace(/url\.length/g, 'urlLen')}
234
-
235
- const errorBody = hNotFound();
236
- const status = errorBody.status || 404;
237
- doLog(status);
238
- return Response.json(errorBody, { status });
239
-
240
- } catch (e) {
241
- doLog(500);
242
- return Response.json(hError(e), { status: 500 });
243
- }
244
- }
245
- `;
246
-
247
- this.hotFetch = new Function(...args, fnBody)(...values);
248
- this.compiled = true;
249
- // Auto-Optimize: Replace wrapper with direct JIT function
250
- this.fetch = this.hotFetch!;
251
- }
252
-
253
- public fetch = (req: Request): any => {
254
- if (!this.compiled) {
255
- this.compile();
256
- return this.hotFetch!(req);
257
- }
258
- return this.hotFetch!(req);
259
- };
260
- public name: string = "App";
261
-
262
- public listen(port?: number, hostname: string = '0.0.0.0', reusePort: boolean = true) {
263
- if (!this.compiled) this.compile();
264
-
265
- // ดึงค่า Config ล่าสุดมาใช้
266
- const { BARE_CONFIG } = require("./config");
267
-
268
- // ลำดับความสำคัญ: Parameter > Config File > Default (3000)
269
- const finalPort = port || BARE_CONFIG.port || 3000;
270
- const isProd = process.env.NODE_ENV === 'production';
271
-
272
- if (!isProd) {
273
- console.log(`
274
- \x1b[33m ____ _ _____ \x1b[0m
275
- \x1b[33m | __ ) __ _ _ __ ___ | | ____|\x1b[0m
276
- \x1b[33m | _ \\ / _\` | '__/ _ \\ _ | | _| \x1b[0m
277
- \x1b[33m | |_) | (_| | | | __/| |_| | |___ \x1b[0m
278
- \x1b[33m |____/ \\__,_|_| \\___| \\___/|_____|\x1b[0m
279
-
280
- \x1b[32m🚀 ${this.name} is running in development mode\x1b[0m
281
- \x1b[90m⚙️ Pool Size: ${this.pool.length} | JIT: Enabled | Port: ${finalPort}\x1b[0m
282
- \x1b[36m🛡️ Hash: ${BARE_CONFIG.hash.algorithm} (${BARE_CONFIG.hash.memoryCost / 1024}MB) | Iterations: ${BARE_CONFIG.hash.timeCost}\x1b[0m
283
- `);
284
- }
285
-
286
- const server = Bun.serve({
287
- port: finalPort,
288
- hostname,
289
- fetch: this.fetch,
290
- reusePort: reusePort,
291
- });
292
-
293
- const shutdown = () => {
294
- const isProd = process.env.NODE_ENV === 'production';
295
- const serverName = this.name;
296
- const supportsEmoji = process.stdout.isTTY;
297
-
298
- if (isProd) {
299
- console.log(`[${serverName}] INFO: Stopping server...`);
300
- } else {
301
-
302
- const stopIcon = supportsEmoji ? "🛑" : "!";
303
- const checkIcon = supportsEmoji ? "✅" : "v";
304
-
305
-
306
- process.stdout.write(`\n\x1b[31m${stopIcon} Stopping ${serverName}...\x1b[0m\n`);
307
- server.stop();
308
- process.stdout.write(`\x1b[32m${checkIcon} ${serverName} has been stopped.\x1b[0m\n`);
309
- }
310
- process.exit(0);
311
- };
312
-
313
- process.on("SIGINT", shutdown);
314
- process.on("SIGTERM", shutdown);
315
- }
316
- }
317
-
318
- export { Context, typebox, t };
1
+ import { BareRouter } from './router';
2
+ import { RadixNode } from './radix';
3
+ import { Context } from './context';
4
+ import { Type as typebox, Type as t } from '@sinclair/typebox';
5
+ import { join } from "node:path";
6
+ import { readFileSync } from "node:fs";
7
+ import { bootstrapConfig } from "./loader";
8
+ import { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from "../utils/openapi";
9
+
10
+ export interface WebSocketRouteHandler {
11
+ open?: (ws: any) => void;
12
+ message?: (ws: any, message: string | Buffer) => void;
13
+ close?: (ws: any, code: number, reason: string) => void;
14
+ drain?: (ws: any) => void;
15
+ }
16
+
17
+ export interface NotFoundResponse {
18
+ status: number;
19
+ message: string;
20
+ [key: string]: any;
21
+ }
22
+ export class BareJS extends BareRouter {
23
+ private tree = new RadixNode();
24
+ private pool: Context[] = [];
25
+ // private poolIdx = 0;
26
+ private hotFetch?: (req: Request) => any;
27
+ private compiled = false;
28
+ private poolMask: number;
29
+ private _useLog: boolean = false;
30
+ private errorHandler?: (err: any, ctx: Context) => any;
31
+ private wsRoutes = new Map<string, WebSocketRouteHandler>();
32
+
33
+ public useLog(enabled: boolean = true): this {
34
+ this._useLog = enabled;
35
+ return this;
36
+ }
37
+ constructor(poolSize: number = 1024) {
38
+ super();
39
+ bootstrapConfig();
40
+ const size = Math.pow(2, Math.ceil(Math.log2(poolSize)));
41
+ this.poolMask = size - 1;
42
+ for (let i = 0; i < size; i++) {
43
+ this.pool.push(new Context());
44
+ }
45
+ try {
46
+ const pkgPath = join(process.cwd(), "package.json");
47
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
48
+ if (pkg.name) {
49
+ this.name = pkg.name
50
+ .split(/[-_]/)
51
+ .map((word: string) => word.charAt(0).toUpperCase() + word.slice(1))
52
+ .join(" ");
53
+ }
54
+ } catch {
55
+ this.name = "App";
56
+ }
57
+ }
58
+
59
+ private notFoundHandler: () => NotFoundResponse = () => ({
60
+ status: 404,
61
+ message: "Route not found"
62
+ });
63
+ public setNotFound(handler: () => NotFoundResponse) {
64
+ this.notFoundHandler = handler;
65
+ }
66
+
67
+ public onError(handler: (err: any, ctx: Context) => any): this {
68
+ this.errorHandler = handler;
69
+ return this;
70
+ }
71
+
72
+ public ws(path: string, handler: WebSocketRouteHandler): this {
73
+ const normalized = ('/' + path).replace(/\/+/g, '/').replace(/\/$/, '') || '/';
74
+ this.wsRoutes.set(normalized, handler);
75
+ return this;
76
+ }
77
+
78
+ public docs(path: string = '/docs', options: OpenAPIOptions = {}): this {
79
+ const basePath = ('/' + path).replace(/\/+/g, '/').replace(/\/$/, '') || '/docs';
80
+ const jsonPath = `${basePath}/json`;
81
+ let cachedSpec: string | null = null;
82
+ const html = renderDocsHTML(jsonPath, options.title || `${this.name} API Docs`);
83
+
84
+ this.get(jsonPath, () => {
85
+ if (!cachedSpec) {
86
+ cachedSpec = JSON.stringify(generateOpenAPISpec(this.routes, { title: this.name, ...options }));
87
+ }
88
+ return new Response(cachedSpec, {
89
+ status: 200,
90
+ headers: { 'content-type': 'application/json' }
91
+ });
92
+ });
93
+
94
+ this.get(basePath, () => {
95
+ return new Response(html, {
96
+ status: 200,
97
+ headers: { 'content-type': 'text/html; charset=utf-8' }
98
+ });
99
+ });
100
+
101
+ return this;
102
+ }
103
+
104
+ public rpc(path: string, procedures: Record<string, (params: any, ctx: Context) => any>): this {
105
+ const execCall = async (reqObj: any, ctx: Context) => {
106
+ if (!reqObj || reqObj.jsonrpc !== '2.0' || typeof reqObj.method !== 'string') {
107
+ return { jsonrpc: '2.0', error: { code: -32600, message: 'Invalid Request' }, id: reqObj?.id ?? null };
108
+ }
109
+ const fn = Object.hasOwn(procedures, reqObj.method) ? procedures[reqObj.method] : undefined;
110
+ if (!fn) {
111
+ return { jsonrpc: '2.0', error: { code: -32601, message: 'Method not found' }, id: reqObj.id ?? null };
112
+ }
113
+ try {
114
+ const result = await fn(reqObj.params, ctx);
115
+ if (reqObj.id === undefined) return null; // Notification
116
+ return { jsonrpc: '2.0', result, id: reqObj.id };
117
+ } catch (err: any) {
118
+ return {
119
+ jsonrpc: '2.0',
120
+ error: { code: -32603, message: err?.message || 'Internal error' },
121
+ id: reqObj.id ?? null
122
+ };
123
+ }
124
+ };
125
+
126
+ this.post(path, async (ctx: Context) => {
127
+ const payload = await ctx.jsonBody();
128
+ if (!payload) {
129
+ return ctx.status(400).json({ jsonrpc: '2.0', error: { code: -32700, message: 'Parse error' }, id: null });
130
+ }
131
+ if (Array.isArray(payload)) {
132
+ const results = (await Promise.all(payload.map((item) => execCall(item, ctx)))).filter(Boolean);
133
+ return results.length > 0 ? results : new Response(null, { status: 204 });
134
+ }
135
+ const res = await execCall(payload, ctx);
136
+ return res === null ? new Response(null, { status: 204 }) : res;
137
+ });
138
+
139
+ return this;
140
+ }
141
+
142
+
143
+ // inherited use() from BareRouter handles router merging now
144
+
145
+ private compileHandler(pipeline: any[], isLog: boolean): Function {
146
+ const len = pipeline.length;
147
+
148
+ // Static ResponseInit for 200 OK (Zero Allocation)
149
+ const json200 = { status: 200, headers: { "content-type": "application/json" } };
150
+ const text200 = { status: 200, headers: { "content-type": "text/plain" } };
151
+
152
+ const logResCode = isLog ? 'doLog(res.status);' : '';
153
+ const logStatusCode = isLog ? 'doLog(finalStatus);' : '';
154
+
155
+ // Inline Finalizer
156
+ const finalizeCode = `
157
+ if (res instanceof Response) {
158
+ ${logResCode}
159
+ return res;
160
+ }
161
+
162
+ const finalStatus = ctx._status || 200;
163
+ ${logStatusCode}
164
+
165
+ if (typeof res === 'string') {
166
+ if (finalStatus === 200 && !ctx._headers) return new Response(res, text200);
167
+ const h = ctx._headers;
168
+ if (h && !h["content-type"]) h["content-type"] = "text/plain";
169
+ return new Response(res, {
170
+ status: finalStatus,
171
+ headers: h || text200.headers
172
+ });
173
+ }
174
+
175
+ if (finalStatus === 200 && !ctx._headers) return Response.json(res ?? null, json200);
176
+ const h = ctx._headers;
177
+ if (h && !h["content-type"]) h["content-type"] = "application/json";
178
+ return Response.json(res ?? null, {
179
+ status: finalStatus,
180
+ headers: h || json200.headers
181
+ });
182
+ `;
183
+
184
+ const argSig = isLog ? 'ctx, doLog' : 'ctx';
185
+
186
+ if (len === 1) {
187
+ const fn0 = pipeline[0];
188
+ return new Function('fn0', 'json200', 'text200', `return function(${argSig}) {
189
+ const res = fn0(ctx);
190
+ if (res && res.then) return res.then(v => { const res = v; ${finalizeCode} });
191
+ ${finalizeCode}
192
+ }`)(fn0, json200, text200);
193
+ }
194
+
195
+ // Check async
196
+ const isAsync = pipeline.some(fn => fn.constructor.name === 'AsyncFunction');
197
+ let code = '';
198
+
199
+ // Middleware Hoisting: Pass functions as arguments to avoid array lookup
200
+ const fnNames = pipeline.map((_, i) => `fn${i}`);
201
+
202
+ if (isAsync) {
203
+ for (let i = 0; i < len - 1; i++) {
204
+ code += `let r${i} = fn${i}(ctx, noop);\n`;
205
+ code += `if (r${i}) {\n`;
206
+ code += ` if (r${i}.then) r${i} = await r${i};\n`;
207
+ code += ` if (r${i} instanceof Response) { ${isLog ? 'doLog(r' + i + '.status);' : ''} return r${i}; }\n`;
208
+ code += `}\n`;
209
+ }
210
+ code += `
211
+ let res = fn${len - 1}(ctx);
212
+ if (res && res.then) res = await res;
213
+ ${finalizeCode}
214
+ `;
215
+ } else {
216
+ for (let i = 0; i < len - 1; i++) {
217
+ code += `const r${i} = fn${i}(ctx, noop);\n`;
218
+ code += `if (r${i} && r${i} instanceof Response) { ${isLog ? 'doLog(r' + i + '.status);' : ''} return r${i}; }\n`;
219
+ }
220
+ code += `
221
+ const res = fn${len - 1}(ctx);
222
+ if (res && res.then) return res.then(v => { const res = v; ${finalizeCode} });
223
+ ${finalizeCode}
224
+ `;
225
+ }
226
+
227
+ const noop = () => { };
228
+ const fnHeader = isAsync
229
+ ? `return async function(${argSig})`
230
+ : `return function(${argSig})`;
231
+
232
+ return new Function(...fnNames, 'noop', 'json200', 'text200', `${fnHeader} { ${code} }`)(...pipeline, noop, json200, text200);
233
+ }
234
+
235
+ public compile() {
236
+ const isLog = this._useLog;
237
+ this.tree = new RadixNode();
238
+ for (const route of this.routes) {
239
+ this.tree.insert(route.path, route.method, this.compileHandler(route.handlers, isLog));
240
+ }
241
+
242
+ const tree = this.tree;
243
+ const pool = this.pool;
244
+ const maxPool = pool.length;
245
+ const hNotFound = this.notFoundHandler;
246
+ const customError = this.errorHandler;
247
+ const hError = (err: any, ctx: Context) => {
248
+ if (customError) {
249
+ const res = customError(err, ctx);
250
+ if (res instanceof Response) return res;
251
+ const status = ctx._status >= 400 ? ctx._status : 500;
252
+ if (typeof res === 'string') return new Response(res, { status });
253
+ return Response.json(res ?? null, { status });
254
+ }
255
+ return Response.json({
256
+ status: 500,
257
+ message: process.env.NODE_ENV === 'development' ? (err?.message || "Internal Server Error") : "Internal Server Error",
258
+ stack: process.env.NODE_ENV === 'development' ? err?.stack : undefined
259
+ }, { status: 500 });
260
+ };
261
+
262
+ const hoistedHandlers: Function[] = [];
263
+ const register = (h: Function) => {
264
+ const name = `h${hoistedHandlers.length}`;
265
+ hoistedHandlers.push(h);
266
+ return name;
267
+ };
268
+
269
+ const rawRouterCode = tree.jitCompile(register);
270
+ const EMPTY_PARAMS = Object.freeze({});
271
+ const hNames = hoistedHandlers.map((_, i) => `h${i}`);
272
+
273
+ const releaseCode = `
274
+ if (ctx.store.size > 0) ctx.store.clear();
275
+ ctx.req = undefined;
276
+ ctx.body = undefined;
277
+ ctx._query = undefined;
278
+ ctx._headers = undefined;
279
+ ctx.params = EMPTY_PARAMS;
280
+ if (poolTop < maxPool) pool[poolTop++] = ctx;
281
+ `;
282
+
283
+ const callSuffix = isLog ? '(ctx, doLog)' : '(ctx)';
284
+ const routerCode = rawRouterCode.replace(
285
+ /return (h\d+)\(ctx\);/g,
286
+ `out = $1${callSuffix};
287
+ if (out && out.then) return out.then((v) => { ${releaseCode} return v; }, (e) => { const errRes = hError(e, ctx); ${releaseCode} ${isLog ? 'doLog(errRes.status || 500);' : ''} return errRes; });
288
+ ${releaseCode}
289
+ return out;`
290
+ );
291
+
292
+ const hasGlobalMw = this.groupMiddleware.length > 0;
293
+ const hOptions = hasGlobalMw ? this.compileHandler(this.groupMiddleware, isLog) : undefined;
294
+ const optionsFallback = hasGlobalMw
295
+ ? `if (method === 'OPTIONS') {
296
+ out = hOptions${callSuffix};
297
+ if (out && out.then) return out.then((v) => { ${releaseCode} return v; }, (e) => { const errRes = hError(e, ctx); ${releaseCode} ${isLog ? 'doLog(errRes.status || 500);' : ''} return errRes; });
298
+ ${releaseCode}
299
+ return out;
300
+ }`
301
+ : '';
302
+
303
+ const args = ['pool', 'maxPool', 'Context', 'hNotFound', 'hError', 'EMPTY_PARAMS', ...(hasGlobalMw ? ['hOptions'] : []), ...hNames];
304
+ const values = [pool, maxPool, Context, hNotFound, hError, EMPTY_PARAMS, ...(hasGlobalMw ? [hOptions] : []), ...hoistedHandlers];
305
+
306
+ const logInit = isLog ? `
307
+ const start = performance.now();
308
+ const doLog = (status) => {
309
+ const duration = (performance.now() - start).toFixed(3);
310
+ console.log(
311
+ \` \\x1b[90m\${new Date().toLocaleTimeString()}\\x1b[0m \` +
312
+ \`\\x1b[1m\\x1b[38;5;117m\${method.padEnd(7)}\\x1b[0m \` +
313
+ \`\\x1b[38;5;250m\${url.substring(url.indexOf('/', 8))}\\x1b[0m \` +
314
+ \`\${status >= 400 ? '\\x1b[33m' : '\\x1b[32m'}\${status}\\x1b[0m \` +
315
+ \`\\x1b[90m(\${duration}ms)\\x1b[0m\`
316
+ );
317
+ };` : '';
318
+
319
+ const fnBody = `
320
+ let poolTop = maxPool;
321
+ return function(req) {
322
+ const url = req.url;
323
+ let s = url.indexOf('/', 8);
324
+ const q = s === -1 ? -1 : url.indexOf('?', s);
325
+ const urlLen = q === -1 ? url.length : q;
326
+ if (s !== -1) s++;
327
+ else s = urlLen;
328
+
329
+ const method = req.method;
330
+ const ctx = poolTop > 0 ? pool[--poolTop] : new Context();
331
+ let out;
332
+ ${logInit}
333
+
334
+ try {
335
+ ctx.req = req;
336
+ ctx._status = 200;
337
+ ctx._headers = undefined;
338
+ if (ctx.store.size > 0) ctx.store.clear();
339
+ ctx.params = EMPTY_PARAMS;
340
+ ctx.body = undefined;
341
+ ctx._query = undefined;
342
+
343
+ ${routerCode}
344
+
345
+ ${optionsFallback}
346
+
347
+ const errorBody = hNotFound();
348
+ const status = errorBody.status || 404;
349
+ ${isLog ? 'doLog(status);' : ''}
350
+ ${releaseCode}
351
+ return Response.json(errorBody, { status });
352
+
353
+ } catch (e) {
354
+ const errRes = hError(e, ctx);
355
+ ${isLog ? 'doLog(errRes.status || 500);' : ''}
356
+ ${releaseCode}
357
+ return errRes;
358
+ }
359
+ }
360
+ `;
361
+
362
+ this.hotFetch = new Function(...args, fnBody)(...values);
363
+ this.compiled = true;
364
+ this.fetch = this.hotFetch!;
365
+ }
366
+
367
+ public fetch = (req: Request): any => {
368
+ if (!this.compiled) {
369
+ this.compile();
370
+ return this.hotFetch!(req);
371
+ }
372
+ return this.hotFetch!(req);
373
+ };
374
+ public name: string = "App";
375
+
376
+ public listen(port?: number, hostname: string = '0.0.0.0', reusePort: boolean = true) {
377
+ if (!this.compiled) this.compile();
378
+
379
+
380
+ const { BARE_CONFIG } = require("./config");
381
+
382
+
383
+ const finalPort = port || BARE_CONFIG.port || 3000;
384
+ const isProd = process.env.NODE_ENV === 'production';
385
+
386
+ if (!isProd) {
387
+ console.log(`
388
+ \x1b[33m ____ _ _____ \x1b[0m
389
+ \x1b[33m | __ ) __ _ _ __ ___ | | ____|\x1b[0m
390
+ \x1b[33m | _ \\ / _\` | '__/ _ \\ _ | | _| \x1b[0m
391
+ \x1b[33m | |_) | (_| | | | __/| |_| | |___ \x1b[0m
392
+ \x1b[33m |____/ \\__,_|_| \\___| \\___/|_____|\x1b[0m
393
+
394
+ \x1b[32m🚀 ${this.name} is running in development mode\x1b[0m
395
+ \x1b[90m⚙️ Pool Size: ${this.pool.length} | JIT: Enabled | Port: ${finalPort}\x1b[0m
396
+ \x1b[36m🛡️ Hash: ${BARE_CONFIG.hash.algorithm} (${BARE_CONFIG.hash.memoryCost / 1024}MB) | Iterations: ${BARE_CONFIG.hash.timeCost}\x1b[0m
397
+ `);
398
+ }
399
+
400
+ const wsRoutes = this.wsRoutes;
401
+ const baseFetch = this.fetch;
402
+ const hasWs = wsRoutes.size > 0;
403
+
404
+ const server = hasWs
405
+ ? Bun.serve<WebSocketRouteHandler>({
406
+ port: finalPort,
407
+ hostname,
408
+ reusePort,
409
+ fetch(req: Request, srv: any) {
410
+ if (req.headers.get('upgrade') === 'websocket') {
411
+ const url = req.url;
412
+ const s = url.indexOf('/', 8);
413
+ const q = s === -1 ? -1 : url.indexOf('?', s);
414
+ const path = s === -1 ? '/' : (q === -1 ? url.slice(s) : url.slice(s, q));
415
+ const normalized = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;
416
+ const handler = wsRoutes.get(normalized);
417
+ if (handler && srv.upgrade(req, { data: handler })) {
418
+ return undefined as any;
419
+ }
420
+ }
421
+ return baseFetch(req);
422
+ },
423
+ websocket: {
424
+ open(ws) { ws.data?.open?.(ws); },
425
+ message(ws, msg) { ws.data?.message?.(ws, msg); },
426
+ close(ws, code, reason) { ws.data?.close?.(ws, code, reason); },
427
+ drain(ws) { ws.data?.drain?.(ws); }
428
+ }
429
+ })
430
+ : Bun.serve({
431
+ port: finalPort,
432
+ hostname,
433
+ reusePort,
434
+ fetch: baseFetch
435
+ });
436
+
437
+ const shutdown = () => {
438
+ const isProd = process.env.NODE_ENV === 'production';
439
+ const serverName = this.name;
440
+ const supportsEmoji = process.stdout.isTTY;
441
+
442
+ if (isProd) {
443
+ console.log(`[${serverName}] INFO: Stopping server...`);
444
+ } else {
445
+
446
+ const stopIcon = supportsEmoji ? "🛑" : "!";
447
+ const checkIcon = supportsEmoji ? "✅" : "v";
448
+
449
+
450
+ process.stdout.write(`\n\x1b[31m${stopIcon} Stopping ${serverName}...\x1b[0m\n`);
451
+ server.stop();
452
+ process.stdout.write(`\x1b[32m${checkIcon} ${serverName} has been stopped.\x1b[0m\n`);
453
+ }
454
+ process.exit(0);
455
+ };
456
+
457
+ process.on("SIGINT", shutdown);
458
+ process.on("SIGTERM", shutdown);
459
+ return server;
460
+ }
461
+ }
462
+
463
+ export { Context, typebox, t };