barejs 0.1.47 → 0.1.48

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,315 @@
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
+
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[], isLog: boolean): Function {
60
+ const len = pipeline.length;
61
+
62
+ // Static ResponseInit for 200 OK (Zero Allocation)
63
+ const json200 = { status: 200, headers: { "content-type": "application/json" } };
64
+ const text200 = { status: 200, headers: { "content-type": "text/plain" } };
65
+
66
+ const logResCode = isLog ? 'doLog(res.status);' : '';
67
+ const logStatusCode = isLog ? 'doLog(finalStatus);' : '';
68
+
69
+ // Inline Finalizer
70
+ const finalizeCode = `
71
+ if (res instanceof Response) {
72
+ ${logResCode}
73
+ return res;
74
+ }
75
+
76
+ const finalStatus = ctx._status || 200;
77
+ ${logStatusCode}
78
+
79
+ if (typeof res === 'string') {
80
+ if (finalStatus === 200 && !ctx._headers) return new Response(res, text200);
81
+ return new Response(res, {
82
+ status: finalStatus,
83
+ headers: ctx._headers || text200.headers
84
+ });
85
+ }
86
+
87
+ if (finalStatus === 200 && !ctx._headers) return Response.json(res ?? null, json200);
88
+ return Response.json(res ?? null, {
89
+ status: finalStatus,
90
+ headers: ctx._headers && ctx._headers["content-type"] ? ctx._headers : json200.headers
91
+ });
92
+ `;
93
+
94
+ const argSig = isLog ? 'ctx, doLog' : 'ctx';
95
+
96
+ if (len === 1) {
97
+ const fn0 = pipeline[0];
98
+ return new Function('fn0', 'json200', 'text200', `return function(${argSig}) {
99
+ const res = fn0(ctx);
100
+ if (res && res.then) return res.then(v => { const res = v; ${finalizeCode} });
101
+ ${finalizeCode}
102
+ }`)(fn0, json200, text200);
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
+ for (let i = 0; i < len - 1; i++) {
114
+ code += `let r${i} = fn${i}(ctx, noop);\n`;
115
+ code += `if (r${i}) {\n`;
116
+ code += ` if (r${i}.then) r${i} = await r${i};\n`;
117
+ code += ` if (r${i} instanceof Response) { ${isLog ? 'doLog(r' + i + '.status);' : ''} return r${i}; }\n`;
118
+ code += `}\n`;
119
+ }
120
+ code += `
121
+ let res = fn${len - 1}(ctx);
122
+ if (res && res.then) res = await res;
123
+ ${finalizeCode}
124
+ `;
125
+ } else {
126
+ for (let i = 0; i < len - 1; i++) {
127
+ code += `const r${i} = fn${i}(ctx, noop);\n`;
128
+ code += `if (r${i} && r${i} instanceof Response) { ${isLog ? 'doLog(r' + i + '.status);' : ''} return r${i}; }\n`;
129
+ }
130
+ code += `
131
+ const res = fn${len - 1}(ctx);
132
+ if (res && res.then) return res.then(v => { const res = v; ${finalizeCode} });
133
+ ${finalizeCode}
134
+ `;
135
+ }
136
+
137
+ const noop = () => { };
138
+ const fnHeader = isAsync
139
+ ? `return async function(${argSig})`
140
+ : `return function(${argSig})`;
141
+
142
+ return new Function(...fnNames, 'noop', 'json200', 'text200', `${fnHeader} { ${code} }`)(...pipeline, noop, json200, text200);
143
+ }
144
+
145
+ public compile() {
146
+ const isLog = this._useLog;
147
+ this.tree = new RadixNode();
148
+ for (const route of this.routes) {
149
+ this.tree.insert(route.path, route.method, this.compileHandler(route.handlers, isLog));
150
+ }
151
+
152
+ const tree = this.tree;
153
+ const pool = this.pool;
154
+ const maxPool = pool.length;
155
+ const hNotFound = this.notFoundHandler;
156
+ const hError = (err: any) => ({
157
+ status: 500,
158
+ message: process.env.NODE_ENV === 'development' ? (err?.message || "Internal Server Error") : "Internal Server Error",
159
+ stack: process.env.NODE_ENV === 'development' ? err?.stack : undefined
160
+ });
161
+
162
+ const hoistedHandlers: Function[] = [];
163
+ const register = (h: Function) => {
164
+ const name = `h${hoistedHandlers.length}`;
165
+ hoistedHandlers.push(h);
166
+ return name;
167
+ };
168
+
169
+ const rawRouterCode = tree.jitCompile(register);
170
+ const EMPTY_PARAMS = Object.freeze({});
171
+ const hNames = hoistedHandlers.map((_, i) => `h${i}`);
172
+
173
+ const releaseCode = `
174
+ if (ctx.store.size > 0) ctx.store.clear();
175
+ ctx.req = undefined;
176
+ ctx.body = undefined;
177
+ ctx._headers = undefined;
178
+ ctx.params = EMPTY_PARAMS;
179
+ if (poolTop < maxPool) pool[poolTop++] = ctx;
180
+ `;
181
+
182
+ const callSuffix = isLog ? '(ctx, doLog)' : '(ctx)';
183
+ const routerCode = rawRouterCode.replace(
184
+ /return (h\d+)\(ctx\);/g,
185
+ `const out = $1${callSuffix};
186
+ if (out && out.then) return out.then((v) => { ${releaseCode} return v; }, (e) => { ${releaseCode} ${isLog ? 'doLog(500);' : ''} return Response.json(hError(e), { status: 500 }); });
187
+ ${releaseCode}
188
+ return out;`
189
+ );
190
+
191
+ const args = ['pool', 'maxPool', 'Context', 'hNotFound', 'hError', 'EMPTY_PARAMS', ...hNames];
192
+ const values = [pool, maxPool, Context, hNotFound, hError, EMPTY_PARAMS, ...hoistedHandlers];
193
+
194
+ const logInit = isLog ? `
195
+ const start = performance.now();
196
+ const doLog = (status) => {
197
+ const duration = (performance.now() - start).toFixed(3);
198
+ console.log(
199
+ \` \\x1b[90m\${new Date().toLocaleTimeString()}\\x1b[0m \` +
200
+ \`\\x1b[1m\\x1b[38;5;117m\${method.padEnd(7)}\\x1b[0m \` +
201
+ \`\\x1b[38;5;250m\${url.substring(url.indexOf('/', 8))}\\x1b[0m \` +
202
+ \`\${status >= 400 ? '\\x1b[33m' : '\\x1b[32m'}\${status}\\x1b[0m \` +
203
+ \`\\x1b[90m(\${duration}ms)\\x1b[0m\`
204
+ );
205
+ };` : '';
206
+
207
+ const fnBody = `
208
+ let poolTop = maxPool;
209
+ return function(req) {
210
+ const url = req.url;
211
+ let s = url.indexOf('/', 8);
212
+ const q = s === -1 ? -1 : url.indexOf('?', s);
213
+ const urlLen = q === -1 ? url.length : q;
214
+ if (s !== -1) s++;
215
+ else s = urlLen;
216
+
217
+ const method = req.method;
218
+ const ctx = poolTop > 0 ? pool[--poolTop] : new Context();
219
+ ${logInit}
220
+
221
+ try {
222
+ ctx.req = req;
223
+ ctx._status = 200;
224
+ ctx._headers = undefined;
225
+ if (ctx.store.size > 0) ctx.store.clear();
226
+ ctx.params = EMPTY_PARAMS;
227
+ ctx.body = undefined;
228
+
229
+ ${routerCode}
230
+
231
+ const errorBody = hNotFound();
232
+ const status = errorBody.status || 404;
233
+ ${isLog ? 'doLog(status);' : ''}
234
+ ${releaseCode}
235
+ return Response.json(errorBody, { status });
236
+
237
+ } catch (e) {
238
+ ${isLog ? 'doLog(500);' : ''}
239
+ ${releaseCode}
240
+ return Response.json(hError(e), { status: 500 });
241
+ }
242
+ }
243
+ `;
244
+
245
+ this.hotFetch = new Function(...args, fnBody)(...values);
246
+ this.compiled = true;
247
+ this.fetch = this.hotFetch!;
248
+ }
249
+
250
+ public fetch = (req: Request): any => {
251
+ if (!this.compiled) {
252
+ this.compile();
253
+ return this.hotFetch!(req);
254
+ }
255
+ return this.hotFetch!(req);
256
+ };
257
+ public name: string = "App";
258
+
259
+ public listen(port?: number, hostname: string = '0.0.0.0', reusePort: boolean = true) {
260
+ if (!this.compiled) this.compile();
261
+
262
+
263
+ const { BARE_CONFIG } = require("./config");
264
+
265
+
266
+ const finalPort = port || BARE_CONFIG.port || 3000;
267
+ const isProd = process.env.NODE_ENV === 'production';
268
+
269
+ if (!isProd) {
270
+ console.log(`
271
+ \x1b[33m ____ _ _____ \x1b[0m
272
+ \x1b[33m | __ ) __ _ _ __ ___ | | ____|\x1b[0m
273
+ \x1b[33m | _ \\ / _\` | '__/ _ \\ _ | | _| \x1b[0m
274
+ \x1b[33m | |_) | (_| | | | __/| |_| | |___ \x1b[0m
275
+ \x1b[33m |____/ \\__,_|_| \\___| \\___/|_____|\x1b[0m
276
+
277
+ \x1b[32m🚀 ${this.name} is running in development mode\x1b[0m
278
+ \x1b[90m⚙️ Pool Size: ${this.pool.length} | JIT: Enabled | Port: ${finalPort}\x1b[0m
279
+ \x1b[36m🛡️ Hash: ${BARE_CONFIG.hash.algorithm} (${BARE_CONFIG.hash.memoryCost / 1024}MB) | Iterations: ${BARE_CONFIG.hash.timeCost}\x1b[0m
280
+ `);
281
+ }
282
+
283
+ const server = Bun.serve({
284
+ port: finalPort,
285
+ hostname,
286
+ fetch: this.fetch,
287
+ reusePort: reusePort,
288
+ });
289
+
290
+ const shutdown = () => {
291
+ const isProd = process.env.NODE_ENV === 'production';
292
+ const serverName = this.name;
293
+ const supportsEmoji = process.stdout.isTTY;
294
+
295
+ if (isProd) {
296
+ console.log(`[${serverName}] INFO: Stopping server...`);
297
+ } else {
298
+
299
+ const stopIcon = supportsEmoji ? "🛑" : "!";
300
+ const checkIcon = supportsEmoji ? "✅" : "v";
301
+
302
+
303
+ process.stdout.write(`\n\x1b[31m${stopIcon} Stopping ${serverName}...\x1b[0m\n`);
304
+ server.stop();
305
+ process.stdout.write(`\x1b[32m${checkIcon} ${serverName} has been stopped.\x1b[0m\n`);
306
+ }
307
+ process.exit(0);
308
+ };
309
+
310
+ process.on("SIGINT", shutdown);
311
+ process.on("SIGTERM", shutdown);
312
+ }
313
+ }
314
+
315
+ export { Context, typebox, t };