barejs 0.1.55 → 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
@@ -68,9 +68,8 @@ export class BareJS<
68
68
  // private poolIdx = 0;
69
69
  private hotFetch?: (req: Request, peerIp?: string) => any;
70
70
  private compiled = false;
71
- private poolMask: number;
72
71
  private _useLog: boolean = false;
73
- private _trustProxy: boolean = false;
72
+ private _trustProxyBox = { val: false };
74
73
  private errorHandler?: (err: any, ctx: Context) => any;
75
74
  private wsRoutes = new Map<string, WebSocketRouteHandler>();
76
75
  private startHooks: (() => void | Promise<void>)[] = [];
@@ -110,6 +109,9 @@ export class BareJS<
110
109
  fn: () => void | Promise<void>,
111
110
  options: CronOptions = {}
112
111
  ): this {
112
+ if (!Number.isFinite(intervalMs) || intervalMs <= 0) {
113
+ throw new RangeError(`cron("${name}") intervalMs must be a positive finite number`);
114
+ }
113
115
  let running = false;
114
116
  const tick = async () => {
115
117
  if (running) return;
@@ -146,14 +148,17 @@ export class BareJS<
146
148
  this.server = undefined;
147
149
  }
148
150
  for (const hook of this.stopHooks) {
149
- await hook();
151
+ try {
152
+ await hook();
153
+ } catch (e) {
154
+ console.error(`[${this.name}] onStop error:`, e);
155
+ }
150
156
  }
151
157
  }
152
158
  constructor(poolSize: number = 1024) {
153
159
  super();
154
160
  bootstrapConfig();
155
161
  const size = Math.pow(2, Math.ceil(Math.log2(poolSize)));
156
- this.poolMask = size - 1;
157
162
  for (let i = 0; i < size; i++) {
158
163
  this.pool.push(new Context());
159
164
  }
@@ -198,7 +203,7 @@ export class BareJS<
198
203
 
199
204
  this.get(jsonPath, () => {
200
205
  if (!cachedSpec) {
201
- cachedSpec = JSON.stringify(generateOpenAPISpec(this.routes, { title: this.name, ...options }));
206
+ cachedSpec = JSON.stringify(generateOpenAPISpec(this.routes, { title: this.name, excludePaths: [basePath, jsonPath], ...options }));
202
207
  }
203
208
  return new Response(cachedSpec, {
204
209
  status: 200,
@@ -289,23 +294,38 @@ export class BareJS<
289
294
  };
290
295
 
291
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
+ ]);
292
308
  public derive<T extends Record<string, any>>(fn: (ctx: Context & Derived) => Promise<T> | T): BareJS<Derived & T, Routes> {
293
309
  this._hasDerive = true;
294
- this.use(async (ctx: any, next: any) => {
310
+ const deriveMw = async (ctx: any, next: any) => {
295
311
  const derived = await fn(ctx);
296
312
  if (derived && typeof derived === 'object') {
297
313
  const keys = Object.keys(derived);
298
314
  if (!ctx._derivedKeys) ctx._derivedKeys = [];
299
315
  for (let i = 0; i < keys.length; i++) {
300
316
  const k = keys[i]!;
301
- 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)) {
302
320
  ctx[k] = (derived as any)[k];
303
321
  ctx._derivedKeys.push(k);
304
322
  }
305
323
  }
306
324
  }
307
325
  return next();
308
- });
326
+ };
327
+ (deriveMw as any).__isDerive = true;
328
+ this.use(deriveMw);
309
329
  return this as any;
310
330
  }
311
331
 
@@ -320,8 +340,16 @@ export class BareJS<
320
340
  if (ctx._headers) {
321
341
  for (const k in ctx._headers) {
322
342
  const val = ctx._headers[k];
323
- if (val !== undefined && !res.headers.has(k)) {
343
+ if (val === undefined) continue;
344
+ if (!res.headers.has(k)) {
324
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
+ }
325
353
  }
326
354
  }
327
355
  }
@@ -334,9 +362,67 @@ export class BareJS<
334
362
  return res;
335
363
  };
336
364
 
