barejs 0.1.51 → 0.1.54

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.
@@ -1,9 +1,26 @@
1
1
  import { resolve, sep } from 'node:path';
2
2
  import { stat, realpath } from 'node:fs/promises';
3
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
+ }
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 = {}) => {
@@ -13,6 +30,12 @@ export const staticFile = (root: string = 'public', options: StaticOptions = {})
13
30
  const maxAge = options.maxAge ?? 3600;
14
31
  const enableEtag = options.etag !== false;
15
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
+
16
39
  const mw = async (ctx: any, next: any) => {
17
40
  const method = ctx.req.method;
18
41
  if (method !== 'GET' && method !== 'HEAD') return next();
@@ -42,25 +65,56 @@ export const staticFile = (root: string = 'public', options: StaticOptions = {})
42
65
  return ctx.status(403).send('Forbidden');
43
66
  }
44
67
 
68
+ let realFile = filePath;
45
69
  let fileSize = 0;
46
70
  let mtimeMs = 0;
47
- try {
48
- const [realRoot, realFile] = await Promise.all([
49
- (realRootPromise ??= realpath(rootDir)),
50
- realpath(filePath)
51
- ]);
52
- const realPrefix = realRoot.endsWith(sep) ? realRoot : realRoot + sep;
53
- if (realFile !== realRoot && !realFile.startsWith(realPrefix)) {
54
- return ctx.status(403).send('Forbidden');
71
+ let etag = '';
72
+
73
+ const cached = metaCache?.get(filePath);
74
+ if (cached && Date.now() < cached.expiresAt) {
75
+ // Refresh LRU position
76
+ metaCache!.delete(filePath);
77
+ metaCache!.set(filePath, cached);
78
+ realFile = cached.realFile;
79
+ fileSize = cached.fileSize;
80
+ mtimeMs = cached.mtimeMs;
81
+ etag = cached.etag;
82
+ } else {
83
+ try {
84
+ const [realRoot, resolvedFile] = await Promise.all([
85
+ (realRootPromise ??= realpath(rootDir)),
86
+ realpath(filePath)
87
+ ]);
88
+ const realPrefix = realRoot.endsWith(sep) ? realRoot : realRoot + sep;
89
+ if (resolvedFile !== realRoot && !resolvedFile.startsWith(realPrefix)) {
90
+ return ctx.status(403).send('Forbidden');
91
+ }
92
+ const st = await stat(resolvedFile);
93
+ if (st.isDirectory()) return next();
94
+ realFile = resolvedFile;
95
+ fileSize = st.size;
96
+ mtimeMs = Math.floor(st.mtimeMs);
97
+ etag = enableEtag ? `W/"${fileSize.toString(16)}-${mtimeMs.toString(16)}"` : '';
98
+
99
+ if (metaCache) {
100
+ if (metaCache.size >= cacheMax) {
101
+ const oldest = metaCache.keys().next().value;
102
+ if (oldest !== undefined) metaCache.delete(oldest);
103
+ }
104
+ metaCache.set(filePath, {
105
+ realFile,
106
+ fileSize,
107
+ mtimeMs,
108
+ etag,
109
+ expiresAt: Date.now() + cacheTtl
110
+ });
111
+ }
112
+ } catch {
113
+ return next();
55
114
  }
56
- const st = await stat(realFile);
57
- if (st.isDirectory()) return next();
58
- fileSize = st.size;
59
- mtimeMs = Math.floor(st.mtimeMs);
60
- } catch {
61
- return next();
62
115
  }
63
- const file = Bun.file(filePath);
116
+
117
+ const file = Bun.file(realFile);
64
118
 
65
119
  const headers: Record<string, string> = {
66
120
  'Cache-Control': `public, max-age=${maxAge}`,
@@ -68,7 +122,6 @@ export const staticFile = (root: string = 'public', options: StaticOptions = {})
68
122
  };
69
123
 
70
124
  if (enableEtag) {
71
- const etag = `W/"${fileSize.toString(16)}-${mtimeMs.toString(16)}"`;
72
125
  headers['ETag'] = etag;
73
126
  const ifNoneMatch = ctx.req.headers?.get?.('if-none-match');
74
127
  if (ifNoneMatch && ifNoneMatch === etag) {