barejs 0.1.54 → 0.1.56

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
@@ -5,6 +5,7 @@ import { Type as typebox, Type as t } from '@sinclair/typebox';
5
5
  import { join } from "node:path";
6
6
  import { readFileSync } from "node:fs";
7
7
  import { bootstrapConfig } from "./loader";
8
+ import { BARE_CONFIG } from "./config";
8
9
  import { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from "../utils/openapi";
9
10
  import type { RouteSchemas } from "../security/validators";
10
11
  import type { RouteSchema } from "../client/index";
@@ -67,9 +68,8 @@ export class BareJS<
67
68
  // private poolIdx = 0;
68
69
  private hotFetch?: (req: Request, peerIp?: string) => any;
69
70
  private compiled = false;
70
- private poolMask: number;
71
71
  private _useLog: boolean = false;
72
- private _trustProxy: boolean = true;
72
+ private _trustProxyBox = { val: false };
73
73
  private errorHandler?: (err: any, ctx: Context) => any;
74
74
  private wsRoutes = new Map<string, WebSocketRouteHandler>();
75
75
  private startHooks: (() => void | Promise<void>)[] = [];
@@ -109,6 +109,9 @@ export class BareJS<
109
109
  fn: () => void | Promise<void>,
110
110
  options: CronOptions = {}
111
111
  ): this {
112
+ if (!Number.isFinite(intervalMs) || intervalMs <= 0) {
113
+ throw new RangeError(`cron("${name}") intervalMs must be a positive finite number`);
114
+ }
112
115
  let running = false;
113
116
  const tick = async () => {
114
117
  if (running) return;
@@ -145,14 +148,17 @@ export class BareJS<
145
148
  this.server = undefined;
146
149
  }
147
150
  for (const hook of this.stopHooks) {
148
- await hook();
151
+ try {
152
+ await hook();
153
+ } catch (e) {
154
+ console.error(`[${this.name}] onStop error:`, e);
155
+ }
149
156
  }
150
157
  }
