barejs 0.1.49 → 0.1.50

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
@@ -29,11 +29,46 @@ export class BareJS extends BareRouter {
29
29
  private _useLog: boolean = false;
30
30
  private errorHandler?: (err: any, ctx: Context) => any;
31
31
  private wsRoutes = new Map<string, WebSocketRouteHandler>();
32
+ private startHooks: (() => void | Promise<void>)[] = [];
33
+ private stopHooks: (() => void | Promise<void>)[] = [];
34
+ private server?: ReturnType<typeof Bun.serve>;
35
+ private shutdownHandler?: () => Promise<void>;
36
+ private wsAdapter = {
37
+ open(ws: any) { ws.data?.open?.(ws); },
38
+ message(ws: any, msg: any) { ws.data?.message?.(ws, msg); },
39
+ close(ws: any, code: any, reason: any) { ws.data?.close?.(ws, code, reason); },
40
+ drain(ws: any) { ws.data?.drain?.(ws); }
41
+ };
32
42
 
33
43
  public useLog(enabled: boolean = true): this {
34
44
  this._useLog = enabled;
35
45
  return this;
36
46
  }
47
+
48
+ public onStart(fn: () => void | Promise<void>): this {
49
+ this.startHooks.push(fn);
50
+ return this;
51
+ }
52
+
53
+ public onStop(fn: () => void | Promise<void>): this {
54
+ this.stopHooks.push(fn);
55
+ return this;
56
+ }
57
+
58
+ public async stop(closeActiveConnections = false): Promise<void> {
59
+ if (this.shutdownHandler) {
60
+ process.off("SIGINT", this.shutdownHandler);
61
+ process.off("SIGTERM", this.shutdownHandler);
62
+ this.shutdownHandler = undefined;
63
+ }
64
+ if (this.server) {
65
+ this.server.stop(closeActiveConnections);
66
+ this.server = undefined;
67
+ }
68
+ for (const hook of this.stopHooks) {
69
+ await hook();
70
+ }
71
+ }
37
72
  constructor(poolSize: number = 1024) {
38
73
  super();
39
74
  bootstrapConfig();
@@ -129,6 +164,9 @@ export class BareJS extends BareRouter {
129
164
  return ctx.status(400).json({ jsonrpc: '2.0', error: { code: -32700, message: 'Parse error' }, id: null });
130
165
  }
131
166
  if (Array.isArray(payload)) {
167
+ if (payload.length === 0) {
168
+ return ctx.status(400).json({ jsonrpc: '2.0', error: { code: -32600, message: 'Invalid Request' }, id: null });
169
+ }
132
170
  const results = (await Promise.all(payload.map((item) => execCall(item, ctx)))).filter(Boolean);
133
171
  return results.length > 0 ? results : new Response(null, { status: 204 });
134
172
  }
@@ -140,10 +178,57 @@ export class BareJS extends BareRouter {
140
178
  }
141
179
 
142
180
 
181
+ private _hasDerive = false;
182
+ public derive<T extends Record<string, any>>(fn: (ctx: Context) => Promise<T> | T): this {
183
+ this._hasDerive = true;
184
+ this.use(async (ctx: any, next: any) => {
185
+ const derived = await fn(ctx);
186
+ if (derived && typeof derived === 'object') {
187
+ const keys = Object.keys(derived);
188
+ if (!ctx._derivedKeys) ctx._derivedKeys = [];
189
+ for (let i = 0; i < keys.length; i++) {
190
+ const k = keys[i]!;
191
+ if (k !== '__proto__' && k !== 'constructor' && k !== 'prototype') {
192
+ ctx[k] = (derived as any)[k];
193
+ ctx._derivedKeys.push(k);
194
+ }
195
+ }
196
+ }
197
+ return next();
198
+ });
199
+ return this;
200
+ }
201
+
143
202
  // inherited use() from BareRouter handles router merging now
144
203
 
145
204
  private compileHandler(pipeline: any[], isLog: boolean): Function {
205
+ const timeoutMw = pipeline.find((fn) => fn?.__timeout);
206
+ if (timeoutMw) {
207
+ const { ms, status, message } = timeoutMw.__timeout;
208
+ const innerPipeline = pipeline.filter((fn) => !fn?.__timeout);
209
+ const innerCompiled = this.compileHandler(innerPipeline, isLog);
210
+ return async (ctx: Context, doLog?: any) => {
211
+ const res = innerCompiled(ctx, doLog);
212
+ if (!res || !res.then) return res;
213
+ let timer: ReturnType<typeof setTimeout> | undefined;
214
+ try {
215
+ const timeoutPromise = new Promise<Response>((resolve) => {
216
+ timer = setTimeout(() => {
217
+ resolve(Response.json({ status: 'error', code: 'REQUEST_TIMEOUT', message }, { status }));
218
+ }, ms);
219
+ });
220
+ return await Promise.race([res, timeoutPromise]);
221
+ } finally {
222
+ if (timer !== undefined) clearTimeout(timer);
223
+ }
224
+ };
225
+ }
226
+
146
227
  const len = pipeline.length;
228
+ const rFilterMw = pipeline.find((fn) => fn?.__responseFilter);
229
+ const rFilter = rFilterMw?.__responseFilter;
230
+ const idemMw = pipeline.find((fn) => fn?.__idempotencyCommit);
231
+ const idemCommit = idemMw?.__idempotencyCommit;
147
232
 
148
233
  // Static ResponseInit for 200 OK (Zero Allocation)
149
234
  const json200 = { status: 200, headers: { "content-type": "application/json" } };
@@ -154,37 +239,59 @@ export class BareJS extends BareRouter {
154
239
 
155
240
  // Inline Finalizer
156
241
  const finalizeCode = `
242
+ ${rFilter ? 'res = rFilter(res);' : ''}
157
243
  if (res instanceof Response) {
244
+ if (ctx._headers) {
245
+ for (const k in ctx._headers) {
246
+ if (!res.headers.has(k)) res.headers.set(k, ctx._headers[k]);
247
+ }
248
+ }
249
+ if (ctx._setCookies) {
250
+ for (let i = 0; i < ctx._setCookies.length; i++) res.headers.append('Set-Cookie', ctx._setCookies[i]);
251
+ }
158
252
  ${logResCode}
159
253
  return res;
160
254
  }
161
255
 
162
256
  const finalStatus = ctx._status || 200;
257
+ ${idemCommit ? 'idemCommit(ctx, res, finalStatus);' : ''}
163
258
  ${logStatusCode}
164
259
 
260
+ let outRes;
165
261
  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, {
262
+ if (finalStatus === 200 && !ctx._headers) {
263
+ outRes = new Response(res, text200);
264
+ } else {
265
+ outRes = new Response(res, {
266
+ status: finalStatus,
267
+ headers: ctx._headers || text200.headers
268
+ });
269
+ }
270
+ } else if (finalStatus === 200 && !ctx._headers) {
271
+ outRes = Response.json(res ?? null, json200);
272
+ } else {
273
+ outRes = Response.json(res ?? null, {
170
274
  status: finalStatus,
171
- headers: h || text200.headers
275
+ headers: ctx._headers || json200.headers
172
276
  });
173
277
  }
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
- });
278
+
279
+ if (ctx._setCookies) {
280
+ for (let i = 0; i < ctx._setCookies.length; i++) outRes.headers.append('Set-Cookie', ctx._setCookies[i]);
281
+ }
282
+ return outRes;
182
283
  `;
183
284
 
184
285
  const argSig = isLog ? 'ctx, doLog' : 'ctx';
185
286
 
186
287
  if (len === 1) {
187
- const fn0 = pipeline[0];
288
+ const fn0 = pipeline[0]!;
289
+ if (fn0.constructor.name === 'AsyncFunction') {
290
+ return new Function('fn0', 'json200', 'text200', `return async function(${argSig}) {
291
+ const res = await fn0(ctx);
292
+ ${finalizeCode}
293
+ }`)(fn0, json200, text200);
294
+ }
188
295
  return new Function('fn0', 'json200', 'text200', `return function(${argSig}) {
189
296
  const res = fn0(ctx);
190
297
  if (res && res.then) return res.then(v => { const res = v; ${finalizeCode} });
@@ -218,8 +325,8 @@ export class BareJS extends BareRouter {
218
325
  code += `if (r${i} && r${i} instanceof Response) { ${isLog ? 'doLog(r' + i + '.status);' : ''} return r${i}; }\n`;
219
326
  }
220
327
  code += `
221
- const res = fn${len - 1}(ctx);
222
- if (res && res.then) return res.then(v => { const res = v; ${finalizeCode} });
328
+ let res = fn${len - 1}(ctx);
329
+ if (res && res.then) return res.then(v => { let res = v; ${finalizeCode} });
223
330
  ${finalizeCode}
224
331
  `;
225
332
  }
@@ -229,7 +336,7 @@ export class BareJS extends BareRouter {
229
336
  ? `return async function(${argSig})`
230
337
  : `return function(${argSig})`;
231
338
 
232
- return new Function(...fnNames, 'noop', 'json200', 'text200', `${fnHeader} { ${code} }`)(...pipeline, noop, json200, text200);
339
+ return new Function(...fnNames, 'noop', 'json200', 'text200', ...(rFilter ? ['rFilter'] : []), ...(idemCommit ? ['idemCommit'] : []), `${fnHeader} { ${code} }`)(...pipeline, noop, json200, text200, ...(rFilter ? [rFilter] : []), ...(idemCommit ? [idemCommit] : []));
233
340
  }
234
341
 
235
342
  public compile() {
@@ -252,6 +359,12 @@ export class BareJS extends BareRouter {
252
359
  if (typeof res === 'string') return new Response(res, { status });
253
360
  return Response.json(res ?? null, { status });
254
361
  }
362
+ if (err?.status >= 400 && err?.status < 500) {
363
+ return Response.json({
364
+ status: err.status,
365
+ message: err.message || 'Bad Request'
366
+ }, { status: err.status });
367
+ }
255
368
  return Response.json({
256
369
  status: 500,
257
370
  message: process.env.NODE_ENV === 'development' ? (err?.message || "Internal Server Error") : "Internal Server Error",
@@ -270,12 +383,26 @@ export class BareJS extends BareRouter {
270
383
  const EMPTY_PARAMS = Object.freeze({});
271
384
  const hNames = hoistedHandlers.map((_, i) => `h${i}`);
272
385
 
386
+ const hasIdem = this.routes.some((r: any) => r.handlers.some((h: any) => h?.__idempotencyCommit));
387
+ const deriveCleanup = this._hasDerive
388
+ ? `if (ctx._derivedKeys) { for (let i = 0; i < ctx._derivedKeys.length; i++) delete ctx[ctx._derivedKeys[i]]; ctx._derivedKeys = undefined; }`
389
+ : '';
390
+ const idemCleanup = hasIdem
391
+ ? `if (ctx._idempotencyKey) { ctx._idemInFlight.delete(ctx._idempotencyKey); ctx._idempotencyKey = undefined; ctx._idemInFlight = undefined; }`
392
+ : '';
393
+
273
394
  const releaseCode = `
274
395
  if (ctx.store.size > 0) ctx.store.clear();
396
+ ${deriveCleanup}
397
+ ${idemCleanup}
275
398
  ctx.req = undefined;
399
+ ctx._status = 200;
276
400
  ctx.body = undefined;
277
401
  ctx._query = undefined;
402
+ ctx._cookies = undefined;
403
+ ctx._setCookies = undefined;
278
404
  ctx._headers = undefined;
405
+ ctx._requestId = undefined;
279
406
  ctx.params = EMPTY_PARAMS;
280
407
  if (poolTop < maxPool) pool[poolTop++] = ctx;
281
408
  `;
@@ -300,8 +427,50 @@ export class BareJS extends BareRouter {
300
427
  }`
301
428
  : '';
302
429
 
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];
430
+ const staticMws = this.groupMiddleware.filter((m: any) => m.__isStatic);
431
+ const hasStaticMw = staticMws.length > 0;
432
+ const runStatic = hasStaticMw
433
+ ? async (ctx: Context) => {
434
+ const noop = () => {};
435
+ for (let i = 0; i < staticMws.length; i++) {
436
+ const r = await staticMws[i](ctx, noop);
437
+ if (r instanceof Response) {
438
+ if (ctx._headers) {
439
+ for (const k in ctx._headers) {
440
+ const val = ctx._headers[k];
441
+ if (val !== undefined && !r.headers.has(k)) r.headers.set(k, val);
442
+ }
443
+ }
444
+ return r;
445
+ }
446
+ }
447
+ return undefined;
448
+ }
449
+ : undefined;
450
+
451
+ const staticFallback = hasStaticMw
452
+ ? `if (method === 'GET' || method === 'HEAD') {
453
+ out = runStatic(ctx);
454
+ if (out && out.then) {
455
+ return out.then((v) => {
456
+ if (v instanceof Response) { ${isLog ? 'doLog(v.status);' : ''} ${releaseCode} return v; }
457
+ const errorBody = hNotFound();
458
+ const status = errorBody.status || 404;
459
+ ${isLog ? 'doLog(status);' : ''}
460
+ ${releaseCode}
461
+ return Response.json(errorBody, { status });
462
+ }, (e) => {
463
+ const errRes = hError(e, ctx);
464
+ ${releaseCode}
465
+ ${isLog ? 'doLog(errRes.status || 500);' : ''}
466
+ return errRes;
467
+ });
468
+ }
469
+ }`
470
+ : '';
471
+
472
+ const args = ['pool', 'maxPool', 'Context', 'hNotFound', 'hError', 'EMPTY_PARAMS', ...(hasGlobalMw ? ['hOptions'] : []), ...(hasStaticMw ? ['runStatic'] : []), ...hNames];
473
+ const values = [pool, maxPool, Context, hNotFound, hError, EMPTY_PARAMS, ...(hasGlobalMw ? [hOptions] : []), ...(hasStaticMw ? [runStatic] : []), ...hoistedHandlers];
305
474
 
306
475
  const logInit = isLog ? `
307
476
  const start = performance.now();
@@ -333,17 +502,13 @@ export class BareJS extends BareRouter {
333
502
 
334
503
  try {
335
504
  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
505
 
343
506
  ${routerCode}
344
507
 
345
508
  ${optionsFallback}
346
509
 
510
+ ${staticFallback}
511
+
347
512
  const errorBody = hNotFound();
348
513
  const status = errorBody.status || 404;
349
514
  ${isLog ? 'doLog(status);' : ''}
@@ -420,12 +585,7 @@ export class BareJS extends BareRouter {
420
585
  }
421
586
  return baseFetch(req);
422
587
  },
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
- }
588
+ websocket: this.wsAdapter
429
589
  })
430
590
  : Bun.serve({
431
591
  port: finalPort,
@@ -434,26 +594,30 @@ export class BareJS extends BareRouter {
434
594
  fetch: baseFetch
435
595
  });
436
596
 
437
- const shutdown = () => {
597
+ this.server = server;
598
+ for (const hook of this.startHooks) {
599
+ Promise.resolve(hook()).catch((e) => console.error(`[${this.name}] onStart error:`, e));
600
+ }
601
+
602
+ const shutdown = async () => {
438
603
  const isProd = process.env.NODE_ENV === 'production';
439
604
  const serverName = this.name;
440
605
  const supportsEmoji = process.stdout.isTTY;
441
606
 
442
607
  if (isProd) {
443
608
  console.log(`[${serverName}] INFO: Stopping server...`);
609
+ await this.stop(false);
444
610
  } else {
445
-
446
611
  const stopIcon = supportsEmoji ? "🛑" : "!";
447
612
  const checkIcon = supportsEmoji ? "✅" : "v";
448
-
449
-
450
613
  process.stdout.write(`\n\x1b[31m${stopIcon} Stopping ${serverName}...\x1b[0m\n`);
451
- server.stop();
614
+ await this.stop(false);
452
615
  process.stdout.write(`\x1b[32m${checkIcon} ${serverName} has been stopped.\x1b[0m\n`);
453
616
  }
454
617
  process.exit(0);
455
618
  };
456
619
 
620
+ this.shutdownHandler = shutdown;
457
621
  process.on("SIGINT", shutdown);
458
622
  process.on("SIGTERM", shutdown);
459
623
  return server;