barejs 0.1.50 → 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.
@@ -0,0 +1,91 @@
1
+ import type { Context, Middleware, Next } from '../core/context';
2
+
3
+ export type CircuitState = 'CLOSED' | 'OPEN' | 'HALF_OPEN';
4
+
5
+ export interface CircuitBreakerOptions {
6
+ /** Number of consecutive failures before opening the circuit (default: 5) */
7
+ failureThreshold?: number;
8
+ /** Cooldown in milliseconds before transitioning from OPEN to HALF_OPEN (default: 30000) */
9
+ resetTimeoutMs?: number;
10
+ /** Custom predicate to determine if a response or error counts as a failure */
11
+ isFailure?: (res: any, err?: any) => boolean;
12
+ /** Optional callback fired when circuit state changes */
13
+ onStateChange?: (from: CircuitState, to: CircuitState) => void;
14
+ }
15
+
16
+ /**
17
+ * Lightweight Circuit Breaker middleware.
18
+ * Protects downstream databases and external APIs from cascading failures.
19
+ */
20
+ export const circuitBreaker = (options: CircuitBreakerOptions = {}): Middleware => {
21
+ const failureThreshold = options.failureThreshold ?? 5;
22
+ const resetTimeoutMs = options.resetTimeoutMs ?? 30_000;
23
+ const isFailure = options.isFailure ?? ((res: any, err?: any) => Boolean(err) || (res instanceof Response && res.status >= 500));
24
+
25
+ let state: CircuitState = 'CLOSED';
26
+ let failures = 0;
27
+ let openedAt = 0;
28
+ let halfOpenInFlight = false;
29
+
30
+ const setState = (nextState: CircuitState) => {
31
+ if (state !== nextState) {
32
+ const prev = state;
33
+ state = nextState;
34
+ options.onStateChange?.(prev, nextState);
35
+ }
36
+ };
37
+
38
+ const runWithBreaker = async (exec: () => any) => {
39
+ if (state === 'OPEN') {
40
+ const elapsed = Date.now() - openedAt;
41
+ if (elapsed < resetTimeoutMs) {
42
+ const retryAfterSec = Math.max(1, Math.ceil((resetTimeoutMs - elapsed) / 1000));
43
+ return Response.json(
44
+ { status: 'error', code: 'CIRCUIT_OPEN', message: 'Service temporarily unavailable' },
45
+ { status: 503, headers: { 'Retry-After': String(retryAfterSec) } }
46
+ );
47
+ }
48
+ setState('HALF_OPEN');
49
+ }
50
+
51
+ let isHalfOpenProbe = false;
52
+ if (state === 'HALF_OPEN') {
53
+ if (halfOpenInFlight) {
54
+ return Response.json(
55
+ { status: 'error', code: 'CIRCUIT_OPEN', message: 'Service temporarily unavailable' },
56
+ { status: 503, headers: { 'Retry-After': '1' } }
57
+ );
58
+ }
59
+ halfOpenInFlight = true;
60
+ isHalfOpenProbe = true;
61
+ }
62
+
63
+ try {
64
+ const res = await exec();
65
+ if (isFailure(res)) {
66
+ failures++;
67
+ if (isHalfOpenProbe || failures >= failureThreshold) {
68
+ openedAt = Date.now();
69
+ setState('OPEN');
70
+ }
71
+ } else {
72
+ failures = 0;
73
+ if (isHalfOpenProbe) setState('CLOSED');
74
+ }
75
+ return res;
76
+ } catch (err) {
77
+ failures++;
78
+ if (isHalfOpenProbe || failures >= failureThreshold) {
79
+ openedAt = Date.now();
80
+ setState('OPEN');
81
+ }
82
+ throw err;
83
+ } finally {
84
+ if (isHalfOpenProbe) halfOpenInFlight = false;
85
+ }
86
+ };
87
+
88
+ const mw: Middleware = (_ctx: Context, next?: Next) => runWithBreaker(() => (next ? next() : undefined));
89
+ (mw as any).__circuitBreaker = runWithBreaker;
90
+ return mw;
91
+ };
@@ -0,0 +1,151 @@
1
+ export interface RateLimitStore {
2
+ increment(key: string, windowMs: number): Promise<{ count: number; resetAt: number }> | { count: number; resetAt: number };
3
+ }
4
+
5
+ export interface CachedIdempotentEntry {
6
+ status: number;
7
+ body?: any;
8
+ rawBody?: ArrayBuffer;
9
+ contentType?: string;
10
+ expiresAt: number;
11
+ }
12
+
13
+ export interface IdempotencyStore {
14
+ get(key: string): Promise<CachedIdempotentEntry | undefined> | CachedIdempotentEntry | undefined;
15
+ set(key: string, entry: CachedIdempotentEntry, ttlMs: number): Promise<void> | void;
16
+ acquire(key: string, ttlMs?: number): Promise<boolean> | boolean;
17
+ release(key: string): Promise<void> | void;
18
+ }
19
+
20
+ export interface RevocationStore {
21
+ revoke(tokenOrJti: string, ttlMs: number): Promise<void> | void;
22
+ isRevoked(tokenOrJti: string): Promise<boolean> | boolean;
23
+ }
24
+
25
+ export type BareStore = RateLimitStore & IdempotencyStore & RevocationStore;
26
+
27
+ export interface RedisStoreOptions {
28
+ /** Key prefix for all entries (default: 'barejs:') */
29
+ prefix?: string;
30
+ }
31
+
32
+ /**
33
+ * Lightweight Redis adapter compatible with both Bun.redis and ioredis.
34
+ * Implements RateLimitStore, IdempotencyStore, and RevocationStore.
35
+ */
36
+ export const redisStore = (client: any, options: RedisStoreOptions = {}): BareStore => {
37
+ const prefix = options.prefix ?? 'barejs:';
38
+
39
+ const useSend = typeof client.send === 'function';
40
+
41
+ const cmdGet = (key: string) =>
42
+ useSend ? client.send('GET', [key]) : client.get(key);
43
+
44
+ const cmdDel = (key: string) =>
45
+ useSend ? client.send('DEL', [key]) : client.del(key);
46
+
47
+ const cmdIncr = (key: string) =>
48
+ useSend ? client.send('INCR', [key]) : client.incr(key);
49
+
50
+ const setWithTtl = async (key: string, value: string, ttlMs: number): Promise<void> => {
51
+ if (useSend) {
52
+ await client.send('SET', [key, value, 'PX', String(ttlMs)]);
53
+ return;
54
+ }
55
+ try {
56
+ await client.set(key, value, 'PX', ttlMs);
57
+ } catch {
58
+ await client.set(key, value);
59
+ if (typeof client.pexpire === 'function') {
60
+ await client.pexpire(key, ttlMs);
61
+ } else if (typeof client.expire === 'function') {
62
+ await client.expire(key, Math.max(1, Math.ceil(ttlMs / 1000)));
63
+ }
64
+ }
65
+ };
66
+
67
+ return {
68
+ async increment(key: string, windowMs: number): Promise<{ count: number; resetAt: number }> {
69
+ const fullKey = `${prefix}rl:${key}`;
70
+ const count = Number(await cmdIncr(fullKey));
71
+ if (count === 1) {
72
+ if (useSend) {
73
+ await client.send('PEXPIRE', [fullKey, String(windowMs)]);
74
+ } else if (typeof client.pexpire === 'function') {
75
+ await client.pexpire(fullKey, windowMs);
76
+ } else if (typeof client.expire === 'function') {
77
+ await client.expire(fullKey, Math.max(1, Math.ceil(windowMs / 1000)));
78
+ }
79
+ }
80
+ let pttl = windowMs;
81
+ if (useSend) {
82
+ const res = Number(await client.send('PTTL', [fullKey]));
83
+ if (Number.isFinite(res) && res > 0) pttl = res;
84
+ } else if (typeof client.pttl === 'function') {
85
+ const res = Number(await client.pttl(fullKey));
86
+ if (Number.isFinite(res) && res > 0) pttl = res;
87
+ } else if (typeof client.ttl === 'function') {
88
+ const res = Number(await client.ttl(fullKey));
89
+ if (Number.isFinite(res) && res > 0) pttl = res * 1000;
90
+ }
91
+ return { count, resetAt: Date.now() + pttl };
92
+ },
93
+
94
+ async get(key: string): Promise<CachedIdempotentEntry | undefined> {
95
+ const raw = await cmdGet(`${prefix}idem:${key}`);
96
+ if (!raw) return undefined;
97
+ try {
98
+ const parsed = JSON.parse(typeof raw === 'string' ? raw : String(raw));
99
+ if (parsed.rawBodyBase64) {
100
+ const buf = Buffer.from(parsed.rawBodyBase64, 'base64');
101
+ return {
102
+ status: parsed.status,
103
+ rawBody: buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength),
104
+ contentType: parsed.contentType,
105
+ expiresAt: parsed.expiresAt
106
+ };
107
+ }
108
+ return parsed;
109
+ } catch {
110
+ return undefined;
111
+ }
112
+ },
113
+
114
+ async set(key: string, entry: CachedIdempotentEntry, ttlMs: number): Promise<void> {
115
+ const serializable: any = {
116
+ status: entry.status,
117
+ expiresAt: entry.expiresAt
118
+ };
119
+ if (entry.rawBody !== undefined) {
120
+ serializable.rawBodyBase64 = Buffer.from(entry.rawBody).toString('base64');
121
+ serializable.contentType = entry.contentType;
122
+ } else {
123
+ serializable.body = entry.body;
124
+ }
125
+ await setWithTtl(`${prefix}idem:${key}`, JSON.stringify(serializable), ttlMs);
126
+ },
127
+
128
+ async acquire(key: string, ttlMs: number = 30_000): Promise<boolean> {
129
+ const lockKey = `${prefix}idem:lock:${key}`;
130
+ if (useSend) {
131
+ const res = await client.send('SET', [lockKey, '1', 'PX', String(ttlMs), 'NX']);
132
+ return res === 'OK' || res === true;
133
+ }
134
+ const res = await client.set(lockKey, '1', 'PX', ttlMs, 'NX');
135
+ return res === 'OK' || res === true || res === 1;
136
+ },
137
+
138
+ async release(key: string): Promise<void> {
139
+ await cmdDel(`${prefix}idem:lock:${key}`);
140
+ },
141
+
142
+ async revoke(tokenOrJti: string, ttlMs: number): Promise<void> {
143
+ await setWithTtl(`${prefix}rev:${tokenOrJti}`, '1', ttlMs);
144
+ },
145
+
146
+ async isRevoked(tokenOrJti: string): Promise<boolean> {
147
+ const val = await cmdGet(`${prefix}rev:${tokenOrJti}`);
148
+ return val !== null && val !== undefined;
149
+ }
150
+ };
151
+ };
@@ -163,6 +163,8 @@ export interface RouteSchemas {
163
163
  params?: any;
164
164
  headers?: any;
165
165
  response?: any;
166
+ /** Strip undeclared properties from validated body using JIT projector (prevents Mass Assignment) */
167
+ stripUnknown?: boolean;
166
168
  detail?: RouteDetail;
167
169
  maxBodySize?: number;
168
170
  }
