barejs 0.1.51 → 0.1.52
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/README.md +50 -29
- package/dist/index.js +87 -80
- package/dist/types/core/bare.d.ts +10 -2
- package/dist/types/core/context.d.ts +1 -1
- package/dist/types/core/router.d.ts +61 -10
- package/dist/types/index.d.ts +5 -4
- package/dist/types/security/auth.d.ts +15 -4
- package/dist/types/security/idempotency.d.ts +3 -0
- package/dist/types/security/rateLimit.d.ts +3 -0
- package/dist/types/security/store.d.ts +36 -0
- package/dist/types/utils/compress.d.ts +6 -3
- package/dist/types/utils/static.d.ts +8 -0
- package/llms.txt +18 -19
- package/package.json +1 -1
- package/src/core/bare.ts +101 -42
- package/src/core/context.ts +26 -11
- package/src/core/router.ts +94 -16
- package/src/index.ts +13 -4
- package/src/security/auth.ts +241 -49
- package/src/security/idempotency.ts +120 -26
- package/src/security/rateLimit.ts +40 -22
- package/src/security/store.ts +151 -0
- package/src/security/validators.ts +9 -4
- package/src/utils/compress.ts +38 -7
- package/src/utils/static.ts +65 -15
package/src/core/bare.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BareRouter, type InferSchema } from './router';
|
|
1
|
+
import { BareRouter, type InferSchema, type PrefixRoutes } from './router';
|
|
2
2
|
import { RadixNode } from './radix';
|
|
3
3
|
import { Context } from './context';
|
|
4
4
|
import { Type as typebox, Type as t } from '@sinclair/typebox';
|
|
@@ -65,10 +65,11 @@ export class BareJS<
|
|
|
65
65
|
private tree = new RadixNode();
|
|
66
66
|
private pool: Context[] = [];
|
|
67
67
|
// private poolIdx = 0;
|
|
68
|
-
private hotFetch?: (req: Request) => any;
|
|
68
|
+
private hotFetch?: (req: Request, peerIp?: string) => any;
|
|
69
69
|
private compiled = false;
|
|
70
70
|
private poolMask: number;
|
|
71
71
|
private _useLog: boolean = false;
|
|
72
|
+
private _trustProxy: boolean = true;
|
|
72
73
|
private errorHandler?: (err: any, ctx: Context) => any;
|
|
73
74
|
private wsRoutes = new Map<string, WebSocketRouteHandler>();
|
|
74
75
|
private startHooks: (() => void | Promise<void>)[] = [];
|
|
@@ -265,8 +266,14 @@ export class BareJS<
|
|
|
265
266
|
declare public head: AddRoute<Derived, Routes, 'HEAD'>;
|
|
266
267
|
declare public all: AddRoute<Derived, Routes, 'ALL'>;
|
|
267
268
|
|
|
269
|
+
declare public route: <P extends string, R2 extends RouteSchema = {}>(
|
|
270
|
+
prefix: P,
|
|
271
|
+
router: BareRouter<R2>
|
|
272
|
+
) => BareJS<Derived, Routes & PrefixRoutes<P, R2>>;
|
|
273
|
+
|
|
268
274
|
declare public use: {
|
|
269
275
|
<R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareJS<Derived, Routes & R2>;
|
|
276
|
+
<P extends string, R2 extends RouteSchema = {}>(prefix: P, mw: BareRouter<R2>): BareJS<Derived, Routes & PrefixRoutes<P, R2>>;
|
|
270
277
|
(mw: any): BareJS<Derived, Routes>;
|
|
271
278
|
};
|
|
272
279
|
|
|
@@ -353,7 +360,7 @@ export class BareJS<
|
|
|
353
360
|
const finalizeCode = `
|
|
354
361
|
${rFilter ? 'res = rFilter(res);' : ''}
|
|
355
362
|
if (res instanceof Response) {
|
|
356
|
-
${
|
|
363
|
+
${idemCommit ? 'idemCommit(ctx, res, res.status);' : ''}
|
|
357
364
|
if (ctx._headers) {
|
|
358
365
|
for (const k in ctx._headers) {
|
|
359
366
|
if (!res.headers.has(k)) res.headers.set(k, ctx._headers[k]);
|
|
@@ -381,12 +388,17 @@ export class BareJS<
|
|
|
381
388
|
});
|
|
382
389
|
}
|
|
383
390
|
} else if (finalStatus === 200 && !ctx._headers) {
|
|
384
|
-
outRes = Response.json(res ?? null
|
|
391
|
+
outRes = Response.json(res ?? null);
|
|
392
|
+
} else if (finalStatus === 200 && ctx._headers === lastHdrs) {
|
|
393
|
+
outRes = Response.json(res ?? null, lastInit200);
|
|
385
394
|
} else {
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
395
|
+
const hdrs = ctx._headers || json200.headers;
|
|
396
|
+
const init = { status: finalStatus, headers: hdrs };
|
|
397
|
+
if (finalStatus === 200 && Object.isFrozen(hdrs)) {
|
|
398
|
+
lastHdrs = hdrs;
|
|
399
|
+
lastInit200 = init;
|
|
400
|
+
}
|
|
401
|
+
outRes = Response.json(res ?? null, init);
|
|
390
402
|
}
|
|
391
403
|
|
|
392
404
|
if (ctx._setCookies) {
|
|
@@ -434,14 +446,14 @@ export class BareJS<
|
|
|
434
446
|
const fn0 = pipeline[0]!;
|
|
435
447
|
if (fn0.constructor.name === 'AsyncFunction') {
|
|
436
448
|
return wrapIdem(
|
|
437
|
-
new Function('fn0', 'json200', 'text200', ...extraNames, `return async function(${argSig}) {
|
|
449
|
+
new Function('fn0', 'json200', 'text200', ...extraNames, `let lastHdrs = null, lastInit200 = null; return async function(${argSig}) {
|
|
438
450
|
const res = await fn0(ctx);
|
|
439
451
|
${finalizeCode}
|
|
440
452
|
}`)(fn0, json200, text200, ...extraVals)
|
|
441
453
|
);
|
|
442
454
|
}
|
|
443
455
|
return wrapIdem(
|
|
444
|
-
new Function('fn0', 'json200', 'text200', ...extraNames, `return function(${argSig}) {
|
|
456
|
+
new Function('fn0', 'json200', 'text200', ...extraNames, `let lastHdrs = null, lastInit200 = null; return function(${argSig}) {
|
|
445
457
|
const res = fn0(ctx);
|
|
446
458
|
if (res && res.then) return res.then(v => { const res = v; ${finalizeCode} });
|
|
447
459
|
${finalizeCode}
|
|
@@ -483,8 +495,8 @@ export class BareJS<
|
|
|
483
495
|
|
|
484
496
|
const noop = () => { };
|
|
485
497
|
const fnHeader = isAsync
|
|
486
|
-
? `return async function(${argSig})`
|
|
487
|
-
: `return function(${argSig})`;
|
|
498
|
+
? `let lastHdrs = null, lastInit200 = null; return async function(${argSig})`
|
|
499
|
+
: `let lastHdrs = null, lastInit200 = null; return function(${argSig})`;
|
|
488
500
|
|
|
489
501
|
return wrapIdem(
|
|
490
502
|
new Function(...fnNames, 'noop', 'json200', 'text200', ...extraNames, `${fnHeader} { ${code} }`)(...pipeline, noop, json200, text200, ...extraVals)
|
|
@@ -503,25 +515,49 @@ export class BareJS<
|
|
|
503
515
|
const maxPool = pool.length;
|
|
504
516
|
const hNotFound = this.notFoundHandler;
|
|
505
517
|
const customError = this.errorHandler;
|
|
506
|
-
const
|
|
518
|
+
const applyCtxHeaders = (res: Response, ctx: Context): Response => {
|
|
519
|
+
if (ctx._headers) {
|
|
520
|
+
for (const k in ctx._headers) {
|
|
521
|
+
const val = ctx._headers[k];
|
|
522
|
+
if (val !== undefined && !res.headers.has(k)) {
|
|
523
|
+
try { res.headers.set(k, val); } catch { /* ignore invalid header values on error path */ }
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
if (ctx._setCookies) {
|
|
528
|
+
for (let i = 0; i < ctx._setCookies.length; i++) {
|
|
529
|
+
try { res.headers.append('Set-Cookie', ctx._setCookies[i]!); } catch { /* ignore */ }
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
return res;
|
|
533
|
+
};
|
|
534
|
+
|
|
535
|
+
const formatCustomError = (res: any, ctx: Context): Response => {
|
|
536
|
+
if (res instanceof Response) return applyCtxHeaders(res, ctx);
|
|
537
|
+
const status = ctx._status >= 400 ? ctx._status : 500;
|
|
538
|
+
if (typeof res === 'string') return applyCtxHeaders(new Response(res, { status }), ctx);
|
|
539
|
+
return applyCtxHeaders(Response.json(res ?? null, { status }), ctx);
|
|
540
|
+
};
|
|
541
|
+
|
|
542
|
+
const hError = (err: any, ctx: Context): Response | Promise<Response> => {
|
|
507
543
|
if (customError) {
|
|
508
544
|
const res = customError(err, ctx);
|
|
509
|
-
if (res
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
return
|
|
545
|
+
if (res && typeof res.then === 'function') {
|
|
546
|
+
return res.then((resolved: any) => formatCustomError(resolved, ctx));
|
|
547
|
+
}
|
|
548
|
+
return formatCustomError(res, ctx);
|
|
513
549
|
}
|
|
514
550
|
if (err?.status >= 400 && err?.status < 500) {
|
|
515
|
-
return Response.json({
|
|
551
|
+
return applyCtxHeaders(Response.json({
|
|
516
552
|
status: err.status,
|
|
517
553
|
message: err.message || 'Bad Request'
|
|
518
|
-
}, { status: err.status });
|
|
554
|
+
}, { status: err.status }), ctx);
|
|
519
555
|
}
|
|
520
|
-
return Response.json({
|
|
556
|
+
return applyCtxHeaders(Response.json({
|
|
521
557
|
status: 500,
|
|
522
558
|
message: process.env.NODE_ENV === 'development' ? (err?.message || "Internal Server Error") : "Internal Server Error",
|
|
523
559
|
stack: process.env.NODE_ENV === 'development' ? err?.stack : undefined
|
|
524
|
-
}, { status: 500 });
|
|
560
|
+
}, { status: 500 }), ctx);
|
|
525
561
|
};
|
|
526
562
|
|
|
527
563
|
const hoistedHandlers: Function[] = [];
|
|
@@ -555,15 +591,22 @@ export class BareJS<
|
|
|
555
591
|
ctx._setCookies = undefined;
|
|
556
592
|
ctx._headers = undefined;
|
|
557
593
|
ctx._requestId = undefined;
|
|
594
|
+
ctx._peerIp = undefined;
|
|
558
595
|
ctx.params = EMPTY_PARAMS;
|
|
559
596
|
if (poolTop < maxPool) pool[poolTop++] = ctx;
|
|
560
597
|
`;
|
|
561
598
|
|
|
599
|
+
const handleErrCode = `const errRes = hError(e, ctx);
|
|
600
|
+
if (errRes && errRes.then) return errRes.then((r) => { ${isLog ? 'doLog(r.status || 500);' : ''} ${releaseCode} return r; });
|
|
601
|
+
${isLog ? 'doLog(errRes.status || 500);' : ''}
|
|
602
|
+
${releaseCode}
|
|
603
|
+
return errRes;`;
|
|
604
|
+
|
|
562
605
|
const callSuffix = isLog ? '(ctx, doLog)' : '(ctx)';
|
|
563
606
|
const routerCode = rawRouterCode.replace(
|
|
564
607
|
/return (h\d+)\(ctx\);/g,
|
|
565
608
|
`out = $1${callSuffix};
|
|
566
|
-
if (out && out.then) return out.then((v) => { ${releaseCode} return v; }, (e) => {
|
|
609
|
+
if (out && out.then) return out.then((v) => { ${releaseCode} return v; }, (e) => { ${handleErrCode} });
|
|
567
610
|
${releaseCode}
|
|
568
611
|
return out;`
|
|
569
612
|
);
|
|
@@ -573,7 +616,7 @@ export class BareJS<
|
|
|
573
616
|
const optionsFallback = hasGlobalMw
|
|
574
617
|
? `if (method === 'OPTIONS') {
|
|
575
618
|
out = hOptions${callSuffix};
|
|
576
|
-
if (out && out.then) return out.then((v) => { ${releaseCode} return v; }, (e) => {
|
|
619
|
+
if (out && out.then) return out.then((v) => { ${releaseCode} return v; }, (e) => { ${handleErrCode} });
|
|
577
620
|
${releaseCode}
|
|
578
621
|
return out;
|
|
579
622
|
}`
|
|
@@ -608,21 +651,20 @@ export class BareJS<
|
|
|
608
651
|
if (v instanceof Response) { ${isLog ? 'doLog(v.status);' : ''} ${releaseCode} return v; }
|
|
609
652
|
const errorBody = hNotFound();
|
|
610
653
|
const status = errorBody.status || 404;
|
|
654
|
+
const nfRes = applyCtxHeaders(Response.json(errorBody, { status }), ctx);
|
|
611
655
|
${isLog ? 'doLog(status);' : ''}
|
|
612
656
|
${releaseCode}
|
|
613
|
-
return
|
|
657
|
+
return nfRes;
|
|
614
658
|
}, (e) => {
|
|
615
|
-
|
|
616
|
-
${releaseCode}
|
|
617
|
-
${isLog ? 'doLog(errRes.status || 500);' : ''}
|
|
618
|
-
return errRes;
|
|
659
|
+
${handleErrCode}
|
|
619
660
|
});
|
|
620
661
|
}
|
|
621
662
|
}`
|
|
622
663
|
: '';
|
|
623
664
|
|
|
624
|
-
const
|
|
625
|
-
const
|
|
665
|
+
const trustProxyVal = this._trustProxy;
|
|
666
|
+
const args = ['pool', 'maxPool', 'Context', 'hNotFound', 'hError', 'applyCtxHeaders', 'EMPTY_PARAMS', 'trustProxyVal', ...(hasGlobalMw ? ['hOptions'] : []), ...(hasStaticMw ? ['runStatic'] : []), ...hNames];
|
|
667
|
+
const values = [pool, maxPool, Context, hNotFound, hError, applyCtxHeaders, EMPTY_PARAMS, trustProxyVal, ...(hasGlobalMw ? [hOptions] : []), ...(hasStaticMw ? [runStatic] : []), ...hoistedHandlers];
|
|
626
668
|
|
|
627
669
|
const logInit = isLog ? `
|
|
628
670
|
const start = performance.now();
|
|
@@ -639,7 +681,7 @@ export class BareJS<
|
|
|
639
681
|
|
|
640
682
|
const fnBody = `
|
|
641
683
|
let poolTop = maxPool;
|
|
642
|
-
return function(req) {
|
|
684
|
+
return function(req, peerIp) {
|
|
643
685
|
const url = req.url;
|
|
644
686
|
let s = url.indexOf('/', 8);
|
|
645
687
|
const q = s === -1 ? -1 : url.indexOf('?', s);
|
|
@@ -648,12 +690,13 @@ export class BareJS<
|
|
|
648
690
|
else s = urlLen;
|
|
649
691
|
|
|
650
692
|
const method = req.method;
|
|
651
|
-
const ctx = poolTop > 0 ? pool[--poolTop] : new Context();
|
|
693
|
+
const ctx = poolTop > 0 ? pool[--poolTop] : new Context(trustProxyVal);
|
|
652
694
|
let out;
|
|
653
695
|
${logInit}
|
|
654
696
|
|
|
655
697
|
try {
|
|
656
698
|
ctx.req = req;
|
|
699
|
+
ctx._peerIp = peerIp;
|
|
657
700
|
|
|
658
701
|
${routerCode}
|
|
659
702
|
|
|
@@ -663,15 +706,13 @@ export class BareJS<
|
|
|
663
706
|
|
|
664
707
|
const errorBody = hNotFound();
|
|
665
708
|
const status = errorBody.status || 404;
|
|
709
|
+
const nfRes = applyCtxHeaders(Response.json(errorBody, { status }), ctx);
|
|
666
710
|
${isLog ? 'doLog(status);' : ''}
|
|
667
711
|
${releaseCode}
|
|
668
|
-
return
|
|
712
|
+
return nfRes;
|
|
669
713
|
|
|
670
714
|
} catch (e) {
|
|
671
|
-
|
|
672
|
-
${isLog ? 'doLog(errRes.status || 500);' : ''}
|
|
673
|
-
${releaseCode}
|
|
674
|
-
return errRes;
|
|
715
|
+
${handleErrCode}
|
|
675
716
|
}
|
|
676
717
|
}
|
|
677
718
|
`;
|
|
@@ -681,16 +722,32 @@ export class BareJS<
|
|
|
681
722
|
this.fetch = this.hotFetch!;
|
|
682
723
|
}
|
|
683
724
|
|
|
684
|
-
public fetch = (req: Request): any => {
|
|
725
|
+
public fetch = (req: Request, peerIp?: string): any => {
|
|
685
726
|
if (!this.compiled) {
|
|
686
727
|
this.compile();
|
|
687
|
-
return this.hotFetch!(req);
|
|
728
|
+
return this.hotFetch!(req, peerIp);
|
|
688
729
|
}
|
|
689
|
-
return this.hotFetch!(req);
|
|
730
|
+
return this.hotFetch!(req, peerIp);
|
|
690
731
|
};
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* Ergonomic in-memory request helper for testing or internal invocations.
|
|
735
|
+
* Normalizes relative paths to http://localhost and delegates to this.fetch(req).
|
|
736
|
+
*/
|
|
737
|
+
public async request(path: string, init?: RequestInit): Promise<Response> {
|
|
738
|
+
let url: string;
|
|
739
|
+
if (path.startsWith('http://') || path.startsWith('https://')) {
|
|
740
|
+
url = path;
|
|
741
|
+
} else {
|
|
742
|
+
const normalized = path.startsWith('/') ? path : `/${path}`;
|
|
743
|
+
url = `http://localhost${normalized}`;
|
|
744
|
+
}
|
|
745
|
+
return this.fetch(new Request(url, init));
|
|
746
|
+
}
|
|
691
747
|
public name: string = "App";
|
|
692
748
|
|
|
693
749
|
public trustProxy(enabled: boolean = true): this {
|
|
750
|
+
this._trustProxy = enabled;
|
|
694
751
|
for (let i = 0; i < this.pool.length; i++) {
|
|
695
752
|
this.pool[i]!._trustProxy = enabled;
|
|
696
753
|
}
|
|
@@ -778,7 +835,7 @@ export class BareJS<
|
|
|
778
835
|
return undefined as any;
|
|
779
836
|
}
|
|
780
837
|
}
|
|
781
|
-
return baseFetch(req);
|
|
838
|
+
return baseFetch(req, srv?.requestIP?.(req)?.address);
|
|
782
839
|
},
|
|
783
840
|
websocket: this.wsAdapter
|
|
784
841
|
})
|
|
@@ -787,7 +844,9 @@ export class BareJS<
|
|
|
787
844
|
hostname,
|
|
788
845
|
reusePort,
|
|
789
846
|
maxRequestBodySize,
|
|
790
|
-
fetch:
|
|
847
|
+
fetch(req: Request, srv: any) {
|
|
848
|
+
return baseFetch(req, srv?.requestIP?.(req)?.address);
|
|
849
|
+
}
|
|
791
850
|
});
|
|
792
851
|
|
|
793
852
|
this.server = server;
|
package/src/core/context.ts
CHANGED
|
@@ -54,7 +54,9 @@ export class Context {
|
|
|
54
54
|
public _requestId: string | undefined = undefined;
|
|
55
55
|
public _peerIp: string | undefined = undefined;
|
|
56
56
|
public _trustProxy: boolean = true;
|
|
57
|
-
constructor() {
|
|
57
|
+
constructor(trustProxy: boolean = true) {
|
|
58
|
+
this._trustProxy = trustProxy;
|
|
59
|
+
}
|
|
58
60
|
|
|
59
61
|
public get query(): Record<string, string> {
|
|
60
62
|
if (this._query !== undefined) return this._query;
|
|
@@ -65,6 +67,8 @@ export class Context {
|
|
|
65
67
|
if (qIdx !== -1) {
|
|
66
68
|
let start = qIdx + 1;
|
|
67
69
|
const len = url.length;
|
|
70
|
+
const hasPlus = url.indexOf('+', start) !== -1;
|
|
71
|
+
const hasPct = url.indexOf('%', start) !== -1;
|
|
68
72
|
while (start < len) {
|
|
69
73
|
let amp = url.indexOf('&', start);
|
|
70
74
|
if (amp === -1) amp = len;
|
|
@@ -79,13 +83,17 @@ export class Context {
|
|
|
79
83
|
k = url.slice(start, amp);
|
|
80
84
|
v = '';
|
|
81
85
|
}
|
|
82
|
-
if (
|
|
83
|
-
|
|
84
|
-
|
|
86
|
+
if (hasPlus) {
|
|
87
|
+
if (k.indexOf('+') !== -1) k = k.replaceAll('+', ' ');
|
|
88
|
+
if (v.indexOf('+') !== -1) v = v.replaceAll('+', ' ');
|
|
85
89
|
}
|
|
86
|
-
if (
|
|
87
|
-
|
|
88
|
-
|
|
90
|
+
if (hasPct) {
|
|
91
|
+
if (k.indexOf('%') !== -1) {
|
|
92
|
+
try { k = decodeURIComponent(k); } catch { /* keep raw */ }
|
|
93
|
+
}
|
|
94
|
+
if (v.indexOf('%') !== -1) {
|
|
95
|
+
try { v = decodeURIComponent(v); } catch { /* keep raw */ }
|
|
96
|
+
}
|
|
89
97
|
}
|
|
90
98
|
if (k !== '__proto__' && k !== 'constructor' && k !== 'prototype') {
|
|
91
99
|
result[k] = v;
|
|
@@ -233,14 +241,21 @@ export class Context {
|
|
|
233
241
|
let res: Response;
|
|
234
242
|
|
|
235
243
|
if (!this._headers) {
|
|
236
|
-
res =
|
|
244
|
+
res = status === 200
|
|
245
|
+
? Response.json(data)
|
|
246
|
+
: Response.json(data, { status });
|
|
237
247
|
} else {
|
|
238
|
-
|
|
239
|
-
|
|
248
|
+
let headers = this._headers;
|
|
249
|
+
if (headers["content-type"] === undefined) {
|
|
250
|
+
if (Object.isFrozen(headers)) {
|
|
251
|
+
headers = { ...headers };
|
|
252
|
+
this._headers = headers;
|
|
253
|
+
}
|
|
254
|
+
headers["content-type"] = "application/json";
|
|
240
255
|
}
|
|
241
256
|
res = Response.json(data, {
|
|
242
257
|
status,
|
|
243
|
-
headers:
|
|
258
|
+
headers: headers as any
|
|
244
259
|
});
|
|
245
260
|
}
|
|
246
261
|
|
package/src/core/router.ts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
|
+
type Context,
|
|
2
3
|
type Middleware,
|
|
3
4
|
type Handler,
|
|
4
5
|
type GroupCallback
|
|
5
6
|
} from '../core/context';
|
|
6
7
|
import { schemaValidator, type RouteSchemas } from '../security/validators';
|
|
7
8
|
|
|
8
|
-
import type { RouteSchema } from '../client/index';
|
|
9
|
+
import type { RouteEndpoint, RouteSchema } from '../client/index';
|
|
9
10
|
|
|
10
11
|
type HandlersChain = (Middleware | Handler | RouteSchemas)[];
|
|
11
12
|
|
|
@@ -14,6 +15,59 @@ export type InferSchema<S> =
|
|
|
14
15
|
: S extends { _output: infer T } ? T
|
|
15
16
|
: any;
|
|
16
17
|
|
|
18
|
+
type StripLeadingSlash<S extends string> = S extends `/${infer Rest}` ? StripLeadingSlash<Rest> : S;
|
|
19
|
+
type StripTrailingSlash<S extends string> = S extends `${infer Rest}/` ? StripTrailingSlash<Rest> : S;
|
|
20
|
+
type NormalizePrefix<P extends string> = StripTrailingSlash<StripLeadingSlash<P>> extends ''
|
|
21
|
+
? ''
|
|
22
|
+
: `/${StripTrailingSlash<StripLeadingSlash<P>>}`;
|
|
23
|
+
|
|
24
|
+
type JoinPath<P extends string, Sub extends string> =
|
|
25
|
+
NormalizePrefix<P> extends ''
|
|
26
|
+
? (Sub extends '' ? '/' : (Sub extends `/${string}` ? Sub : `/${Sub}`))
|
|
27
|
+
: (StripLeadingSlash<Sub> extends ''
|
|
28
|
+
? NormalizePrefix<P>
|
|
29
|
+
: `${NormalizePrefix<P>}/${StripLeadingSlash<Sub>}`);
|
|
30
|
+
|
|
31
|
+
export type PrefixRoutes<P extends string, R extends RouteSchema> = {
|
|
32
|
+
[K in keyof R as K extends `${infer M} ${infer Sub}`
|
|
33
|
+
? `${M} ${JoinPath<P, Sub>}`
|
|
34
|
+
: K]: R[K] extends infer E extends RouteEndpoint
|
|
35
|
+
? Omit<E, 'path'> & {
|
|
36
|
+
path: E['path'] extends string
|
|
37
|
+
? JoinPath<P, E['path']>
|
|
38
|
+
: JoinPath<P, K extends `${string} ${infer Sub}` ? Sub : (K & string)>;
|
|
39
|
+
}
|
|
40
|
+
: R[K];
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
type TypedRouterHandler<S extends RouteSchemas, Res> = (
|
|
44
|
+
ctx: Context & {
|
|
45
|
+
body: S extends { body: infer B } ? InferSchema<B> : any;
|
|
46
|
+
query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, string>;
|
|
47
|
+
params: S extends { params: infer Pa } ? InferSchema<Pa> : Record<string, any>;
|
|
48
|
+
}
|
|
49
|
+
) => Res | Promise<Res>;
|
|
50
|
+
|
|
51
|
+
type AddRouterRoute<Routes extends RouteSchema, M extends string> = {
|
|
52
|
+
<P extends string, S extends RouteSchemas, Res = S extends { response: infer R } ? InferSchema<R> : any>(
|
|
53
|
+
path: P,
|
|
54
|
+
schemas: S,
|
|
55
|
+
handler: TypedRouterHandler<S, Res>
|
|
56
|
+
): BareRouter<Routes & Record<`${M} ${P}`, {
|
|
57
|
+
method: M;
|
|
58
|
+
path: P;
|
|
59
|
+
params: S extends { params: infer Pa } ? InferSchema<Pa> : Record<string, any>;
|
|
60
|
+
query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, any>;
|
|
61
|
+
headers: S extends { headers: infer H } ? InferSchema<H> : Record<string, string>;
|
|
62
|
+
body: S extends { body: infer B } ? InferSchema<B> : any;
|
|
63
|
+
response: S extends { response: infer R } ? InferSchema<R> : Awaited<Res>;
|
|
64
|
+
}>>;
|
|
65
|
+
<P extends string, Res = any>(
|
|
66
|
+
path: P,
|
|
67
|
+
...handlers: any[]
|
|
68
|
+
): BareRouter<Routes & Record<`${M} ${P}`, { method: M; path: P; response: Awaited<Res> }>>;
|
|
69
|
+
};
|
|
70
|
+
|
|
17
71
|
export class BareRouter<Routes extends RouteSchema = {}> {
|
|
18
72
|
declare readonly __routes: Routes;
|
|
19
73
|
public routes: any[] = [];
|
|
@@ -47,19 +101,19 @@ export class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
47
101
|
return this;
|
|
48
102
|
}
|
|
49
103
|
|
|
50
|
-
public get:
|
|
51
|
-
public post:
|
|
52
|
-
public put:
|
|
53
|
-
public patch:
|
|
54
|
-
public delete:
|
|
55
|
-
public options:
|
|
56
|
-
public head:
|
|
57
|
-
public all:
|
|
104
|
+
public get: AddRouterRoute<Routes, 'GET'> = ((path: string, ...h: HandlersChain) => this._add("GET", path, h)) as any;
|
|
105
|
+
public post: AddRouterRoute<Routes, 'POST'> = ((path: string, ...h: HandlersChain) => this._add("POST", path, h)) as any;
|
|
106
|
+
public put: AddRouterRoute<Routes, 'PUT'> = ((path: string, ...h: HandlersChain) => this._add("PUT", path, h)) as any;
|
|
107
|
+
public patch: AddRouterRoute<Routes, 'PATCH'> = ((path: string, ...h: HandlersChain) => this._add("PATCH", path, h)) as any;
|
|
108
|
+
public delete: AddRouterRoute<Routes, 'DELETE'> = ((path: string, ...h: HandlersChain) => this._add("DELETE", path, h)) as any;
|
|
109
|
+
public options: AddRouterRoute<Routes, 'OPTIONS'> = ((path: string, ...h: HandlersChain) => this._add("OPTIONS", path, h)) as any;
|
|
110
|
+
public head: AddRouterRoute<Routes, 'HEAD'> = ((path: string, ...h: HandlersChain) => this._add("HEAD", path, h)) as any;
|
|
111
|
+
public all: AddRouterRoute<Routes, 'ALL'> = ((path: string, ...h: HandlersChain) => {
|
|
58
112
|
for (const m of ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]) {
|
|
59
113
|
this._add(m, path, h);
|
|
60
114
|
}
|
|
61
115
|
return this;
|
|
62
|
-
};
|
|
116
|
+
}) as any;
|
|
63
117
|
|
|
64
118
|
public group = (path: string, ...args: any[]) => {
|
|
65
119
|
const callback = args.pop();
|
|
@@ -73,15 +127,39 @@ export class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
73
127
|
return this;
|
|
74
128
|
};
|
|
75
129
|
|
|
130
|
+
private _mountRouter(prefix: string, router: BareRouter<any>) {
|
|
131
|
+
const base = (this.prefix + "/" + prefix).replace(/\/+/g, "/").replace(/\/$/, "");
|
|
132
|
+
for (const r of router.routes) {
|
|
133
|
+
let fullPath = (base + "/" + r.path).replace(/\/+/g, "/");
|
|
134
|
+
if (fullPath.endsWith("/")) fullPath = fullPath.slice(0, -1);
|
|
135
|
+
this.routes.push({
|
|
136
|
+
method: r.method,
|
|
137
|
+
path: fullPath || "",
|
|
138
|
+
handlers: [...this.groupMiddleware, ...r.handlers]
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
public route<P extends string, R2 extends RouteSchema = {}>(
|
|
144
|
+
prefix: P,
|
|
145
|
+
router: BareRouter<R2>
|
|
146
|
+
): BareRouter<Routes & PrefixRoutes<P, R2>> {
|
|
147
|
+
this._mountRouter(prefix, router);
|
|
148
|
+
return this as any;
|
|
149
|
+
}
|
|
150
|
+
|
|
76
151
|
public use<R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareRouter<Routes & R2>;
|
|
152
|
+
public use<P extends string, R2 extends RouteSchema = {}>(prefix: P, mw: BareRouter<R2>): BareRouter<Routes & PrefixRoutes<P, R2>>;
|
|
77
153
|
public use(mw: any): BareRouter<Routes>;
|
|
78
|
-
public use(
|
|
79
|
-
if (
|
|
80
|
-
this.
|
|
81
|
-
} else if (
|
|
82
|
-
|
|
154
|
+
public use(prefixOrMw: any, maybeMw?: any): any {
|
|
155
|
+
if (typeof prefixOrMw === 'string' && (maybeMw instanceof BareRouter || (maybeMw && maybeMw.routes))) {
|
|
156
|
+
this._mountRouter(prefixOrMw, maybeMw);
|
|
157
|
+
} else if (prefixOrMw instanceof BareRouter || (prefixOrMw && prefixOrMw.routes)) {
|
|
158
|
+
this._mountRouter("", prefixOrMw);
|
|
159
|
+
} else if (prefixOrMw && typeof prefixOrMw.install === 'function') {
|
|
160
|
+
prefixOrMw.install(this);
|
|
83
161
|
} else {
|
|
84
|
-
this.groupMiddleware.push(
|
|
162
|
+
this.groupMiddleware.push(prefixOrMw);
|
|
85
163
|
}
|
|
86
164
|
return this;
|
|
87
165
|
}
|
package/src/index.ts
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
// --- 1. Core Engine ---
|
|
9
9
|
export { BareJS, type WebSocketRouteHandler, type CronOptions } from './core/bare';
|
|
10
|
-
export { BareRouter, type InferSchema } from './core/router';
|
|
10
|
+
export { BareRouter, type InferSchema, type PrefixRoutes } from './core/router';
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
13
|
* Plugin Interface for BareJS
|
|
@@ -66,15 +66,24 @@ export { csrf, type CsrfOptions } from './security/csrf';
|
|
|
66
66
|
export { timeout, type TimeoutOptions } from './security/timeout';
|
|
67
67
|
export { rateLimit, type RateLimitOptions } from './security/rateLimit';
|
|
68
68
|
export { idempotency, createSingleflight, type IdempotencyOptions } from './security/idempotency';
|
|
69
|
+
export {
|
|
70
|
+
redisStore,
|
|
71
|
+
type BareStore,
|
|
72
|
+
type RateLimitStore,
|
|
73
|
+
type IdempotencyStore,
|
|
74
|
+
type CachedIdempotentEntry,
|
|
75
|
+
type RevocationStore,
|
|
76
|
+
type RedisStoreOptions,
|
|
77
|
+
} from './security/store';
|
|
69
78
|
export { circuitBreaker, type CircuitBreakerOptions, type CircuitState } from './security/resilience';
|
|
70
79
|
export { securityHeaders, type SecurityHeadersOptions } from './security/headers';
|
|
71
|
-
export { staticFile, type StaticOptions } from './utils/static';
|
|
72
|
-
export { compress, type CompressOptions } from './utils/compress';
|
|
80
|
+
export { staticFile, type StaticOptions, type StaticMetadataCacheOptions } from './utils/static';
|
|
81
|
+
export { compress, type CompressOptions, type CompressionEncoding } from './utils/compress';
|
|
73
82
|
export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
|
|
74
83
|
|
|
75
84
|
// --- 6. Authentication (Bun Native) ---
|
|
76
85
|
// Always deploy using process.env [2026-01-06]
|
|
77
|
-
export { bareAuth, createToken, basicAuth, hasRole, revokeToken, isTokenRevoked, type BareAuthOptions } from './security/auth';
|
|
86
|
+
export { bareAuth, createToken, basicAuth, hasRole, revokeToken, isTokenRevoked, type BareAuthOptions, type JwtAlgorithm } from './security/auth';
|
|
78
87
|
// --- 7. Hashing ---
|
|
79
88
|
export { Hash as Password, Hash } from './security/hash';
|
|
80
89
|
|