337
- const timeoutMw = pipeline.find((fn) => fn?.__timeout);
338
- if (timeoutMw) {
339
- const { ms, status, message } = timeoutMw.__timeout;
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;
340
426
  const innerPipeline = pipeline.filter((fn) => !fn?.__timeout);
341
427
  const innerCompiled = this.compileHandler(innerPipeline, isLog);
342
428
  return async (ctx: Context, doLog?: any) => {
@@ -347,7 +433,13 @@ export class BareJS<
347
433
  const timeoutPromise = new Promise<Response>((resolve) => {
348
434
  timer = setTimeout(() => {
349
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
+ }
350
441
  if (typeof res.catch === 'function') res.catch(() => {});
442
+ if (isLog && doLog) doLog(status);
351
443
  resolve(applyCtxHeadersToRes(Response.json({ status: 'error', code: 'REQUEST_TIMEOUT', message }, { status }), ctx));
352
444
  }, ms);
353
445
  });
@@ -358,25 +450,6 @@ export class BareJS<
358
450
  };
359
451
  }
360
452
 
361
- const cbMw = pipeline.find((fn) => fn?.__circuitBreaker);
362
- if (cbMw) {
363
- const runWithBreaker = cbMw.__circuitBreaker;
364
- const innerPipeline = pipeline.filter((fn) => !fn?.__circuitBreaker);
365
- const innerCompiled = this.compileHandler(innerPipeline, isLog);
366
- return (ctx: Context, doLog?: any) => runWithBreaker(() => innerCompiled(ctx, doLog));
367
- }
368
-
369
- const compMw = pipeline.find((fn) => fn?.__compress);
370
- if (compMw) {
371
- const applyCompress = compMw.__compress;
372
- const innerPipeline = pipeline.filter((fn) => !fn?.__compress);
373
- const innerCompiled = this.compileHandler(innerPipeline, isLog);
374
- return async (ctx: Context, doLog?: any) => {
375
- const res = await innerCompiled(ctx, doLog);
376
- return applyCompress(ctx, res);
377
- };
378
- }
379
-
380
453
  const len = pipeline.length;
381
454
  const rFilterMw = pipeline.find((fn) => fn?.__responseFilter);
382
455
  const rFilter = rFilterMw?.__responseFilter;
@@ -388,30 +461,37 @@ export class BareJS<
388
461
  const json200 = { status: 200, headers: { "content-type": "application/json" } };
389
462
  const text200 = { status: 200, headers: { "content-type": "text/plain" } };
390
463
 
391
- const logResCode = isLog ? 'doLog(res.status);' : '';
392
- const logStatusCode = isLog ? 'doLog(finalStatus);' : '';
464
+ const logResCode = isLog ? 'if (!ctx._detached) doLog(res.status);' : '';
465
+ const logStatusCode = isLog ? 'if (!ctx._detached) doLog(finalStatus);' : '';
393
466
 
394
- // Inline Finalizer
395
- const finalizeCode = `
396
- ${rFilter ? 'res = rFilter(res);' : ''}
397
- if (res instanceof Response) {
398
- ${idemCommit ? 'idemCommit(ctx, res, res.status);' : ''}
399
- if (ctx._headers) {
400
- for (const k in ctx._headers) {
401
- 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
+ }
402
481
  }
403
482
  }
404
- if (ctx._setCookies) {
405
- 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 {}
406
487
  }
407
- ${logResCode}
408
- return res;
409
488
  }
410
-
411
- const finalStatus = ctx._status || 200;
412
- ${idemCommit ? 'idemCommit(ctx, res, finalStatus);' : ''}
413
- ${logStatusCode}
489
+ ${logResCode}
490
+ return res;
491
+ `;
414
492
 
493
+ const buildNonResFinalize = `
494
+ ${logStatusCode}
415
495
  let outRes;
416
496
  if (typeof res === 'string') {
417
497
  if (finalStatus === 200 && !ctx._headers) {
@@ -437,21 +517,39 @@ export class BareJS<
437
517
  }
438
518
 
439
519
  if (ctx._setCookies) {
440
- 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
+ }
441
523
  }
442
524
  return outRes;
443
525
  `;
444
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
+
445
540
  const argSig = isLog ? 'ctx, doLog' : 'ctx';