@@ -269,8 +271,10 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
269
271
  const queryCheck = schemas.query ? compileSingleSchema(schemas.query) : null;
270
272
  const paramsCheck = schemas.params ? compileSingleSchema(schemas.params) : null;
271
273
  const headersCheck = schemas.headers ? compileSingleSchema(schemas.headers) : null;
274
+ const bodyProjector = schemas.stripUnknown && schemas.body ? compileProjector(schemas.body) : null;
272
275
  const responseFilter = schemas.response ? createResponseFilter(schemas.response) : null;
273
276
  const maxBodySize = schemas.maxBodySize ?? 1048576;
277
+ const hasSyncParts = Boolean(paramsCheck || queryCheck || headersCheck);
274
278
 
275
279
  const validateSyncParts = (ctx: Context): Response | undefined => {
276
280
  if (paramsCheck) {
@@ -296,8 +300,10 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
296
300
 
297
301
  if (!bodyCheck) {
298
302
  const syncMw: Middleware = (ctx: Context, next?: Next) => {
299
- const errRes = validateSyncParts(ctx);
300
- if (errRes) return errRes;
303
+ if (hasSyncParts) {
304
+ const errRes = validateSyncParts(ctx);
305
+ if (errRes) return errRes;
306
+ }
301
307
  return next ? next() : undefined;
302
308
  };
303
309
  (syncMw as any).__routeSchemas = schemas;
@@ -306,8 +312,10 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
306
312
  }
307
313
 
308
314
  const mw: Middleware = async (ctx: Context, next?: Next) => {
309
- const errRes = validateSyncParts(ctx);
310
- if (errRes) return errRes;
315
+ if (hasSyncParts) {
316
+ const errRes = validateSyncParts(ctx);
317
+ if (errRes) return errRes;
318
+ }
311
319
 
312
320
  let body: any;
313
321
  try {
@@ -320,7 +328,7 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
320
328
  }
321
329
  const r = bodyCheck(body);
322
330
  if (!r.ok) return errorJSON({ status: 'error', code: 'VALIDATION_FAILED', error: r.error });
323
- ctx.body = r.data;
331
+ ctx.body = bodyProjector ? bodyProjector(r.data) : r.data;
324
332
 
325
333
  return next ? next() : undefined;
326
334
  };
@@ -0,0 +1,80 @@
1
+ import type { Context, Middleware, Next } from '../core/context';
2
+ import { brotliCompressSync, constants as zlibConstants } from 'node:zlib';
3
+
4
+ export type CompressionEncoding = 'zstd' | 'br' | 'gzip';
5
+
6
+ export interface CompressOptions {
7
+ /** Minimum response size in bytes before compression is applied (default: 1024) */
8
+ minSize?: number;
9
+ /** Gzip compression level 0-9 (default: 6) */
10
+ level?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
11
+ /** Preferred compression encodings in priority order (default: ['zstd', 'br', 'gzip']) */
12
+ encodings?: CompressionEncoding[];
13
+ }
14
+
15
+ /**
16
+ * Zero-dependency response compression middleware supporting zstd, brotli (br), and gzip.
17
+ * Negotiates encoding from Accept-Encoding, and skips streaming SSE, 204/304, already-encoded, and small payloads.
18
+ */
19
+ export const compress = (options: CompressOptions = {}): Middleware => {
20
+ const minSize = options.minSize ?? 1024;
21
+ const level = options.level ?? 6;
22
+ const encodings: CompressionEncoding[] = options.encodings ?? ['zstd', 'br', 'gzip'];
23
+ const hasZstd = typeof (Bun as any).zstdCompressSync === 'function';
24
+
25
+ const negotiate = (accept: string): CompressionEncoding | null => {
26
+ const lower = accept.toLowerCase();
27
+ for (let i = 0; i < encodings.length; i++) {
28
+ const enc = encodings[i]!;
29
+ if (enc === 'zstd' && hasZstd && lower.includes('zstd')) return 'zstd';
30
+ if (enc === 'br' && lower.includes('br')) return 'br';
31
+ if (enc === 'gzip' && lower.includes('gzip')) return 'gzip';
32
+ }
33
+ return null;
34
+ };
35
+
36
+ const applyCompress = async (ctx: Context, res: any) => {
37
+ if (ctx.req.method === 'HEAD') return res;
38
+ const accept = ctx.req.headers.get('accept-encoding');
39
+ if (!accept) return res;
40
+ const chosen = negotiate(accept);
41
+ if (!chosen) return res;
42
+ if (!(res instanceof Response)) return res;
43
+ if (res.status === 204 || res.status === 304) return res;
44
+ if (res.headers.has('content-encoding')) return res;
45
+
46
+ const ct = res.headers.get('content-type') || '';
47
+ if (ct.includes('text/event-stream')) return res;
48
+
49
+ const buf = await res.arrayBuffer();
50
+ if (buf.byteLength < minSize) {
51
+ return new Response(buf, { status: res.status, headers: res.headers });
52
+ }
53
+
54
+ const raw = new Uint8Array(buf);
55
+ let compressed: Uint8Array;
56
+ if (chosen === 'zstd') {
57
+ compressed = (Bun as any).zstdCompressSync(raw);
58
+ } else if (chosen === 'br') {
59
+ compressed = brotliCompressSync(raw, {
60
+ params: { [zlibConstants.BROTLI_PARAM_QUALITY]: Math.min(11, Math.max(1, level)) }
61
+ });
62
+ } else {
63
+ compressed = Bun.gzipSync(raw, { level });
64
+ }
65
+
66
+ const headers = new Headers(res.headers);
67
+ headers.set('Content-Encoding', chosen);
68
+ headers.set('Vary', 'Accept-Encoding');
69
+ headers.delete('Content-Length');
70
+
71
+ return new Response(compressed, { status: res.status, headers });
72
+ };
73
+
74
+ const mw: Middleware = async (ctx: Context, next?: Next) => {
75
+ const res = await (next ? next() : undefined);
76
+ return applyCompress(ctx, res);
77
+ };
78
+ (mw as any).__compress = applyCompress;
79
+ return mw;
80
+ };
@@ -0,0 +1,65 @@
1
+ import type { BarePlugin } from '../index';
2
+
3
+ export type HealthCheckFn = () => boolean | Promise<boolean>;
4
+
5
+ export interface HealthcheckOptions {
6
+ /** Liveness endpoint path (default: '/health') */
7
+ path?: string;
8
+ /** Optional readiness endpoint path (e.g. '/ready') */
9
+ readyPath?: string;
10
+ /** Optional version string to include in response */
11
+ version?: string;
12
+ /** Named dependency checks (e.g. { db: () => pingDb() }) */
13
+ checks?: Record<string, HealthCheckFn>;
14
+ }
15
+
16
+ /**
17
+ * Built-in Healthcheck & Readiness plugin for BareJS.
18
+ * Registers /health (and optional /ready) returning 200 OK or 503 Service Unavailable.
19
+ */
20
+ export const healthcheck = (options: HealthcheckOptions = {}): BarePlugin => {
21
+ const path = options.path ?? '/health';
22
+ const readyPath = options.readyPath;
23
+ const checks = options.checks;
24
+ const startedAt = Date.now();
25
+
26
+ const evaluate = async () => {
27
+ const checkResults: Record<string, 'ok' | 'fail'> = {};
28
+ let healthy = true;
29
+
30
+ if (checks) {
31
+ const entries = Object.entries(checks);
32
+ await Promise.all(
33
+ entries.map(async ([name, fn]) => {
34
+ try {
35
+ const ok = await fn();
36
+ checkResults[name] = ok ? 'ok' : 'fail';
37
+ if (!ok) healthy = false;
38
+ } catch {
39
+ checkResults[name] = 'fail';
40
+ healthy = false;
41
+ }
42
+ })
43
+ );
44
+ }
45
+
46
+ const payload: Record<string, any> = {
47
+ status: healthy ? 'ok' : 'degraded',
48
+ uptimeMs: Date.now() - startedAt,
49
+ timestamp: new Date().toISOString()
50
+ };
51
+ if (options.version) payload.version = options.version;
52
+ if (checks) payload.checks = checkResults;
53
+
54
+ return Response.json(payload, { status: healthy ? 200 : 503 });
55
+ };
56
+
57
+ return {
58
+ install(app: any) {
59
+ app.get(path, evaluate);
60
+ if (readyPath && readyPath !== path) {
61
+ app.get(readyPath, evaluate);
62
+ }
63
+ }
64
+ };
65
+ };
@@ -0,0 +1,66 @@
1
+ import type { Context, Middleware } from '../core/context';
2
+
3
+ export interface LogEntry {
4
+ timestamp: string;
5
+ method: string;
6
+ path: string;
7
+ requestId?: string;
8
+ ip?: string;
9
+ }
10
+
11
+ export interface LoggerOptions {
12
+ /** Output format: 'pretty' (default) or 'json' */
13
+ format?: 'pretty' | 'json';
14
+ /** Attach X-Request-Id response header from ctx.requestId (default: true) */
15
+ requestId?: boolean;
16
+ /** Skip logging for matching requests */
17
+ skip?: (ctx: Context, path: string) => boolean;
18
+ /** Custom log sink (defaults to console.log) */
19
+ onLog?: (entry: LogEntry) => void;
20
+ }
21
+
22
+ const getPath = (rawUrl: string): string => {
23
+ const s = rawUrl.indexOf('/', 8);
24
+ if (s === -1) return '/';
25
+ const q = rawUrl.indexOf('?', s);
26
+ return q === -1 ? rawUrl.slice(s) : rawUrl.slice(s, q);
27
+ };
28
+
29
+ /**
30
+ * Lightweight structured/pretty request logger & X-Request-Id middleware.
31
+ */
32
+ export const logger = (options: LoggerOptions = {}): Middleware => {
33
+ const format = options.format ?? 'pretty';
34
+ const attachId = options.requestId ?? true;
35
+ const skip = options.skip;
36
+ const sink = options.onLog;
37
+
38
+ return (ctx: Context, next) => {
39
+ const path = getPath(ctx.req.url);
40
+ if (skip?.(ctx, path)) return next();
41
+
42
+ const reqId = attachId ? ctx.requestId : undefined;
43
+ if (reqId) {
44
+ ctx.setHeader('x-request-id', reqId);
45
+ }
46
+
47
+ const entry: LogEntry = {
48
+ timestamp: new Date().toISOString(),
49
+ method: ctx.req.method,
50
+ path,
51
+ ...(reqId ? { requestId: reqId } : {}),
52
+ ip: ctx.ip
53
+ };
54
+
55
+ if (sink) {
56
+ sink(entry);
57
+ } else if (format === 'json') {
58
+ console.log(JSON.stringify(entry));
59
+ } else {
60
+ const idPart = reqId ? ` [${reqId.slice(0, 8)}]` : '';
61
+ console.log(`[${entry.timestamp}] ${entry.method} ${entry.path}${idPart}`);
62
+ }
63
+
64
+ return next();
65
+ };
66
+ };
@@ -2,6 +2,10 @@ export interface OpenAPIOptions {
2
2
  title?: string;
3
3
  version?: string;
4
4
  description?: string;
5
+ servers?: Array<{ url: string; description?: string }>;
6
+ tags?: Array<{ name: string; description?: string }>;
7
+ securitySchemes?: Record<string, Record<string, any>>;
8
+ security?: Array<Record<string, string[]>>;
5
9
  }
6
10
 
7
11
  const zodToJsonSchema = (schema: any): Record<string, any> => {
@@ -129,6 +133,12 @@ export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {})
129
133
  version: options.version || '1.0.0',
130
134
  ...(options.description ? { description: options.description } : {})
131
135
  },
136
+ ...(options.servers?.length ? { servers: options.servers } : {}),
137
+ ...(options.tags?.length ? { tags: options.tags } : {}),
138
+ ...(options.securitySchemes
139
+ ? { components: { securitySchemes: options.securitySchemes } }
140
+ : {}),
141
+ ...(options.security?.length ? { security: options.security } : {}),
132
142
  paths
133
143
  };