151
158
  constructor(poolSize: number = 1024) {
152
159
  super();
153
160
  bootstrapConfig();
154
161
  const size = Math.pow(2, Math.ceil(Math.log2(poolSize)));
155
- this.poolMask = size - 1;
156
162
  for (let i = 0; i < size; i++) {
157
163
  this.pool.push(new Context());
158
164
  }
@@ -197,7 +203,7 @@ export class BareJS<
197
203
 
198
204
  this.get(jsonPath, () => {
199
205
  if (!cachedSpec) {
200
- cachedSpec = JSON.stringify(generateOpenAPISpec(this.routes, { title: this.name, ...options }));
206
+ cachedSpec = JSON.stringify(generateOpenAPISpec(this.routes, { title: this.name, excludePaths: [basePath, jsonPath], ...options }));
201
207
  }
202
208
  return new Response(cachedSpec, {
203
209
  status: 200,
@@ -215,7 +221,14 @@ export class BareJS<
215
221
  return this;
216
222
  }
217
223
 
218
- public rpc(path: string, procedures: Record<string, (params: any, ctx: Context) => any>): this {
224
+ public rpc(
225
+ path: string,
226
+ procedures: Record<string, (params: any, ctx: Context) => any>,
227
+ options: { maxBatchSize?: number } = {}
228
+ ): this {
229
+ const maxBatchSize = options.maxBatchSize ?? 100;
230
+ const isProd = process.env.NODE_ENV === 'production';
231
+
219
232
  const execCall = async (reqObj: any, ctx: Context) => {
220
233
  if (!reqObj || reqObj.jsonrpc !== '2.0' || typeof reqObj.method !== 'string') {
221
234
  return { jsonrpc: '2.0', error: { code: -32600, message: 'Invalid Request' }, id: reqObj?.id ?? null };
@@ -229,9 +242,12 @@ export class BareJS<
229
242
  if (reqObj.id === undefined) return null; // Notification
230
243
  return { jsonrpc: '2.0', result, id: reqObj.id };
231
244
  } catch (err: any) {
245
+ const msg = !isProd || err?.expose || (err?.status >= 400 && err?.status < 500)
246
+ ? (err?.message || 'Internal error')
247
+ : 'Internal error';
232
248
  return {
233
249
  jsonrpc: '2.0',
234
- error: { code: -32603, message: err?.message || 'Internal error' },
250
+ error: { code: -32603, message: msg },
235
251
  id: reqObj.id ?? null
236
252
  };
237
253
  }
@@ -243,7 +259,7 @@ export class BareJS<
243
259
  return ctx.status(400).json({ jsonrpc: '2.0', error: { code: -32700, message: 'Parse error' }, id: null });
244
260
  }
245
261
  if (Array.isArray(payload)) {
246
- if (payload.length === 0) {
262
+ if (payload.length === 0 || payload.length > maxBatchSize) {
247
263
  return ctx.status(400).json({ jsonrpc: '2.0', error: { code: -32600, message: 'Invalid Request' }, id: null });
248
264
  }
249
265
  const results = (await Promise.all(payload.map((item) => execCall(item, ctx)))).filter(Boolean);
@@ -278,32 +294,135 @@ export class BareJS<
278
294
  };
279
295
 
280
296
  private _hasDerive = false;
297
+ private static readonly DERIVE_RESERVED = new Set([
298
+ '__proto__', 'constructor', 'prototype',
299
+ 'req', 'params', 'store', 'body', 'user',
300
+ 'query', 'cookies', 'requestId', 'ip',
301
+ 'status', 'json', 'html', 'text', 'redirect', 'sse', 'upload', 'reset',
302
+ 'set', 'get', 'setHeader', 'setCookie', 'getSignedCookie', 'deleteCookie',
303
+ 'jsonBody', 'send', 'getQuery',
304
+ '_status', '_headers', '_query', '_cookies', '_setCookies',
305
+ '_requestId', '_peerIp', '_trustProxy', '_detached',
306
+ '_derivedKeys', '_idempotencyKey', '_idemInFlight'
307
+ ]);
281
308
  public derive<T extends Record<string, any>>(fn: (ctx: Context & Derived) => Promise<T> | T): BareJS<Derived & T, Routes> {
282
309
  this._hasDerive = true;
283
- this.use(async (ctx: any, next: any) => {
310
+ const deriveMw = async (ctx: any, next: any) => {
284
311
  const derived = await fn(ctx);
285
312
  if (derived && typeof derived === 'object') {
286
313
  const keys = Object.keys(derived);
287
314
  if (!ctx._derivedKeys) ctx._derivedKeys = [];
288
315
  for (let i = 0; i < keys.length; i++) {
289
316
  const k = keys[i]!;
290
- if (k !== '__proto__' && k !== 'constructor' && k !== 'prototype') {
317
+ if (k === 'user') {
318
+ ctx.set('user', (derived as any)[k]);
319
+ } else if (!BareJS.DERIVE_RESERVED.has(k)) {
291
320
  ctx[k] = (derived as any)[k];
292
321
  ctx._derivedKeys.push(k);
293
322
  }
294
323
  }
295
324
  }
296
325
  return next();
297
- });
326
+ };
327
+ (deriveMw as any).__isDerive = true;
328
+ this.use(deriveMw);
298
329
  return this as any;
299
330
  }
300
331
 
301
332
  // inherited use() from BareRouter handles router merging now
302
333
 
303
334
  private compileHandler(pipeline: any[], isLog: boolean): Function {
304
- const timeoutMw = pipeline.find((fn) => fn?.__timeout);
305
- if (timeoutMw) {
306
- const { ms, status, message } = timeoutMw.__timeout;
335
+ if (pipeline.length === 0) {
336
+ return () => undefined;
337
+ }
338
+
339
+ const applyCtxHeadersToRes = (res: Response, ctx: Context): Response => {
340
+ if (ctx._headers) {
341
+ for (const k in ctx._headers) {
342
+ const val = ctx._headers[k];
343
+ if (val === undefined) continue;
344
+ if (!res.headers.has(k)) {
345
+ try { res.headers.set(k, val); } catch { /* ignore invalid header */ }
346
+ } else if (k.toLowerCase() === 'vary') {
347
+ const existing = res.headers.get('vary') || '';
348
+ const parts = existing.toLowerCase().split(',').map((v) => v.trim());
349
+ const toAdd = val.split(',').map((v) => v.trim()).filter((v) => v && !parts.includes(v.toLowerCase()));
350
+ if (toAdd.length > 0) {
351
+ try { res.headers.set('vary', existing ? `${existing}, ${toAdd.join(', ')}` : toAdd.join(', ')); } catch {}
352
+ }
353
+ }
354
+ }
355
+ }
356
+ if (ctx._setCookies) {
357
+ for (let i = 0; i < ctx._setCookies.length; i++) {
358
+ try { res.headers.append('Set-Cookie', ctx._setCookies[i]!); } catch { /* ignore */ }
359
+ }
360
+ ctx._setCookies = undefined;
361
+ }
362
+ return res;
363
+ };
364
+
365
+ const compMw = pipeline.find((fn) => fn?.__compress);
366
+ if (compMw) {
367
+ const applyCompress = compMw.__compress;
368
+ const innerPipeline = pipeline.filter((fn) => !fn?.__compress);
369
+ const innerCompiled = this.compileHandler(innerPipeline, isLog);
370
+ return async (ctx: Context, doLog?: any) => {
371
+ const res = await innerCompiled(ctx, doLog);
372
+ return applyCompress(ctx, res);
373
+ };
374
+ }
375
+
376
+ const cbIdx = pipeline.findIndex((fn) => fn?.__circuitBreaker);
377
+ if (cbIdx !== -1) {
378
+ const cbMw = pipeline[cbIdx]!;
379
+ const runWithBreaker = cbMw.__circuitBreaker;
380
+ const rawPre = pipeline.slice(0, cbIdx);
381
+ const prePipeline: any[] = [];
382
+ const hoistedToPost: any[] = [];
383
+ for (let i = 0; i < rawPre.length; i++) {
384
+ const fn = rawPre[i];
385
+ if (fn?.__timeout || fn?.__idempotencyCommit || fn?.__responseFilter) {
386
+ hoistedToPost.push(fn);
387
+ } else {
388
+ prePipeline.push(fn);
389
+ }
390
+ }
391
+ const postPipeline = [...hoistedToPost, ...pipeline.slice(cbIdx + 1)];
392
+ const postCompiled = this.compileHandler(postPipeline, isLog);
393
+ const noopPre = () => {};
394
+ return async (ctx: Context, doLog?: any) => {
395
+ for (let i = 0; i < prePipeline.length; i++) {
396
+ let preRes = prePipeline[i](ctx, noopPre);
397
+ if (preRes && typeof preRes.then === 'function') preRes = await preRes;
398
+ if (preRes instanceof Response) {
399
+ applyCtxHeadersToRes(preRes, ctx);
400
+ if (isLog && doLog && !ctx._detached) doLog(preRes.status);
401
+ return preRes;
402
+ }
403
+ }
404
+ let innerRan = false;
405
+ const out = await runWithBreaker(() => {
406
+ innerRan = true;
407
+ return postCompiled(ctx, doLog);
408
+ });
409
+ if (!innerRan && out instanceof Response) {
410
+ applyCtxHeadersToRes(out, ctx);
411
+ if (isLog && doLog && !ctx._detached) doLog(out.status);
412
+ }
413
+ return out;
414
+ };
415
+ }
416
+
417
+ const timeoutMws = pipeline.filter((fn) => fn?.__timeout);
418
+ if (timeoutMws.length > 0) {
419
+ let chosen = timeoutMws[0]!.__timeout;
420
+ for (let i = 1; i < timeoutMws.length; i++) {
421
+ if (timeoutMws[i]!.__timeout.ms < chosen.ms) {
422
+ chosen = timeoutMws[i]!.__timeout;
423
+ }
424
+ }
425
+ const { ms, status, message } = chosen;
307
426
  const innerPipeline = pipeline.filter((fn) => !fn?.__timeout);
308
427
  const innerCompiled = this.compileHandler(innerPipeline, isLog);
309
428
  return async (ctx: Context, doLog?: any) => {
@@ -313,7 +432,15 @@ export class BareJS<
313
432
  try {
314
433
  const timeoutPromise = new Promise<Response>((resolve) => {
315
434
  timer = setTimeout(() => {
316
- resolve(Response.json({ status: 'error', code: 'REQUEST_TIMEOUT', message }, { status }));
435
+ ctx._detached = true;
436
+ if ((ctx as any)._idempotencyKey && (ctx as any)._idemInFlight) {
437
+ (ctx as any)._idemInFlight.delete((ctx as any)._idempotencyKey);
438
+ (ctx as any)._idempotencyKey = undefined;
439
+ (ctx as any)._idemInFlight = undefined;
440
+ }
441
+ if (typeof res.catch === 'function') res.catch(() => {});
442
+ if (isLog && doLog) doLog(status);
443
+ resolve(applyCtxHeadersToRes(Response.json({ status: 'error', code: 'REQUEST_TIMEOUT', message }, { status }), ctx));
317
444
  }, ms);
318
445
  });
319
446
  return await Promise.race([res, timeoutPromise]);
@@ -323,25 +450,6 @@ export class BareJS<
323
450
  };
324
451
  }
325
452
 
326
- const cbMw = pipeline.find((fn) => fn?.__circuitBreaker);
327
- if (cbMw) {
328
- const runWithBreaker = cbMw.__circuitBreaker;
329
- const innerPipeline = pipeline.filter((fn) => !fn?.__circuitBreaker);
330
- const innerCompiled = this.compileHandler(innerPipeline, isLog);
331
- return (ctx: Context, doLog?: any) => runWithBreaker(() => innerCompiled(ctx, doLog));
332
- }
333
-
334
- const compMw = pipeline.find((fn) => fn?.__compress);
335
- if (compMw) {
336
- const applyCompress = compMw.__compress;
337
- const innerPipeline = pipeline.filter((fn) => !fn?.__compress);
338
- const innerCompiled = this.compileHandler(innerPipeline, isLog);
339
- return async (ctx: Context, doLog?: any) => {
340
- const res = await innerCompiled(ctx, doLog);
341
- return applyCompress(ctx, res);
342
- };
343
- }
344
-
345
453
  const len = pipeline.length;
346
454
  const rFilterMw = pipeline.find((fn) => fn?.__responseFilter);
347
455
  const rFilter = rFilterMw?.__responseFilter;
@@ -353,30 +461,37 @@ export class BareJS<
353
461
  const json200 = { status: 200, headers: { "content-type": "application/json" } };
354
462
  const text200 = { status: 200, headers: { "content-type": "text/plain" } };
355
463
 
356
- const logResCode = isLog ? 'doLog(res.status);' : '';
357
- const logStatusCode = isLog ? 'doLog(finalStatus);' : '';
464
+ const logResCode = isLog ? 'if (!ctx._detached) doLog(res.status);' : '';
465
+ const logStatusCode = isLog ? 'if (!ctx._detached) doLog(finalStatus);' : '';
358
466
 
359
- // Inline Finalizer
360
- const finalizeCode = `
361
- ${rFilter ? 'res = rFilter(res);' : ''}
362
- if (res instanceof Response) {
363
- ${idemCommit ? 'idemCommit(ctx, res, res.status);' : ''}
364
- if (ctx._headers) {
365
- for (const k in ctx._headers) {
366
- if (!res.headers.has(k)) res.headers.set(k, ctx._headers[k]);
467
+ const buildResFinalize = `
468
+ if (ctx._headers) {
469
+ for (const k in ctx._headers) {
470
+ const val = ctx._headers[k];
471
+ if (val === undefined) continue;
472
+ if (!res.headers.has(k)) {
473
+ try { res.headers.set(k, val); } catch {}
474
+ } else if (k.toLowerCase() === 'vary') {
475
+ const existing = res.headers.get('vary') || '';
476
+ const parts = existing.toLowerCase().split(',').map((v) => v.trim());
477
+ const toAdd = val.split(',').map((v) => v.trim()).filter((v) => v && !parts.includes(v.toLowerCase()));
478
+ if (toAdd.length > 0) {
479
+ try { res.headers.set('vary', existing ? \`\${existing}, \${toAdd.join(', ')}\` : toAdd.join(', ')); } catch {}
480
+ }
367
481
  }
368
482
  }
369
- if (ctx._setCookies) {
370
- for (let i = 0; i < ctx._setCookies.length; i++) res.headers.append('Set-Cookie', ctx._setCookies[i]);
483
+ }
484
+ if (ctx._setCookies) {
485
+ for (let i = 0; i < ctx._setCookies.length; i++) {
486
+ try { res.headers.append('Set-Cookie', ctx._setCookies[i]); } catch {}
371
487
  }
372
- ${logResCode}
373
- return res;
374
488
  }
375
-
376
- const finalStatus = ctx._status || 200;
377
- ${idemCommit ? 'idemCommit(ctx, res, finalStatus);' : ''}
378
- ${logStatusCode}
489
+ ${logResCode}
490
+ return res;
491
+ `;
379
492
 
493
+ const buildNonResFinalize = `
494
+ ${logStatusCode}
380
495
  let outRes;
381
496
  if (typeof res === 'string') {
382
497
  if (finalStatus === 200 && !ctx._headers) {
@@ -402,19 +517,39 @@ export class BareJS<
402
517
  }
403
518
 
404
519
  if (ctx._setCookies) {
405
- for (let i = 0; i < ctx._setCookies.length; i++) outRes.headers.append('Set-Cookie', ctx._setCookies[i]);
520
+ for (let i = 0; i < ctx._setCookies.length; i++) {
521
+ try { outRes.headers.append('Set-Cookie', ctx._setCookies[i]); } catch {}
522
+ }
406
523
  }
407
524
  return outRes;
408
525
  `;
409
526
 
527
+ // Inline Finalizer
528
+ const finalizeCode = `
529
+ ${rFilter ? 'res = rFilter(res);' : ''}
530
+ if (res instanceof Response) {
531
+ ${idemCommit ? 'const ic = idemCommit(ctx, res, res.status); if (ic && ic.then) return ic.then(() => { ' + buildResFinalize + ' });' : ''}
532
+ ${buildResFinalize}
533
+ }
534
+
535
+ const finalStatus = ctx._status || 200;
536
+ ${idemCommit ? 'const ic = idemCommit(ctx, res, finalStatus); if (ic && ic.then) return ic.then(() => { ' + buildNonResFinalize + ' });' : ''}
537
+ ${buildNonResFinalize}
538
+ `;
539
+
410
540
  const argSig = isLog ? 'ctx, doLog' : 'ctx';
541
+ const noop = () => { };
411
542
 
412
543
  const extraNames = [
544
+ 'applyShortCircuit',
545
+ 'noop',
413
546
  ...(rFilter ? ['rFilter'] : []),
414
547
  ...(idemCommit ? ['idemCommit'] : []),
415
548
  ...(idemRelease ? ['idemRelease'] : [])
416
549
  ];
417
550
  const extraVals = [
551
+ applyCtxHeadersToRes,
552
+ noop,
418
553
  ...(rFilter ? [rFilter] : []),
419
554
  ...(idemCommit ? [idemCommit] : []),
420
555
  ...(idemRelease ? [idemRelease] : [])
@@ -447,14 +582,14 @@ export class BareJS<
447
582
  if (fn0.constructor.name === 'AsyncFunction') {
448
583
  return wrapIdem(
449
584
  new Function('fn0', 'json200', 'text200', ...extraNames, `let lastHdrs = null, lastInit200 = null; return async function(${argSig}) {
450
- const res = await fn0(ctx);
585
+ const res = await fn0(ctx, noop);
451
586
  ${finalizeCode}
452
587
  }`)(fn0, json200, text200, ...extraVals)
453
588
  );
454
589
  }
455
590
  return wrapIdem(
456
591
  new Function('fn0', 'json200', 'text200', ...extraNames, `let lastHdrs = null, lastInit200 = null; return function(${argSig}) {
457
- const res = fn0(ctx);
592
+ const res = fn0(ctx, noop);
458
593
  if (res && res.then) return res.then(v => { const res = v; ${finalizeCode} });
459
594
  ${finalizeCode}
460
595
  }`)(fn0, json200, text200, ...extraVals)
@@ -467,48 +602,88 @@ export class BareJS<
467
602
 
468
603
  // Middleware Hoisting: Pass functions as arguments to avoid array lookup
469
604
  const fnNames = pipeline.map((_, i) => `fn${i}`);
605
+ let continueAsyncDef = '';
470
606
 
471
607
  if (isAsync) {
472
608
  for (let i = 0; i < len - 1; i++) {
473
609
  code += `let r${i} = fn${i}(ctx, noop);\n`;
474
610
  code += `if (r${i}) {\n`;
475
611
  code += ` if (r${i}.then) r${i} = await r${i};\n`;
476
- code += ` if (r${i} instanceof Response) { ${isLog ? 'doLog(r' + i + '.status);' : ''} return r${i}; }\n`;
612
+ code += ` if (r${i} instanceof Response) { applyShortCircuit(r${i}, ctx); ${isLog ? 'if (!ctx._detached) doLog(r' + i + '.status);' : ''} return r${i}; }\n`;
477
613
  code += `}\n`;
478
614
  }
479
615
  code += `
480
- let res = fn${len - 1}(ctx);
616
+ let res = fn${len - 1}(ctx, noop);
481
617
  if (res && res.then) res = await res;
482
618
  ${finalizeCode}
483
619
  `;
484
620
  } else {
621
+ continueAsyncDef = `
622
+ const fns = [${fnNames.join(', ')}];
623
+ const continueAsync = async (${isLog ? 'idx, pending, ctx, doLog' : 'idx, pending, ctx'}) => {
624
+ let r = await pending;
625
+ if (r instanceof Response) { applyShortCircuit(r, ctx); ${isLog ? 'if (!ctx._detached) doLog(r.status);' : ''} return r; }
626
+ for (let i = idx + 1; i < fns.length - 1; i++) {
627
+ r = fns[i](ctx, noop);
628
+ if (r) {
629
+ if (typeof r.then === 'function') r = await r;
630
+ if (r instanceof Response) { applyShortCircuit(r, ctx); ${isLog ? 'if (!ctx._detached) doLog(r.status);' : ''} return r; }
631
+ }
632
+ }
633
+ let res = fns[fns.length - 1](ctx, noop);
634
+ if (res && typeof res.then === 'function') res = await res;
635
+ ${finalizeCode}
636
+ };
637
+ `;
485
638
  for (let i = 0; i < len - 1; i++) {
486
639
  code += `const r${i} = fn${i}(ctx, noop);\n`;
487
- code += `if (r${i} && r${i} instanceof Response) { ${isLog ? 'doLog(r' + i + '.status);' : ''} return r${i}; }\n`;
640
+ code += `if (r${i}) {\n`;
641
+ code += ` if (r${i} instanceof Response) { applyShortCircuit(r${i}, ctx); ${isLog ? 'if (!ctx._detached) doLog(r' + i + '.status);' : ''} return r${i}; }\n`;
642
+ code += ` if (typeof r${i}.then === 'function') return continueAsync(${i}, r${i}, ${argSig});\n`;
643
+ code += `}\n`;
488
644
  }
489
645
  code += `
490
- let res = fn${len - 1}(ctx);
646
+ let res = fn${len - 1}(ctx, noop);
491
647
  if (res && res.then) return res.then(v => { let res = v; ${finalizeCode} });
492
648
  ${finalizeCode}
493
649
  `;
494
650
  }
495
651
 
496
- const noop = () => { };
497
652
  const fnHeader = isAsync
498
653
  ? `let lastHdrs = null, lastInit200 = null; return async function(${argSig})`
499
- : `let lastHdrs = null, lastInit200 = null; return function(${argSig})`;
654
+ : `let lastHdrs = null, lastInit200 = null; ${continueAsyncDef} return function(${argSig})`;
500
655
 
501
656
  return wrapIdem(
502
- new Function(...fnNames, 'noop', 'json200', 'text200', ...extraNames, `${fnHeader} { ${code} }`)(...pipeline, noop, json200, text200, ...extraVals)
657
+ new Function(...fnNames, 'json200', 'text200', ...extraNames, `${fnHeader} { ${code} }`)(...pipeline, json200, text200, ...extraVals)
503
658
  );
504
659
  }
505
660
 
506
661
  public compile() {
507
662
  const isLog = this._useLog;
508
663
  this.tree = new RadixNode();
664
+ const explicitOptionsPaths = new Set<string>();
509
665
  for (const route of this.routes) {
666
+ if (route.method === 'OPTIONS') explicitOptionsPaths.add(route.path);
510
667
  this.tree.insert(route.path, route.method, this.compileHandler(route.handlers, isLog));
511
668
  }
669
+ for (const route of this.routes) {
670
+ if (route.method === 'OPTIONS' || explicitOptionsPaths.has(route.path)) continue;
671
+ let lastCorsIdx = -1;
672
+ for (let i = route.handlers.length - 1; i >= 0; i--) {
673
+ if ((route.handlers[i] as any)?.__isCors && !this.groupMiddleware.includes(route.handlers[i])) {
674
+ lastCorsIdx = i;
675
+ break;
676
+ }
677
+ }
678
+ if (lastCorsIdx !== -1) {
679
+ explicitOptionsPaths.add(route.path);
680
+ const preflightPipeline = [
681
+ ...route.handlers.slice(0, lastCorsIdx + 1).filter((h: any, idx: number) => idx === lastCorsIdx || !h?.__isCors),
682
+ () => new Response(null, { status: 204 })
683
+ ];
684
+ this.tree.insert(route.path, 'OPTIONS', this.compileHandler(preflightPipeline, isLog));
685
+ }
686
+ }
512
687
 
513
688
  const tree = this.tree;
514
689
  const pool = this.pool;
@@ -519,8 +694,16 @@ export class BareJS<
519
694
  if (ctx._headers) {
520
695
  for (const k in ctx._headers) {
521
696
  const val = ctx._headers[k];
522
- if (val !== undefined && !res.headers.has(k)) {
697
+ if (val === undefined) continue;
698
+ if (!res.headers.has(k)) {
523
699
  try { res.headers.set(k, val); } catch { /* ignore invalid header values on error path */ }
700
+ } else if (k.toLowerCase() === 'vary') {
701
+ const existing = res.headers.get('vary') || '';
702
+ const parts = existing.toLowerCase().split(',').map((v) => v.trim());
703
+ const toAdd = val.split(',').map((v) => v.trim()).filter((v) => v && !parts.includes(v.toLowerCase()));
704
+ if (toAdd.length > 0) {
705
+ try { res.headers.set('vary', existing ? `${existing}, ${toAdd.join(', ')}` : toAdd.join(', ')); } catch { /* ignore */ }
706
+ }
524
707
  }
525
708
  }
526
709
  }
@@ -539,14 +722,7 @@ export class BareJS<
539
722
  return applyCtxHeaders(Response.json(res ?? null, { status }), ctx);
540
723
  };
541
724
 
542
- const hError = (err: any, ctx: Context): Response | Promise<Response> => {
543
- if (customError) {
544
- const res = customError(err, ctx);
545
- if (res && typeof res.then === 'function') {
546
- return res.then((resolved: any) => formatCustomError(resolved, ctx));
547
- }
548
- return formatCustomError(res, ctx);
549
- }
725
+ const defaultErrorRes = (err: any, ctx: Context): Response => {
550
726
  if (err?.status >= 400 && err?.status < 500) {
551
727
  return applyCtxHeaders(Response.json({
552
728
  status: err.status,
@@ -560,6 +736,24 @@ export class BareJS<
560
736
  }, { status: 500 }), ctx);
561
737
  };
562
738
 
739
+ const hError = (err: any, ctx: Context): Response | Promise<Response> => {
740
+ if (customError) {
741
+ try {
742
+ const res = customError(err, ctx);
743
+ if (res && typeof res.then === 'function') {
744
+ return res.then(
745
+ (resolved: any) => formatCustomError(resolved, ctx),
746
+ (handlerErr: any) => defaultErrorRes(handlerErr, ctx)
747
+ );
748
+ }
749
+ return formatCustomError(res, ctx);
750
+ } catch (handlerErr) {
751
+ return defaultErrorRes(handlerErr, ctx);
752
+ }
753
+ }
754
+ return defaultErrorRes(err, ctx);
755
+ };
756
+
563
757
  const hoistedHandlers: Function[] = [];
564
758
  const register = (h: Function) => {
565
759
  const name = `h${hoistedHandlers.length}`;
@@ -567,33 +761,35 @@ export class BareJS<
567
761
  return name;
568
762
  };
569
763
 
570
- const rawRouterCode = tree.jitCompile(register);
571
764
  const EMPTY_PARAMS = Object.freeze({});
572
- const hNames = hoistedHandlers.map((_, i) => `h${i}`);
573
765
 
574
- const hasIdem = this.routes.some((r: any) => r.handlers.some((h: any) => h?.__idempotencyCommit));
575
- const deriveCleanup = this._hasDerive
766
+ const hasIdem = this.routes.some((r: any) => r.handlers.some((h: any) => h?.__idempotencyCommit)) ||
767
+ this.groupMiddleware.some((m: any) => m?.__idempotencyCommit);
768
+ const hasDerive = this._hasDerive || this.routes.some((r: any) => r.handlers.some((h: any) => h?.__isDerive));
769
+ const deriveCleanup = hasDerive
576
770
  ? `if (ctx._derivedKeys) { for (let i = 0; i < ctx._derivedKeys.length; i++) delete ctx[ctx._derivedKeys[i]]; ctx._derivedKeys = undefined; }`
577
771
  : '';
578
772
  const idemCleanup = hasIdem
579
- ? `if (ctx._idempotencyKey) { ctx._idemInFlight.delete(ctx._idempotencyKey); ctx._idempotencyKey = undefined; ctx._idemInFlight = undefined; }`
773
+ ? `if (ctx._idempotencyKey) { if (ctx._idemInFlight) ctx._idemInFlight.delete(ctx._idempotencyKey); ctx._idempotencyKey = undefined; ctx._idemInFlight = undefined; }`
580
774
  : '';
581
775
 
582
776
  const releaseCode = `
583
- if (ctx.store.size > 0) ctx.store.clear();
584
- ${deriveCleanup}
585
- ${idemCleanup}
586
- ctx.req = undefined;
587
- ctx._status = 200;
588
- ctx.body = undefined;
589
- ctx._query = undefined;
590
- ctx._cookies = undefined;
591
- ctx._setCookies = undefined;
592
- ctx._headers = undefined;
593
- ctx._requestId = undefined;
594
- ctx._peerIp = undefined;
595
- ctx.params = EMPTY_PARAMS;
596
- if (poolTop < maxPool) pool[poolTop++] = ctx;
777
+ if (!ctx._detached) {
778
+ if (ctx.store.size > 0) ctx.store.clear();
779
+ ${deriveCleanup}
780
+ ${idemCleanup}
781
+ ctx.req = undefined;
782
+ ctx._status = 200;
783
+ ctx.body = undefined;
784
+ ctx._query = undefined;
785
+ ctx._cookies = undefined;
786
+ ctx._setCookies = undefined;
787
+ ctx._headers = undefined;
788
+ ctx._requestId = undefined;
789
+ ctx._peerIp = undefined;
790
+ ctx.params = EMPTY_PARAMS;
791
+ if (poolTop < maxPool) pool[poolTop++] = ctx;
792
+ }
597
793
  `;
598
794
 
599
795
  const handleErrCode = `const errRes = hError(e, ctx);
@@ -603,22 +799,60 @@ export class BareJS<
603
799
  return errRes;`;
604
800
 
605
801
  const callSuffix = isLog ? '(ctx, doLog)' : '(ctx)';
606
- const routerCode = rawRouterCode.replace(
607
- /return (h\d+)\(ctx\);/g,
608
- `out = $1${callSuffix};
609
- if (out && out.then) return out.then((v) => { ${releaseCode} return v; }, (e) => { ${handleErrCode} });
610
- ${releaseCode}
611
- return out;`
802
+ const useCompactEmit = this.routes.length > 16;
803
+ const routerCode = tree.jitCompile(register, 0, 'url', 's', [], (hName: string) =>
804
+ useCompactEmit
805
+ ? `out = ${hName}${callSuffix};
806
+ if (out && out.then) return out.then((v) => { _rel(ctx); return v; }, (e) => _onErr(e, ctx${isLog ? ', doLog' : ''}));
807
+ _rel(ctx);
808
+ return out;`
809
+ : `out = ${hName}${callSuffix};
810
+ if (out && out.then) return out.then((v) => { ${releaseCode} return v; }, (e) => { ${handleErrCode} });
811
+ ${releaseCode}
812
+ return out;`
612
813
  );
613
814
 
815
+ const hNames = hoistedHandlers.map((_, i) => `h${i}`);
816
+
614
817
  const hasGlobalMw = this.groupMiddleware.length > 0;
615
- const hOptions = hasGlobalMw ? this.compileHandler(this.groupMiddleware, isLog) : undefined;
818
+ const runGlobalOptions = hasGlobalMw
819
+ ? async (ctx: Context) => {
820
+ const mws = this.groupMiddleware;
821
+ const dispatch = async (idx: number): Promise<Response | undefined> => {
822
+ if (idx >= mws.length) return undefined;
823
+ let nextCalled = false;
824
+ let downstreamRes: Response | undefined;
825
+ const r = await mws[idx](ctx, () => {
826
+ nextCalled = true;
827
+ return dispatch(idx + 1).then((res) => {
828
+ downstreamRes = res;
829
+ return res;
830
+ });
831
+ });
832
+ if (r instanceof Response) return applyCtxHeaders(r, ctx);
833
+ if (downstreamRes instanceof Response) return downstreamRes;
834
+ if (!nextCalled) return dispatch(idx + 1);
835
+ return undefined;
836
+ };
837
+ return dispatch(0);
838
+ }
839
+ : undefined;
616
840
  const optionsFallback = hasGlobalMw
617
841
  ? `if (method === 'OPTIONS') {
618
- out = hOptions${callSuffix};
619
- if (out && out.then) return out.then((v) => { ${releaseCode} return v; }, (e) => { ${handleErrCode} });
620
- ${releaseCode}
621
- return out;
842
+ out = runGlobalOptions(ctx);
843
+ if (out && out.then) {
844
+ return out.then((v) => {
845
+ if (v instanceof Response) { ${isLog ? 'doLog(v.status);' : ''} ${releaseCode} return v; }
846
+ const errorBody = hNotFound();
847
+ const status = errorBody.status || 404;
848
+ const nfRes = applyCtxHeaders(Response.json(errorBody, { status }), ctx);
849
+ ${isLog ? 'doLog(status);' : ''}
850
+ ${releaseCode}
851
+ return nfRes;
852
+ }, (e) => {
853
+ ${handleErrCode}
854
+ });
855
+ }
622
856
  }`
623
857
  : '';
624
858
 
@@ -628,8 +862,18 @@ export class BareJS<
628
862
  const mws = this.groupMiddleware;
629
863
  const dispatch = async (idx: number): Promise<Response | undefined> => {
630
864
  if (idx >= mws.length) return undefined;
631
- const r = await mws[idx](ctx, () => dispatch(idx + 1));
865
+ let nextCalled = false;
866
+ let downstreamRes: Response | undefined;
867
+ const r = await mws[idx](ctx, () => {
868
+ nextCalled = true;
869
+ return dispatch(idx + 1).then((res) => {
870
+ downstreamRes = res;
871
+ return res;
872
+ });
873
+ });
632
874
  if (r instanceof Response) return applyCtxHeaders(r, ctx);
875
+ if (downstreamRes instanceof Response) return downstreamRes;
876
+ if (!nextCalled) return dispatch(idx + 1);
633
877
  return undefined;
634
878
  };
635
879
  return dispatch(0);
@@ -655,9 +899,19 @@ export class BareJS<
655
899
  }`
656
900
  : '';
657
901
 
658
- const trustProxyVal = this._trustProxy;
659
- const args = ['pool', 'maxPool', 'Context', 'hNotFound', 'hError', 'applyCtxHeaders', 'EMPTY_PARAMS', 'trustProxyVal', ...(hasGlobalMw ? ['hOptions'] : []), ...(hasStaticMw ? ['runStatic'] : []), ...hNames];
660
- const values = [pool, maxPool, Context, hNotFound, hError, applyCtxHeaders, EMPTY_PARAMS, trustProxyVal, ...(hasGlobalMw ? [hOptions] : []), ...(hasStaticMw ? [runStatic] : []), ...hoistedHandlers];
902
+ const globalCorsMws = this.groupMiddleware.filter((m: any) => m?.__isCors);
903
+ const apply404Cors = globalCorsMws.length > 0
904
+ ? (res: Response, ctx: Context): Response => {
905
+ for (let i = 0; i < globalCorsMws.length; i++) {
906
+ try { globalCorsMws[i](ctx, () => res); } catch {}
907
+ }
908
+ return applyCtxHeaders(res, ctx);
909
+ }
910
+ : undefined;
911
+
912
+ const trustProxyBox = this._trustProxyBox;
913
+ const args = ['pool', 'maxPool', 'Context', 'hNotFound', 'hError', 'applyCtxHeaders', 'EMPTY_PARAMS', 'trustProxyBox', ...(hasGlobalMw ? ['runGlobalOptions'] : []), ...(hasStaticMw ? ['runStatic'] : []), ...(apply404Cors ? ['apply404Cors'] : []), ...hNames];
914
+ const values = [pool, maxPool, Context, hNotFound, hError, applyCtxHeaders, EMPTY_PARAMS, trustProxyBox, ...(hasGlobalMw ? [runGlobalOptions] : []), ...(hasStaticMw ? [runStatic] : []), ...(apply404Cors ? [apply404Cors] : []), ...hoistedHandlers];
661
915
 
662
916
  const logInit = isLog ? `
663
917
  const start = performance.now();
@@ -672,8 +926,13 @@ export class BareJS<
672
926
  );
673
927
  };` : '';
674
928
 
929
+ const compactHelpers = useCompactEmit
930
+ ? `
931
+ const _rel = (ctx) => { ${releaseCode} };
932
+ const _onErr = (e, ctx${isLog ? ', doLog' : ''}) => { ${handleErrCode} };`
933
+ : '';
675
934
  const fnBody = `
676
- let poolTop = maxPool;
935
+ let poolTop = maxPool;${compactHelpers}
677
936
  return function(req, peerIp) {
678
937
  const url = req.url;
679
938
  let s = url.indexOf('/', 8);
@@ -683,7 +942,7 @@ export class BareJS<
683
942
  else s = urlLen;
684
943
 
685
944
  const method = req.method;
686
- const ctx = poolTop > 0 ? pool[--poolTop] : new Context(trustProxyVal);
945
+ const ctx = poolTop > 0 ? pool[--poolTop] : new Context(trustProxyBox.val);
687
946
  let out;
688
947
  ${logInit}
689
948
 
@@ -699,7 +958,7 @@ export class BareJS<
699
958
 
700
959
  const errorBody = hNotFound();
701
960
  const status = errorBody.status || 404;
702
- const nfRes = applyCtxHeaders(Response.json(errorBody, { status }), ctx);
961
+ const nfRes = ${apply404Cors ? 'apply404Cors(Response.json(errorBody, { status }), ctx)' : 'applyCtxHeaders(Response.json(errorBody, { status }), ctx)'};
703
962
  ${isLog ? 'doLog(status);' : ''}
704
963
  ${releaseCode}
705
964
  return nfRes;
@@ -740,7 +999,7 @@ export class BareJS<
740
999
  public name: string = "App";
741
1000
 
742
1001
  public trustProxy(enabled: boolean = true): this {
743
- this._trustProxy = enabled;
1002
+ this._trustProxyBox.val = enabled;
744
1003
  for (let i = 0; i < this.pool.length; i++) {
745
1004
  this.pool[i]!._trustProxy = enabled;
746
1005
  }
@@ -753,15 +1012,13 @@ export class BareJS<
753
1012
  reusePort: boolean = true,
754
1013
  options: { maxRequestBodySize?: number; trustProxy?: boolean } = {}
755
1014
  ) {
756
- if (!this.compiled) this.compile();
757
1015
  if (options.trustProxy !== undefined) {
758
1016
  this.trustProxy(options.trustProxy);
759
1017
  }
1018
+ if (!this.compiled) this.compile();
760
1019
  const maxRequestBodySize = options.maxRequestBodySize ?? 10 * 1024 * 1024;
761
1020
 
762
- const { BARE_CONFIG } = require("./config");
763
-
764
- const finalPort = port || BARE_CONFIG.port || 3000;
1021
+ const finalPort = port ?? BARE_CONFIG.port ?? 3000;
765
1022
  const isProd = process.env.NODE_ENV === 'production';
766
1023
 
767
1024
  if (!isProd) {
@@ -794,7 +1051,8 @@ export class BareJS<
794
1051
  const s = url.indexOf('/', 8);
795
1052
  const q = s === -1 ? -1 : url.indexOf('?', s);
796
1053
  const path = s === -1 ? '/' : (q === -1 ? url.slice(s) : url.slice(s, q));
797
- const normalized = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;
1054
+ const collapsed = path.replace(/\/+/g, '/');
1055
+ const normalized = collapsed.length > 1 && collapsed.endsWith('/') ? collapsed.slice(0, -1) : collapsed;
798
1056
  let handler = wsRoutes.get(normalized);
799
1057
  let params: Record<string, string> | undefined;
800
1058
  if (!handler) {