541
+ const noop = () => { };
446
542
 
447
543
  const extraNames = [
448
544
  'applyShortCircuit',
545
+ 'noop',
449
546
  ...(rFilter ? ['rFilter'] : []),
450
547
  ...(idemCommit ? ['idemCommit'] : []),
451
548
  ...(idemRelease ? ['idemRelease'] : [])
452
549
  ];
453
550
  const extraVals = [
454
551
  applyCtxHeadersToRes,
552
+ noop,
455
553
  ...(rFilter ? [rFilter] : []),
456
554
  ...(idemCommit ? [idemCommit] : []),
457
555
  ...(idemRelease ? [idemRelease] : [])
@@ -484,14 +582,14 @@ export class BareJS<
484
582
  if (fn0.constructor.name === 'AsyncFunction') {
485
583
  return wrapIdem(
486
584
  new Function('fn0', 'json200', 'text200', ...extraNames, `let lastHdrs = null, lastInit200 = null; return async function(${argSig}) {
487
- const res = await fn0(ctx);
585
+ const res = await fn0(ctx, noop);
488
586
  ${finalizeCode}
489
587
  }`)(fn0, json200, text200, ...extraVals)
490
588
  );
491
589
  }
492
590
  return wrapIdem(
493
591
  new Function('fn0', 'json200', 'text200', ...extraNames, `let lastHdrs = null, lastInit200 = null; return function(${argSig}) {
494
- const res = fn0(ctx);
592
+ const res = fn0(ctx, noop);
495
593
  if (res && res.then) return res.then(v => { const res = v; ${finalizeCode} });
496
594
  ${finalizeCode}
497
595
  }`)(fn0, json200, text200, ...extraVals)
@@ -504,48 +602,88 @@ export class BareJS<
504
602
 
505
603
  // Middleware Hoisting: Pass functions as arguments to avoid array lookup
506
604
  const fnNames = pipeline.map((_, i) => `fn${i}`);
605
+ let continueAsyncDef = '';
507
606
 
508
607
  if (isAsync) {
509
608
  for (let i = 0; i < len - 1; i++) {
510
609
  code += `let r${i} = fn${i}(ctx, noop);\n`;
511
610
  code += `if (r${i}) {\n`;
512
611
  code += ` if (r${i}.then) r${i} = await r${i};\n`;
513
- code += ` if (r${i} instanceof Response) { applyShortCircuit(r${i}, ctx); ${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`;
514
613
  code += `}\n`;
515
614
  }
516
615
  code += `
517
- let res = fn${len - 1}(ctx);
616
+ let res = fn${len - 1}(ctx, noop);
518
617
  if (res && res.then) res = await res;
519
618
  ${finalizeCode}
520
619
  `;
521
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
+ `;
522
638
  for (let i = 0; i < len - 1; i++) {
523
639
  code += `const r${i} = fn${i}(ctx, noop);\n`;
524
- code += `if (r${i} && r${i} instanceof Response) { applyShortCircuit(r${i}, ctx); ${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`;
525
644
  }
526
645
  code += `
527
- let res = fn${len - 1}(ctx);
646
+ let res = fn${len - 1}(ctx, noop);
528
647
  if (res && res.then) return res.then(v => { let res = v; ${finalizeCode} });
529
648
  ${finalizeCode}
530
649
  `;
531
650
  }
532
651
 
533
- const noop = () => { };
534
652
  const fnHeader = isAsync
535
653
  ? `let lastHdrs = null, lastInit200 = null; return async function(${argSig})`
536
- : `let lastHdrs = null, lastInit200 = null; return function(${argSig})`;
654
+ : `let lastHdrs = null, lastInit200 = null; ${continueAsyncDef} return function(${argSig})`;
537
655
 
538
656
  return wrapIdem(
539
- 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)
540
658
  );
541
659
  }
542
660
 
543
661
  public compile() {
544
662
  const isLog = this._useLog;
545
663
  this.tree = new RadixNode();
664
+ const explicitOptionsPaths = new Set<string>();
546
665
  for (const route of this.routes) {
666
+ if (route.method === 'OPTIONS') explicitOptionsPaths.add(route.path);
547
667
  this.tree.insert(route.path, route.method, this.compileHandler(route.handlers, isLog));
548
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
+ }
549
687
 
550
688
  const tree = this.tree;
551
689
  const pool = this.pool;
@@ -556,8 +694,16 @@ export class BareJS<
556
694
  if (ctx._headers) {
557
695
  for (const k in ctx._headers) {
558
696
  const val = ctx._headers[k];
559
- if (val !== undefined && !res.headers.has(k)) {
697
+ if (val === undefined) continue;
698
+ if (!res.headers.has(k)) {
560
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
+ }
561
707
  }
562
708
  }
563
709
  }
@@ -576,14 +722,7 @@ export class BareJS<
576
722
  return applyCtxHeaders(Response.json(res ?? null, { status }), ctx);
577
723
  };
578
724
 
579
- const hError = (err: any, ctx: Context): Response | Promise<Response> => {
580
- if (customError) {
581
- const res = customError(err, ctx);
582
- if (res && typeof res.then === 'function') {
583
- return res.then((resolved: any) => formatCustomError(resolved, ctx));
584
- }
585
- return formatCustomError(res, ctx);
586
- }
725
+ const defaultErrorRes = (err: any, ctx: Context): Response => {
587
726
  if (err?.status >= 400 && err?.status < 500) {
588
727
  return applyCtxHeaders(Response.json({
589
728
  status: err.status,
@@ -597,6 +736,24 @@ export class BareJS<
597
736
  }, { status: 500 }), ctx);
598
737
  };
599
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
+
600
757
  const hoistedHandlers: Function[] = [];
601
758
  const register = (h: Function) => {
602
759
  const name = `h${hoistedHandlers.length}`;
@@ -604,16 +761,16 @@ export class BareJS<
604
761
  return name;
605
762
  };
606
763
 
607
- const rawRouterCode = tree.jitCompile(register);
608
764
  const EMPTY_PARAMS = Object.freeze({});
609
- const hNames = hoistedHandlers.map((_, i) => `h${i}`);
610
765
 
611
- const hasIdem = this.routes.some((r: any) => r.handlers.some((h: any) => h?.__idempotencyCommit));
612
- 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
613
770
  ? `if (ctx._derivedKeys) { for (let i = 0; i < ctx._derivedKeys.length; i++) delete ctx[ctx._derivedKeys[i]]; ctx._derivedKeys = undefined; }`
614
771
  : '';
615
772
  const idemCleanup = hasIdem
616
- ? `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; }`
617
774
  : '';
618
775
 
619
776
  const releaseCode = `
@@ -642,22 +799,60 @@ export class BareJS<
642
799
  return errRes;`;
643
800
 
644
801
  const callSuffix = isLog ? '(ctx, doLog)' : '(ctx)';
645
- const routerCode = rawRouterCode.replace(
646
- /return (h\d+)\(ctx\);/g,
647
- `out = $1${callSuffix};
648
- if (out && out.then) return out.then((v) => { ${releaseCode} return v; }, (e) => { ${handleErrCode} });
649
- ${releaseCode}
650
- 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;`
651
813
  );
652
814
 
815
+ const hNames = hoistedHandlers.map((_, i) => `h${i}`);
816
+
653
817
  const hasGlobalMw = this.groupMiddleware.length > 0;
654
- 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;
655
840
  const optionsFallback = hasGlobalMw
656
841
  ? `if (method === 'OPTIONS') {
657
- out = hOptions${callSuffix};
658
- if (out && out.then) return out.then((v) => { ${releaseCode} return v; }, (e) => { ${handleErrCode} });
659
- ${releaseCode}
660
- 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
+ }
661
856
  }`
662
857
  : '';
663
858
 
@@ -667,8 +862,18 @@ export class BareJS<
667
862
  const mws = this.groupMiddleware;
668
863
  const dispatch = async (idx: number): Promise<Response | undefined> => {
669
864
  if (idx >= mws.length) return undefined;
670
- 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
+ });
671
874
  if (r instanceof Response) return applyCtxHeaders(r, ctx);
875
+ if (downstreamRes instanceof Response) return downstreamRes;
876
+ if (!nextCalled) return dispatch(idx + 1);
672
877
  return undefined;
673
878
  };
674
879
  return dispatch(0);
@@ -694,9 +899,19 @@ export class BareJS<
694
899
  }`
695
900
  : '';
696
901
 
697
- const trustProxyVal = this._trustProxy;
698
- const args = ['pool', 'maxPool', 'Context', 'hNotFound', 'hError', 'applyCtxHeaders', 'EMPTY_PARAMS', 'trustProxyVal', ...(hasGlobalMw ? ['hOptions'] : []), ...(hasStaticMw ? ['runStatic'] : []), ...hNames];
699
- 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];
700
915
 
701
916
  const logInit = isLog ? `
702
917
  const start = performance.now();
@@ -711,8 +926,13 @@ export class BareJS<
711
926
  );
712
927
  };` : '';
713
928
 
929
+ const compactHelpers = useCompactEmit
930
+ ? `
931
+ const _rel = (ctx) => { ${releaseCode} };
932
+ const _onErr = (e, ctx${isLog ? ', doLog' : ''}) => { ${handleErrCode} };`
933
+ : '';
714
934
  const fnBody = `
715
- let poolTop = maxPool;
935
+ let poolTop = maxPool;${compactHelpers}
716
936
  return function(req, peerIp) {
717
937
  const url = req.url;
718
938
  let s = url.indexOf('/', 8);
@@ -722,7 +942,7 @@ export class BareJS<
722
942
  else s = urlLen;
723
943
 
724
944
  const method = req.method;
725
- const ctx = poolTop > 0 ? pool[--poolTop] : new Context(trustProxyVal);
945
+ const ctx = poolTop > 0 ? pool[--poolTop] : new Context(trustProxyBox.val);
726
946
  let out;
727
947
  ${logInit}
728
948
 
@@ -738,7 +958,7 @@ export class BareJS<
738
958
 
739
959
  const errorBody = hNotFound();
740
960
  const status = errorBody.status || 404;
741
- const nfRes = applyCtxHeaders(Response.json(errorBody, { status }), ctx);
961
+ const nfRes = ${apply404Cors ? 'apply404Cors(Response.json(errorBody, { status }), ctx)' : 'applyCtxHeaders(Response.json(errorBody, { status }), ctx)'};
742
962
  ${isLog ? 'doLog(status);' : ''}
743
963
  ${releaseCode}
744
964
  return nfRes;
@@ -779,7 +999,7 @@ export class BareJS<
779
999
  public name: string = "App";
780
1000
 
781
1001
  public trustProxy(enabled: boolean = true): this {
782
- this._trustProxy = enabled;
1002
+ this._trustProxyBox.val = enabled;
783
1003
  for (let i = 0; i < this.pool.length; i++) {
784
1004
  this.pool[i]!._trustProxy = enabled;
785
1005
  }
@@ -792,13 +1012,13 @@ export class BareJS<
792
1012
  reusePort: boolean = true,
793
1013
  options: { maxRequestBodySize?: number; trustProxy?: boolean } = {}
794
1014
  ) {
795
- if (!this.compiled) this.compile();
796
1015
  if (options.trustProxy !== undefined) {
797
1016
  this.trustProxy(options.trustProxy);
798
1017
  }
1018
+ if (!this.compiled) this.compile();
799
1019
  const maxRequestBodySize = options.maxRequestBodySize ?? 10 * 1024 * 1024;
800
1020
 
801
- const finalPort = port || BARE_CONFIG.port || 3000;
1021
+ const finalPort = port ?? BARE_CONFIG.port ?? 3000;
802
1022
  const isProd = process.env.NODE_ENV === 'production';
803
1023
 
804
1024
  if (!isProd) {
@@ -831,7 +1051,8 @@ export class BareJS<
831
1051
  const s = url.indexOf('/', 8);
832
1052
  const q = s === -1 ? -1 : url.indexOf('?', s);
833
1053
  const path = s === -1 ? '/' : (q === -1 ? url.slice(s) : url.slice(s, q));
834
- 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;
835
1056
  let handler = wsRoutes.get(normalized);
836
1057
  let params: Record<string, string> | undefined;
837
1058
  if (!handler) {