134
144
  };
@@ -1,17 +1,41 @@
1
1
  import { resolve, sep } from 'node:path';
2
- import { stat } from 'node:fs/promises';
2
+ import { stat, realpath } from 'node:fs/promises';
3
+
4
+ export interface StaticMetadataCacheOptions {
5
+ /** Maximum cached file metadata entries (default: 1000) */
6
+ maxEntries?: number;
7
+ /** Cache TTL in milliseconds (default: 30_000) */
8
+ ttlMs?: number;
9
+ }
3
10
 
4
11
  export interface StaticOptions {
5
12
  maxAge?: number;
6
13
  etag?: boolean;
14
+ /** Optional LRU metadata cache for realpath, stat, and ETag to avoid repeated syscalls */
15
+ cacheMetadata?: boolean | StaticMetadataCacheOptions;
16
+ }
17
+
18
+ interface StaticMetaEntry {
19
+ realFile: string;
20
+ fileSize: number;
21
+ mtimeMs: number;
22
+ etag: string;
23
+ expiresAt: number;
7
24
  }
8
25
 
9
26
  export const staticFile = (root: string = 'public', options: StaticOptions = {}) => {
10
27
  const rootDir = resolve(process.cwd(), root);
11
28
  const rootPrefix = rootDir.endsWith(sep) ? rootDir : rootDir + sep;
29
+ let realRootPromise: Promise<string> | null = null;
12
30
  const maxAge = options.maxAge ?? 3600;
13
31
  const enableEtag = options.etag !== false;
14
32
 
33
+ const cacheOpt = options.cacheMetadata;
34
+ const useCache = Boolean(cacheOpt);
35
+ const cacheMax = typeof cacheOpt === 'object' ? (cacheOpt.maxEntries ?? 1000) : 1000;
36
+ const cacheTtl = typeof cacheOpt === 'object' ? (cacheOpt.ttlMs ?? 30_000) : 30_000;
37
+ const metaCache = useCache ? new Map<string, StaticMetaEntry>() : null;
38
+
15
39
  const mw = async (ctx: any, next: any) => {
16
40
  const method = ctx.req.method;
17
41
  if (method !== 'GET' && method !== 'HEAD') return next();
@@ -43,14 +67,50 @@ export const staticFile = (root: string = 'public', options: StaticOptions = {})
43
67
 
44
68
  let fileSize = 0;
45
69
  let mtimeMs = 0;
46
- try {
47
- const st = await stat(filePath);
48
- if (st.isDirectory()) return next();
49
- fileSize = st.size;
50
- mtimeMs = Math.floor(st.mtimeMs);
51
- } catch {
52
- return next();
70
+ let etag = '';
71
+
72
+ const cached = metaCache?.get(filePath);
73
+ if (cached && Date.now() < cached.expiresAt) {
74
+ // Refresh LRU position
75
+ metaCache!.delete(filePath);
76
+ metaCache!.set(filePath, cached);
77
+ fileSize = cached.fileSize;
78
+ mtimeMs = cached.mtimeMs;
79
+ etag = cached.etag;
80
+ } else {
81
+ try {
82
+ const [realRoot, realFile] = await Promise.all([
83
+ (realRootPromise ??= realpath(rootDir)),
84
+ realpath(filePath)
85
+ ]);
86
+ const realPrefix = realRoot.endsWith(sep) ? realRoot : realRoot + sep;
87
+ if (realFile !== realRoot && !realFile.startsWith(realPrefix)) {
88
+ return ctx.status(403).send('Forbidden');
89
+ }
90
+ const st = await stat(realFile);
91
+ if (st.isDirectory()) return next();
92
+ fileSize = st.size;
93
+ mtimeMs = Math.floor(st.mtimeMs);
94
+ etag = enableEtag ? `W/"${fileSize.toString(16)}-${mtimeMs.toString(16)}"` : '';
95
+
96
+ if (metaCache) {
97
+ if (metaCache.size >= cacheMax) {
98
+ const oldest = metaCache.keys().next().value;
99
+ if (oldest !== undefined) metaCache.delete(oldest);
100
+ }
101
+ metaCache.set(filePath, {
102
+ realFile,
103
+ fileSize,
104
+ mtimeMs,
105
+ etag,
106
+ expiresAt: Date.now() + cacheTtl
107
+ });
108
+ }
109
+ } catch {
110
+ return next();
111
+ }
53
112
  }
113
+
54
114
  const file = Bun.file(filePath);
55
115
 
56
116
  const headers: Record<string, string> = {
@@ -59,7 +119,6 @@ export const staticFile = (root: string = 'public', options: StaticOptions = {})
59
119
  };
60
120
 
61
121
  if (enableEtag) {
62
- const etag = `W/"${fileSize.toString(16)}-${mtimeMs.toString(16)}"`;
63
122
  headers['ETag'] = etag;
64
123
  const ifNoneMatch = ctx.req.headers?.get?.('if-none-match');
65
124
  if (ifNoneMatch && ifNoneMatch === etag) {