barejs 0.2.7 → 0.2.9
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 +139 -126
- package/dist/aws-lambda.js +1 -0
- package/dist/cache.js +1 -0
- package/dist/cloudflare-pages.js +1 -0
- package/dist/edge.js +28 -28
- package/dist/etag.js +1 -0
- package/dist/html.js +1 -0
- package/dist/index.js +146 -144
- package/dist/jsx.js +1 -0
- package/dist/netlify.js +1 -0
- package/dist/node.js +146 -144
- package/dist/ssg.js +1 -0
- package/dist/types/adapters/aws-lambda.d.ts +43 -0
- package/dist/types/adapters/cloudflare-pages.d.ts +18 -0
- package/dist/types/adapters/netlify.d.ts +32 -0
- package/dist/types/core/bare.d.ts +15 -3
- package/dist/types/core/radix.d.ts +5 -0
- package/dist/types/core/router.d.ts +2 -0
- package/dist/types/edge.d.ts +13 -0
- package/dist/types/index.d.ts +3 -1
- package/dist/types/utils/cache.d.ts +26 -0
- package/dist/types/utils/etag.d.ts +12 -0
- package/dist/types/utils/html.d.ts +22 -0
- package/dist/types/utils/jsx.d.ts +34 -0
- package/dist/types/utils/ssg.d.ts +36 -0
- package/llms.txt +24 -3
- package/package.json +42 -2
- package/src/adapters/aws-lambda.ts +166 -0
- package/src/adapters/cloudflare-pages.ts +27 -0
- package/src/adapters/netlify.ts +28 -0
- package/src/core/bare.ts +78 -22
- package/src/core/context.ts +1 -1
- package/src/core/radix.ts +46 -10
- package/src/core/router.ts +41 -7
- package/src/edge.ts +28 -1
- package/src/index.ts +3 -1
- package/src/utils/cache.ts +128 -0
- package/src/utils/etag.ts +115 -0
- package/src/utils/html.ts +72 -0
- package/src/utils/jsx.ts +217 -0
- package/src/utils/ssg.ts +110 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export interface CloudflarePagesContext<Env = Record<string, any>> {
|
|
2
|
+
request: Request;
|
|
3
|
+
env: Env;
|
|
4
|
+
params: Record<string, string | string[]>;
|
|
5
|
+
waitUntil(promise: Promise<any>): void;
|
|
6
|
+
next(input?: Request | string, init?: RequestInit): Promise<Response>;
|
|
7
|
+
data: Record<string, unknown>;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
interface FetchableEdgeApp {
|
|
11
|
+
fetch(req: Request, env?: any, executionCtx?: any): Response | Promise<Response>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Cloudflare Pages Functions adapter (`onRequest`).
|
|
16
|
+
* Usage: `export const onRequest = handle(app);`
|
|
17
|
+
*/
|
|
18
|
+
export const handle = <Env = Record<string, any>>(app: FetchableEdgeApp) => {
|
|
19
|
+
return (context: CloudflarePagesContext<Env>): Response | Promise<Response> => {
|
|
20
|
+
return app.fetch(context.request, context.env, {
|
|
21
|
+
waitUntil: (p: Promise<any>) => context.waitUntil(p),
|
|
22
|
+
passThroughOnException: () => {}
|
|
23
|
+
});
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export const cloudflarePages = handle;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export interface NetlifyContext {
|
|
2
|
+
ip?: string;
|
|
3
|
+
requestId?: string;
|
|
4
|
+
site?: { id?: string; name?: string; url?: string };
|
|
5
|
+
geo?: { city?: string; country?: { code?: string; name?: string }; timezone?: string };
|
|
6
|
+
cookies?: { get(name: string): string | undefined };
|
|
7
|
+
waitUntil?(promise: Promise<any>): void;
|
|
8
|
+
[key: string]: any;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
interface FetchableApp {
|
|
12
|
+
fetch(req: Request, peerIpOrEnv?: any, executionCtx?: any): Response | Promise<Response>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Netlify Functions v2 adapter.
|
|
17
|
+
* Usage: `export default handle(app);`
|
|
18
|
+
*/
|
|
19
|
+
export const handle = (app: FetchableApp) => {
|
|
20
|
+
return (req: Request, context?: NetlifyContext): Response | Promise<Response> => {
|
|
21
|
+
const execCtx = context?.waitUntil
|
|
22
|
+
? { waitUntil: (p: Promise<any>) => context.waitUntil!(p) }
|
|
23
|
+
: undefined;
|
|
24
|
+
return app.fetch(req, context ?? {}, execCtx);
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export const netlify = handle;
|
package/src/core/bare.ts
CHANGED
|
@@ -155,6 +155,13 @@ type AddRoute<
|
|
|
155
155
|
): BareJS<Derived, Routes & Record<`${M} ${P}`, { method: M; path: P; response: Awaited<Res>; error: any }>, Macros>;
|
|
156
156
|
};
|
|
157
157
|
|
|
158
|
+
export interface BareJSOptions {
|
|
159
|
+
/** Context object pool size (default: 1024, max: 65536). */
|
|
160
|
+
poolSize?: number;
|
|
161
|
+
/** Base path prefix applied to all registered routes (e.g. '/api' for Next.js, Astro, SvelteKit). */
|
|
162
|
+
prefix?: string;
|
|
163
|
+
}
|
|
164
|
+
|
|
158
165
|
export class BareJS<
|
|
159
166
|
Derived extends Record<string, any> = {},
|
|
160
167
|
Routes extends RouteSchema = {},
|
|
@@ -320,11 +327,17 @@ export class BareJS<
|
|
|
320
327
|
private static readonly DEFAULT_POOL_SIZE = 1024;
|
|
321
328
|
private static readonly MAX_POOL_SIZE = 65_536;
|
|
322
329
|
|
|
323
|
-
constructor(
|
|
324
|
-
|
|
330
|
+
constructor(poolSizeOrOptions: number | BareJSOptions = BareJS.DEFAULT_POOL_SIZE) {
|
|
331
|
+
const opts = typeof poolSizeOrOptions === 'object' && poolSizeOrOptions !== null
|
|
332
|
+
? poolSizeOrOptions
|
|
333
|
+
: { poolSize: poolSizeOrOptions };
|
|
334
|
+
const normalizedPrefix = opts.prefix
|
|
335
|
+
? ('/' + opts.prefix).replace(/\/+/g, '/').replace(/\/$/, '')
|
|
336
|
+
: '';
|
|
337
|
+
super(normalizedPrefix);
|
|
325
338
|
bootstrapConfig();
|
|
326
339
|
this.maxPool = normalizePoolSize(
|
|
327
|
-
poolSize,
|
|
340
|
+
opts.poolSize ?? BareJS.DEFAULT_POOL_SIZE,
|
|
328
341
|
BareJS.DEFAULT_POOL_SIZE,
|
|
329
342
|
BareJS.MAX_POOL_SIZE
|
|
330
343
|
);
|
|
@@ -342,13 +355,27 @@ export class BareJS<
|
|
|
342
355
|
}
|
|
343
356
|
}
|
|
344
357
|
|
|
358
|
+
/**
|
|
359
|
+
* Set or append a base path prefix for all subsequently registered routes
|
|
360
|
+
* (e.g. `new BareJS().basePath('/api')` for Next.js / Astro / SvelteKit).
|
|
361
|
+
*/
|
|
362
|
+
public basePath(path: string): this {
|
|
363
|
+
const clean = ('/' + path).replace(/\/+/g, '/').replace(/\/$/, '');
|
|
364
|
+
if (clean) {
|
|
365
|
+
this.prefix = (this.prefix + clean).replace(/\/+/g, '/').replace(/\/$/, '');
|
|
366
|
+
this._onRouteMutate();
|
|
367
|
+
}
|
|
368
|
+
return this;
|
|
369
|
+
}
|
|
370
|
+
|
|
345
371
|
private notFoundHandler: () => NotFoundResponse = () => ({
|
|
346
372
|
status: 404,
|
|
347
373
|
message: "Route not found"
|
|
348
374
|
});
|
|
349
|
-
public setNotFound(handler: () => NotFoundResponse) {
|
|
375
|
+
public setNotFound(handler: () => NotFoundResponse): this {
|
|
350
376
|
this.notFoundHandler = handler;
|
|
351
377
|
this._onRouteMutate();
|
|
378
|
+
return this;
|
|
352
379
|
}
|
|
353
380
|
|
|
354
381
|
public onError(handler: (err: any, ctx: Context) => any): this {
|
|
@@ -388,7 +415,7 @@ export class BareJS<
|
|
|
388
415
|
}>,
|
|
389
416
|
Macros
|
|
390
417
|
> {
|
|
391
|
-
const normalized = ('/' + path).replace(/\/+/g, '/').replace(/\/$/, '') || '/';
|
|
418
|
+
const normalized = (this.prefix + '/' + path).replace(/\/+/g, '/').replace(/\/$/, '') || '/';
|
|
392
419
|
const hasBody = Boolean(handler.body);
|
|
393
420
|
const hasQuery = Boolean(handler.query);
|
|
394
421
|
const hasHeaders = Boolean(handler.headers);
|
|
@@ -665,6 +692,13 @@ export class BareJS<
|
|
|
665
692
|
return this as any;
|
|
666
693
|
}
|
|
667
694
|
|
|
695
|
+
protected override _createGroupRouter(prefix: string, middleware: any[]): BareRouter<any> {
|
|
696
|
+
const sub = new BareJS({ prefix });
|
|
697
|
+
sub.groupMiddleware = middleware;
|
|
698
|
+
sub.macros = { ...this.macros };
|
|
699
|
+
return sub;
|
|
700
|
+
}
|
|
701
|
+
|
|
668
702
|
protected override _add(method: string, path: string, handlers: any[]) {
|
|
669
703
|
const macroKeys = Object.keys(this.macros);
|
|
670
704
|
if (macroKeys.length === 0) {
|
|
@@ -807,6 +841,27 @@ export class BareJS<
|
|
|
807
841
|
};
|
|
808
842
|
}
|
|
809
843
|
|
|
844
|
+
const postIdx = pipeline.findIndex((fn) => fn?.__postResponse);
|
|
845
|
+
if (postIdx !== -1) {
|
|
846
|
+
const applyPost = pipeline[postIdx]!.__postResponse;
|
|
847
|
+
const innerPipeline = pipeline.filter((_, i) => i !== postIdx);
|
|
848
|
+
const innerCompiled = this.compileHandler(innerPipeline, isLog);
|
|
849
|
+
return async (ctx: Context, doLog?: any) => {
|
|
850
|
+
const res = await innerCompiled(ctx, doLog);
|
|
851
|
+
return applyPost(ctx, res);
|
|
852
|
+
};
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
const wrapIdx = pipeline.findIndex((fn) => fn?.__wrapHandler);
|
|
856
|
+
if (wrapIdx !== -1) {
|
|
857
|
+
const applyWrap = pipeline[wrapIdx]!.__wrapHandler;
|
|
858
|
+
const innerPipeline = pipeline.filter((_, i) => i !== wrapIdx);
|
|
859
|
+
const innerCompiled = this.compileHandler(innerPipeline, isLog);
|
|
860
|
+
return async (ctx: Context, doLog?: any) => {
|
|
861
|
+
return applyWrap(ctx, () => innerCompiled(ctx, doLog));
|
|
862
|
+
};
|
|
863
|
+
}
|
|
864
|
+
|
|
810
865
|
const cbIdx = pipeline.findIndex((fn) => fn?.__circuitBreaker);
|
|
811
866
|
if (cbIdx !== -1) {
|
|
812
867
|
const cbMw = pipeline[cbIdx]!;
|
|
@@ -1263,15 +1318,14 @@ export class BareJS<
|
|
|
1263
1318
|
const hasIdem = this.routes.some((r: any) => r.handlers.some((h: any) => h?.__idempotencyCommit)) ||
|
|
1264
1319
|
this.groupMiddleware.some((m: any) => m?.__idempotencyCommit);
|
|
1265
1320
|
const hasDerive = this._hasDerive || this.routes.some((r: any) => r.handlers.some((h: any) => h?.__isDerive));
|
|
1321
|
+
const isDevUaf = process.env.NODE_ENV === 'development' || !process.env.NODE_ENV;
|
|
1322
|
+
const ctxVar = isDevUaf ? 'rawCtx' : 'ctx';
|
|
1266
1323
|
const deriveCleanup = hasDerive
|
|
1267
|
-
? `if (
|
|
1324
|
+
? `if (${ctxVar}._derivedKeys) { for (let i = 0; i < ${ctxVar}._derivedKeys.length; i++) delete ${ctxVar}[${ctxVar}._derivedKeys[i]]; ${ctxVar}._derivedKeys = undefined; }`
|
|
1268
1325
|
: '';
|
|
1269
1326
|
const idemCleanup = hasIdem
|
|
1270
|
-
? `if (
|
|
1327
|
+
? `if (${ctxVar}._idempotencyKey) { if (${ctxVar}._idemInFlight) ${ctxVar}._idemInFlight.delete(${ctxVar}._idempotencyKey); ${ctxVar}._idempotencyKey = undefined; ${ctxVar}._idemInFlight = undefined; }`
|
|
1271
1328
|
: '';
|
|
1272
|
-
|
|
1273
|
-
const isDevUaf = process.env.NODE_ENV === 'development' || !process.env.NODE_ENV;
|
|
1274
|
-
const ctxVar = isDevUaf ? 'rawCtx' : 'ctx';
|
|
1275
1329
|
const wrapUaf = isDevUaf
|
|
1276
1330
|
? (rawCtx: Context, state: { released: boolean }): Context => {
|
|
1277
1331
|
const warn = (prop: string | symbol) => {
|
|
@@ -1307,8 +1361,8 @@ export class BareJS<
|
|
|
1307
1361
|
if (!${ctxVar}._detached) {
|
|
1308
1362
|
${isDevUaf ? '_uaf.released = true;' : ''}
|
|
1309
1363
|
if (${ctxVar}.store.size > 0) ${ctxVar}.store.clear();
|
|
1310
|
-
${deriveCleanup
|
|
1311
|
-
${idemCleanup
|
|
1364
|
+
${deriveCleanup}
|
|
1365
|
+
${idemCleanup}
|
|
1312
1366
|
${ctxVar}.req = undefined;
|
|
1313
1367
|
${ctxVar}._status = 200;
|
|
1314
1368
|
${ctxVar}.body = undefined;
|
|
@@ -1485,10 +1539,11 @@ export class BareJS<
|
|
|
1485
1539
|
const poolState = this._poolState;
|
|
1486
1540
|
const trustProxyBox = this._trustProxyBox;
|
|
1487
1541
|
const emitStructuredLog = isLog && (this._logFormat === 'json' || this._logSink !== undefined)
|
|
1488
|
-
? (method: string, rawUrl: string, status: number, durationMs: number, peerIp?:
|
|
1542
|
+
? (method: string, rawUrl: string, status: number, durationMs: number, peerIp?: unknown) => {
|
|
1489
1543
|
const idx = rawUrl.indexOf('/', 8);
|
|
1490
1544
|
const qIdx = idx === -1 ? -1 : rawUrl.indexOf('?', idx);
|
|
1491
1545
|
const path = idx === -1 ? '/' : (qIdx === -1 ? rawUrl.slice(idx) : rawUrl.slice(idx, qIdx));
|
|
1546
|
+
const ip = typeof peerIp === 'string' && peerIp ? peerIp : undefined;
|
|
1492
1547
|
const entry: UseLogEntry = {
|
|
1493
1548
|
level: status >= 500 ? 'error' : status >= 400 ? 'warn' : 'info',
|
|
1494
1549
|
timestamp: new Date().toISOString(),
|
|
@@ -1496,7 +1551,7 @@ export class BareJS<
|
|
|
1496
1551
|
path,
|
|
1497
1552
|
status,
|
|
1498
1553
|
durationMs: Number(durationMs.toFixed(3)),
|
|
1499
|
-
...(
|
|
1554
|
+
...(ip ? { ip } : {})
|
|
1500
1555
|
};
|
|
1501
1556
|
if (this._logSink) this._logSink(entry);
|
|
1502
1557
|
else console.log(JSON.stringify(entry));
|
|
@@ -1554,7 +1609,7 @@ export class BareJS<
|
|
|
1554
1609
|
|
|
1555
1610
|
try {
|
|
1556
1611
|
${ctxVar}.req = req;
|
|
1557
|
-
${ctxVar}._peerIp = peerIp;
|
|
1612
|
+
${ctxVar}._peerIp = typeof peerIp === 'string' ? peerIp : undefined;
|
|
1558
1613
|
|
|
1559
1614
|
${staticFastPathCode}
|
|
1560
1615
|
|
|
@@ -1633,13 +1688,14 @@ export class BareJS<
|
|
|
1633
1688
|
const innerFetch = this.hotFetch!;
|
|
1634
1689
|
const reqHooks = this.requestHooks.slice();
|
|
1635
1690
|
const resHooks = this.responseHooks.slice();
|
|
1636
|
-
this.hotFetch = async (req: Request, peerIp?:
|
|
1691
|
+
this.hotFetch = async (req: Request, peerIp?: any) => {
|
|
1692
|
+
const ip = typeof peerIp === 'string' ? peerIp : undefined;
|
|
1637
1693
|
const start = performance.now();
|
|
1638
1694
|
for (let i = 0; i < reqHooks.length; i++) {
|
|
1639
|
-
const maybeRes = await reqHooks[i]!(req,
|
|
1695
|
+
const maybeRes = await reqHooks[i]!(req, ip);
|
|
1640
1696
|
if (maybeRes instanceof Response) return maybeRes;
|
|
1641
1697
|
}
|
|
1642
|
-
let res: Response = await innerFetch(req,
|
|
1698
|
+
let res: Response = await innerFetch(req, ip);
|
|
1643
1699
|
const durationMs = performance.now() - start;
|
|
1644
1700
|
for (let i = 0; i < resHooks.length; i++) {
|
|
1645
1701
|
const updated = await resHooks[i]!(req, res, durationMs);
|
|
@@ -1652,7 +1708,7 @@ export class BareJS<
|
|
|
1652
1708
|
this.fetch = this.hotFetch!;
|
|
1653
1709
|
}
|
|
1654
1710
|
|
|
1655
|
-
private readonly _lazyFetch = (req: Request, peerIp?:
|
|
1711
|
+
private readonly _lazyFetch = (req: Request, peerIp?: any): any => {
|
|
1656
1712
|
if (!this.compiled) {
|
|
1657
1713
|
this.compile();
|
|
1658
1714
|
return this.hotFetch!(req, peerIp);
|
|
@@ -1660,7 +1716,7 @@ export class BareJS<
|
|
|
1660
1716
|
return this.hotFetch!(req, peerIp);
|
|
1661
1717
|
};
|
|
1662
1718
|
|
|
1663
|
-
public fetch = this._lazyFetch;
|
|
1719
|
+
public fetch: (req: Request, peerIp?: any) => any = this._lazyFetch;
|
|
1664
1720
|
|
|
1665
1721
|
/**
|
|
1666
1722
|
* Ergonomic in-memory request helper for testing or internal invocations.
|
|
@@ -1714,7 +1770,7 @@ export class BareJS<
|
|
|
1714
1770
|
let count = 0;
|
|
1715
1771
|
for (const route of this.routes) {
|
|
1716
1772
|
if (route.method === 'ALL') continue;
|
|
1717
|
-
if (route.path.includes('*') || route.path.includes('?') || route.path.includes('(')) continue;
|
|
1773
|
+
if (route.path.includes('*') || route.path.includes('?') || route.path.includes('(') || route.path.includes('{')) continue;
|
|
1718
1774
|
if (route.handlers.length !== 1) continue;
|
|
1719
1775
|
|
|
1720
1776
|
const rawHandler = route.handlers[0] as any;
|
|
@@ -1847,7 +1903,7 @@ export class BareJS<
|
|
|
1847
1903
|
|
|
1848
1904
|
for (const route of this.routes) {
|
|
1849
1905
|
if (route.method !== 'GET' && route.method !== 'HEAD' && route.method !== 'DELETE' && route.method !== 'OPTIONS') continue;
|
|
1850
|
-
if (route.path.includes('*') || route.path.includes('?') || route.path.includes('(')) continue;
|
|
1906
|
+
if (route.path.includes('*') || route.path.includes('?') || route.path.includes('(') || route.path.includes('{')) continue;
|
|
1851
1907
|
if (route.handlers.length !== 1) continue;
|
|
1852
1908
|
|
|
1853
1909
|
const rawHandler = route.handlers[0] as any;
|
package/src/core/context.ts
CHANGED
|
@@ -98,7 +98,7 @@ function ipv4ToInt(ip: string): number | null {
|
|
|
98
98
|
|
|
99
99
|
export function isTrustedProxyIp(peerIp: string | undefined, trustProxy: boolean | string[]): boolean {
|
|
100
100
|
if (trustProxy === true) return true;
|
|
101
|
-
if (!trustProxy || !Array.isArray(trustProxy) || trustProxy.length === 0 || !peerIp) return false;
|
|
101
|
+
if (!trustProxy || !Array.isArray(trustProxy) || trustProxy.length === 0 || typeof peerIp !== 'string' || !peerIp) return false;
|
|
102
102
|
const normalized = peerIp.startsWith('::ffff:') ? peerIp.slice(7) : peerIp;
|
|
103
103
|
const peerInt = ipv4ToInt(normalized);
|
|
104
104
|
for (let i = 0; i < trustProxy.length; i++) {
|
package/src/core/radix.ts
CHANGED
|
@@ -5,6 +5,7 @@ export class RadixNode {
|
|
|
5
5
|
public staticKeys: string[] = [];
|
|
6
6
|
public paramNode: RadixNode | null = null;
|
|
7
7
|
public paramName: string | null = null;
|
|
8
|
+
public regexParamNodes: Array<{ regex: RegExp; pattern: string; node: RadixNode }> = [];
|
|
8
9
|
public wildcardNode: RadixNode | null = null;
|
|
9
10
|
public handlers: Record<string, Function> = Object.create(null);
|
|
10
11
|
public handlerParams: Record<string, string[]> = Object.create(null);
|
|
@@ -19,11 +20,24 @@ export class RadixNode {
|
|
|
19
20
|
node = node.wildcardNode;
|
|
20
21
|
break;
|
|
21
22
|
} else if (part.startsWith(':')) {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
23
|
+
const braceIdx = part.indexOf('{');
|
|
24
|
+
if (braceIdx !== -1 && part.endsWith('}')) {
|
|
25
|
+
const pName = part.slice(1, braceIdx);
|
|
26
|
+
const pattern = part.slice(braceIdx + 1, -1);
|
|
27
|
+
let entry = node.regexParamNodes.find((e) => e.pattern === pattern);
|
|
28
|
+
if (!entry) {
|
|
29
|
+
entry = { regex: new RegExp(`^(?:${pattern})$`), pattern, node: new RadixNode() };
|
|
30
|
+
node.regexParamNodes.push(entry);
|
|
31
|
+
}
|
|
32
|
+
paramNames.push(pName);
|
|
33
|
+
node = entry.node;
|
|
34
|
+
} else {
|
|
35
|
+
if (!node.paramNode) node.paramNode = new RadixNode();
|
|
36
|
+
const pName = part.slice(1);
|
|
37
|
+
if (!node.paramName) node.paramName = pName;
|
|
38
|
+
paramNames.push(pName);
|
|
39
|
+
node = node.paramNode;
|
|
40
|
+
}
|
|
27
41
|
} else {
|
|
28
42
|
if (!node.children[part]) {
|
|
29
43
|
node.children[part] = new RadixNode();
|
|
@@ -101,6 +115,19 @@ export class RadixNode {
|
|
|
101
115
|
if (res) return res;
|
|
102
116
|
}
|
|
103
117
|
|
|
118
|
+
if (node.regexParamNodes.length > 0 && segmentLen > 0) {
|
|
119
|
+
const seg = url.slice(pos, j);
|
|
120
|
+
for (let r = 0; r < node.regexParamNodes.length; r++) {
|
|
121
|
+
const entry = node.regexParamNodes[r]!;
|
|
122
|
+
if (entry.regex.test(seg)) {
|
|
123
|
+
pVals.push(seg);
|
|
124
|
+
const res = matchNode(entry.node, j + 1, pVals);
|
|
125
|
+
if (res) return res;
|
|
126
|
+
pVals.pop();
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
104
131
|
if (node.paramNode && segmentLen > 0) {
|
|
105
132
|
pVals.push(url.slice(pos, j));
|
|
106
133
|
const res = matchNode(node.paramNode, j + 1, pVals);
|
|
@@ -157,7 +184,7 @@ export class RadixNode {
|
|
|
157
184
|
code += `${indent}}\n`;
|
|
158
185
|
}
|
|
159
186
|
|
|
160
|
-
const hasChildren = this.staticKeys.length > 0 || this.paramNode !== null;
|
|
187
|
+
const hasChildren = this.staticKeys.length > 0 || this.regexParamNodes.length > 0 || this.paramNode !== null;
|
|
161
188
|
if (hasChildren) {
|
|
162
189
|
const innerIndent = indent + ' ';
|
|
163
190
|
code += `${indent}if (${idxPrefix} < urlLen) {\n`;
|
|
@@ -291,8 +318,7 @@ export class RadixNode {
|
|
|
291
318
|
}
|
|
292
319
|
}
|
|
293
320
|
|
|
294
|
-
if (this.paramNode) {
|
|
295
|
-
const pNode = this.paramNode;
|
|
321
|
+
if (this.regexParamNodes.length > 0 || this.paramNode) {
|
|
296
322
|
if (this.staticKeys.length <= 1) {
|
|
297
323
|
code += `${innerIndent}let slash${level} = ${pathPrefix}.indexOf('/', ${idxPrefix});\n`;
|
|
298
324
|
code += `${innerIndent}if (slash${level} === -1 || slash${level} > urlLen) slash${level} = urlLen;\n`;
|
|
@@ -301,9 +327,19 @@ export class RadixNode {
|
|
|
301
327
|
const pVar = `pL${level}`;
|
|
302
328
|
code += `${innerIndent}if (slash${level} > ${idxPrefix}) {\n`;
|
|
303
329
|
code += `${innerIndent} const ${pVar} = ${pathPrefix}.slice(${idxPrefix}, slash${level});\n`;
|
|
304
|
-
|
|
305
330
|
const newVars = [...paramVars, pVar];
|
|
306
|
-
|
|
331
|
+
|
|
332
|
+
for (let r = 0; r < this.regexParamNodes.length; r++) {
|
|
333
|
+
const entry = this.regexParamNodes[r]!;
|
|
334
|
+
const reVar = register(entry.regex as any);
|
|
335
|
+
code += `${innerIndent} if (${reVar}.test(${pVar})) {\n`;
|
|
336
|
+
code += entry.node.jitCompile(register, level + 2, pathPrefix, `slash${level} + 1`, newVars, emitCall);
|
|
337
|
+
code += `${innerIndent} }\n`;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
if (this.paramNode) {
|
|
341
|
+
code += this.paramNode.jitCompile(register, level + 1, pathPrefix, `slash${level} + 1`, newVars, emitCall);
|
|
342
|
+
}
|
|
307
343
|
code += `${innerIndent}}\n`;
|
|
308
344
|
}
|
|
309
345
|
|
package/src/core/router.ts
CHANGED
|
@@ -111,6 +111,32 @@ export class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
111
111
|
public groupMiddleware: any[] = []
|
|
112
112
|
) { }
|
|
113
113
|
|
|
114
|
+
private static expandOptionalPaths(fullPath: string): string[] {
|
|
115
|
+
if (!fullPath.includes('?')) return [fullPath];
|
|
116
|
+
const parts = fullPath.split('/').filter(Boolean);
|
|
117
|
+
const hasOptParam = parts.some((p) => p.startsWith(':') && p.endsWith('?'));
|
|
118
|
+
if (!hasOptParam) return [fullPath];
|
|
119
|
+
|
|
120
|
+
let paths: string[] = [''];
|
|
121
|
+
for (let i = 0; i < parts.length; i++) {
|
|
122
|
+
const part = parts[i]!;
|
|
123
|
+
if (part.startsWith(':') && part.endsWith('?')) {
|
|
124
|
+
const concrete = part.slice(0, -1);
|
|
125
|
+
const next: string[] = [];
|
|
126
|
+
for (let j = 0; j < paths.length; j++) {
|
|
127
|
+
next.push(paths[j]!); // omitted
|
|
128
|
+
next.push(paths[j]! + '/' + concrete); // included
|
|
129
|
+
}
|
|
130
|
+
paths = next;
|
|
131
|
+
} else {
|
|
132
|
+
for (let j = 0; j < paths.length; j++) {
|
|
133
|
+
paths[j] = paths[j]! + '/' + part;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return Array.from(new Set(paths));
|
|
138
|
+
}
|
|
139
|
+
|
|
114
140
|
protected _add(method: string, path: string, handlers: HandlersChain) {
|
|
115
141
|
let fullPath = (this.prefix + "/" + path)
|
|
116
142
|
.replace(/\/+/g, "/");
|
|
@@ -127,14 +153,18 @@ export class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
127
153
|
}
|
|
128
154
|
}
|
|
129
155
|
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
156
|
+
const expanded = BareRouter.expandOptionalPaths(fullPath || "");
|
|
157
|
+
const upperMethod = method.toUpperCase();
|
|
158
|
+
for (let i = 0; i < expanded.length; i++) {
|
|
159
|
+
this.routes.push({
|
|
160
|
+
method: upperMethod,
|
|
161
|
+
path: expanded[i]!,
|
|
162
|
+
handlers: [...this.groupMiddleware, ...resolvedHandlers]
|
|
163
|
+
});
|
|
164
|
+
}
|
|
135
165
|
this._onRouteMutate?.();
|
|
136
166
|
return this;
|
|
137
|
-
}
|
|
167
|
+
}
|
|
138
168
|
|
|
139
169
|
public get: AddRouterRoute<Routes, 'GET'> = ((path: string, ...h: HandlersChain) => this._add("GET", path, h)) as any;
|
|
140
170
|
public post: AddRouterRoute<Routes, 'POST'> = ((path: string, ...h: HandlersChain) => this._add("POST", path, h)) as any;
|
|
@@ -150,12 +180,16 @@ export class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
150
180
|
return this;
|
|
151
181
|
}) as any;
|
|
152
182
|
|
|
183
|
+
protected _createGroupRouter(prefix: string, middleware: any[]): BareRouter<any> {
|
|
184
|
+
return new BareRouter(prefix, middleware);
|
|
185
|
+
}
|
|
186
|
+
|
|
153
187
|
public group = (path: string, ...args: any[]) => {
|
|
154
188
|
const callback = args.pop();
|
|
155
189
|
const middleware = args;
|
|
156
190
|
|
|
157
191
|
const newPrefix = (this.prefix + "/" + path).replace(/\/+/g, "/");
|
|
158
|
-
const subRouter =
|
|
192
|
+
const subRouter = this._createGroupRouter(newPrefix, [...this.groupMiddleware, ...middleware]);
|
|
159
193
|
|
|
160
194
|
callback(subRouter);
|
|
161
195
|
this.routes.push(...subRouter.routes);
|
package/src/edge.ts
CHANGED
|
@@ -304,11 +304,17 @@ class EdgeRadixNode<Env> {
|
|
|
304
304
|
}
|
|
305
305
|
}
|
|
306
306
|
|
|
307
|
+
export interface BareEdgeOptions {
|
|
308
|
+
/** Base path prefix applied to all registered routes (e.g. '/api'). */
|
|
309
|
+
prefix?: string;
|
|
310
|
+
}
|
|
311
|
+
|
|
307
312
|
/**
|
|
308
313
|
* Zero-Node Edge Web Framework (`barejs/edge`).
|
|
309
314
|
* Drop-in `export default app` for Cloudflare Workers, Vercel Edge, Deno Deploy, and Bun.
|
|
310
315
|
*/
|
|
311
316
|
export class BareEdge<Env = Record<string, any>> {
|
|
317
|
+
private prefix: string = '';
|
|
312
318
|
private staticRoutes: Map<string, EdgeRouteEntry<Env>> = new Map();
|
|
313
319
|
private dynamicTrees: Map<string, EdgeRadixNode<Env>> = new Map();
|
|
314
320
|
private middlewares: EdgeMiddleware<Env>[] = [];
|
|
@@ -316,6 +322,24 @@ export class BareEdge<Env = Record<string, any>> {
|
|
|
316
322
|
private responseHooks: Array<(ctx: EdgeContext<Env>, res: Response) => Promise<void> | void> = [];
|
|
317
323
|
private errorHandler: ((err: any, ctx: EdgeContext<Env>) => Response | Promise<Response>) | null = null;
|
|
318
324
|
|
|
325
|
+
constructor(options?: BareEdgeOptions) {
|
|
326
|
+
if (options?.prefix) {
|
|
327
|
+
this.prefix = ('/' + options.prefix).replace(/\/+/g, '/').replace(/\/$/, '');
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Set or append a base path prefix for all subsequently registered routes
|
|
333
|
+
* (e.g. `new BareEdge().basePath('/api')` for Next.js Edge / Astro / SvelteKit).
|
|
334
|
+
*/
|
|
335
|
+
public basePath(path: string): this {
|
|
336
|
+
const clean = ('/' + path).replace(/\/+/g, '/').replace(/\/$/, '');
|
|
337
|
+
if (clean) {
|
|
338
|
+
this.prefix = (this.prefix + clean).replace(/\/+/g, '/').replace(/\/$/, '');
|
|
339
|
+
}
|
|
340
|
+
return this;
|
|
341
|
+
}
|
|
342
|
+
|
|
319
343
|
public use(mw: EdgeMiddleware<Env>): this {
|
|
320
344
|
this.middlewares.push(mw);
|
|
321
345
|
return this;
|
|
@@ -340,7 +364,8 @@ export class BareEdge<Env = Record<string, any>> {
|
|
|
340
364
|
if (fns.length === 0) return this;
|
|
341
365
|
const handler = fns[fns.length - 1] as EdgeHandler<Env>;
|
|
342
366
|
const middlewares = fns.slice(0, -1);
|
|
343
|
-
const
|
|
367
|
+
const joined = (this.prefix + '/' + path).replace(/\/+/g, '/');
|
|
368
|
+
const cleanPath = joined.length > 1 && joined.endsWith('/') ? joined.slice(0, -1) : (joined || '/');
|
|
344
369
|
const entry: EdgeRouteEntry<Env> = { middlewares, handler };
|
|
345
370
|
|
|
346
371
|
if (!cleanPath.includes(':') && !cleanPath.includes('*')) {
|
|
@@ -469,6 +494,8 @@ export function createSingleflight() {
|
|
|
469
494
|
}
|
|
470
495
|
|
|
471
496
|
export { tracing, serverTiming, type TracingOptions, type TracingSpan } from './utils/tracing';
|
|
497
|
+
export { html, raw, escapeHtml, type HtmlString } from './utils/html';
|
|
498
|
+
export { etag, type EtagOptions } from './utils/etag';
|
|
472
499
|
|
|
473
500
|
export {
|
|
474
501
|
BareEdge as BareJS,
|
package/src/index.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
// --- 1. Core Engine ---
|
|
9
|
-
export { BareJS, normalizePoolSize, type MacroDefinition, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
|
|
9
|
+
export { BareJS, normalizePoolSize, type BareJSOptions, type MacroDefinition, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
|
|
10
10
|
export { BareRouter, type InferSchema, type InferResponseSuccess, type InferResponseError, type PrefixRoutes } from './core/router';
|
|
11
11
|
|
|
12
12
|
/**
|
|
@@ -88,6 +88,8 @@ export { file, type FileResponseOptions } from './utils/file';
|
|
|
88
88
|
export { compress, type CompressOptions, type CompressionEncoding } from './utils/compress';
|
|
89
89
|
export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
|
|
90
90
|
export { tracing, serverTiming, type TracingOptions, type TracingSpan } from './utils/tracing';
|
|
91
|
+
export { html, raw, escapeHtml, type HtmlString } from './utils/html';
|
|
92
|
+
export { etag, type EtagOptions } from './utils/etag';
|
|
91
93
|
|
|
92
94
|
// --- 6. Authentication (Bun Native) ---
|
|
93
95
|
// Always deploy using process.env [2026-01-06]
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import type { Context, Middleware, Next } from '../core/context';
|
|
2
|
+
|
|
3
|
+
export interface CacheLike {
|
|
4
|
+
match(request: Request | string): Promise<Response | undefined>;
|
|
5
|
+
put(request: Request | string, response: Response): Promise<void>;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface CacheOptions {
|
|
9
|
+
/** Cache name for Web Cache API (`caches.open(cacheName)`). Falls back to `caches.default` on Cloudflare Workers. */
|
|
10
|
+
cacheName?: string;
|
|
11
|
+
/** Optional custom `Cache`-compatible store (overrides `globalThis.caches`, useful for testing or custom stores). */
|
|
12
|
+
cache?: CacheLike;
|
|
13
|
+
/** `Cache-Control` header value applied to cacheable 200 OK responses (e.g. `'public, max-age=60, stale-while-revalidate=30'`). */
|
|
14
|
+
cacheControl?: string;
|
|
15
|
+
/** Optional `Vary` header(s) appended to responses (e.g. `'Accept-Encoding'` or `['Accept', 'Accept-Language']`). */
|
|
16
|
+
vary?: string | string[];
|
|
17
|
+
/** Custom cache key generator (defaults to `ctx.req.url`). */
|
|
18
|
+
keyGenerator?: (ctx: Context) => string;
|
|
19
|
+
/** Await `cache.put()` before returning the response (default: `false`; uses `executionCtx.waitUntil` when available). */
|
|
20
|
+
wait?: boolean;
|
|
21
|
+
/** HTTP status codes eligible for caching (default: `[200]`). */
|
|
22
|
+
cacheableStatuses?: number[];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const resolveWebCache = async (cacheName?: string): Promise<CacheLike | null> => {
|
|
26
|
+
const g = globalThis as any;
|
|
27
|
+
const storage = g.caches;
|
|
28
|
+
if (!storage) return null;
|
|
29
|
+
if (cacheName && typeof storage.open === 'function') {
|
|
30
|
+
return await storage.open(cacheName);
|
|
31
|
+
}
|
|
32
|
+
if (storage.default && typeof storage.default.match === 'function') {
|
|
33
|
+
return storage.default as CacheLike;
|
|
34
|
+
}
|
|
35
|
+
if (typeof storage.open === 'function') {
|
|
36
|
+
return await storage.open('barejs-default');
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
const mergeVary = (headers: Headers, vary: string | string[]) => {
|
|
42
|
+
const incoming = Array.isArray(vary) ? vary : [vary];
|
|
43
|
+
const existing = headers.get('vary');
|
|
44
|
+
const set = new Set<string>(
|
|
45
|
+
existing ? existing.split(',').map((s) => s.trim().toLowerCase()).filter(Boolean) : []
|
|
46
|
+
);
|
|
47
|
+
const out = existing ? existing.split(',').map((s) => s.trim()).filter(Boolean) : [];
|
|
48
|
+
for (let i = 0; i < incoming.length; i++) {
|
|
49
|
+
const v = incoming[i]!.trim();
|
|
50
|
+
if (!v) continue;
|
|
51
|
+
const lower = v.toLowerCase();
|
|
52
|
+
if (!set.has(lower)) {
|
|
53
|
+
set.add(lower);
|
|
54
|
+
out.push(v);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if (out.length > 0) headers.set('vary', out.join(', '));
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Zero-dependency HTTP `Cache-Control` + Web Cache API (`caches.default` / `caches.open`) middleware.
|
|
62
|
+
* Edge-safe (Cloudflare Workers, Deno Deploy, Bun, Node.js). Caches GET/HEAD responses only.
|
|
63
|
+
*/
|
|
64
|
+
export const cache = (options: CacheOptions = {}): Middleware => {
|
|
65
|
+
const cacheName = options.cacheName;
|
|
66
|
+
const customCache = options.cache;
|
|
67
|
+
const cacheControl = options.cacheControl;
|
|
68
|
+
const vary = options.vary;
|
|
69
|
+
const keyGenerator = options.keyGenerator;
|
|
70
|
+
const wait = options.wait ?? false;
|
|
71
|
+
const allowedStatuses = new Set<number>(options.cacheableStatuses ?? [200]);
|
|
72
|
+
|
|
73
|
+
const wrapCache = async (ctx: Context, next: () => Promise<any>): Promise<any> => {
|
|
74
|
+
const method = ctx.req.method;
|
|
75
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
76
|
+
return next();
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const webCache = customCache ?? (await resolveWebCache(cacheName));
|
|
80
|
+
const cacheKey = keyGenerator ? keyGenerator(ctx) : ctx.req.url;
|
|
81
|
+
const cacheReq = new Request(cacheKey, { method: 'GET' });
|
|
82
|
+
|
|
83
|
+
if (webCache) {
|
|
84
|
+
const hit = await webCache.match(cacheReq);
|
|
85
|
+
if (hit) {
|
|
86
|
+
if (method === 'HEAD') {
|
|
87
|
+
return new Response(null, { status: hit.status, headers: hit.headers });
|
|
88
|
+
}
|
|
89
|
+
return hit;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const res = await next();
|
|
94
|
+
if (!(res instanceof Response)) return res;
|
|
95
|
+
|
|
96
|
+
const ct = (res.headers.get('content-type') || '').toLowerCase();
|
|
97
|
+
if (ct.includes('text/event-stream')) return res;
|
|
98
|
+
if (!allowedStatuses.has(res.status)) return res;
|
|
99
|
+
|
|
100
|
+
let out = res;
|
|
101
|
+
if (cacheControl || vary) {
|
|
102
|
+
const headers = new Headers(res.headers);
|
|
103
|
+
if (cacheControl && !headers.has('cache-control')) {
|
|
104
|
+
headers.set('cache-control', cacheControl);
|
|
105
|
+
}
|
|
106
|
+
if (vary) mergeVary(headers, vary);
|
|
107
|
+
out = new Response(res.body, { status: res.status, statusText: res.statusText, headers });
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (webCache && method === 'GET') {
|
|
111
|
+
const putPromise = webCache.put(cacheReq, out.clone() as any).catch(() => {});
|
|
112
|
+
const execCtx = (ctx as any).executionCtx;
|
|
113
|
+
if (wait) {
|
|
114
|
+
await putPromise;
|
|
115
|
+
} else if (execCtx && typeof execCtx.waitUntil === 'function') {
|
|
116
|
+
execCtx.waitUntil(putPromise);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return out;
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
const mw: Middleware = async (ctx: Context, next?: Next) => {
|
|
124
|
+
return wrapCache(ctx, () => Promise.resolve(next ? next() : undefined));
|
|
125
|
+
};
|
|
126
|
+
(mw as any).__wrapHandler = wrapCache;
|
|
127
|
+
return mw;
|
|
128
|
+
};
|