barejs 0.1.49 → 0.1.51

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.
Files changed (43) hide show
  1. package/README.md +257 -98
  2. package/dist/index.js +157 -94
  3. package/dist/types/client/index.d.ts +24 -22
  4. package/dist/types/core/bare.d.ts +83 -3
  5. package/dist/types/core/context.d.ts +47 -1
  6. package/dist/types/core/radix.d.ts +1 -0
  7. package/dist/types/core/router.d.ts +21 -10
  8. package/dist/types/index.d.ts +16 -8
  9. package/dist/types/security/auth.d.ts +10 -1
  10. package/dist/types/security/cors.d.ts +7 -3
  11. package/dist/types/security/csrf.d.ts +12 -0
  12. package/dist/types/security/idempotency.d.ts +22 -0
  13. package/dist/types/security/resilience.d.ts +17 -0
  14. package/dist/types/security/timeout.d.ts +6 -0
  15. package/dist/types/security/validators.d.ts +18 -0
  16. package/dist/types/utils/compress.d.ts +12 -0
  17. package/dist/types/utils/health.d.ts +17 -0
  18. package/dist/types/utils/logger.d.ts +22 -0
  19. package/dist/types/utils/openapi.d.ts +23 -1
  20. package/dist/types/utils/static.d.ts +5 -1
  21. package/llms.txt +138 -0
  22. package/package.json +3 -1
  23. package/src/client/index.ts +61 -18
  24. package/src/core/bare.ts +409 -49
  25. package/src/core/context.ts +266 -32
  26. package/src/core/radix.ts +37 -3
  27. package/src/core/router.ts +43 -16
  28. package/src/index.ts +25 -9
  29. package/src/security/auth.ts +68 -11
  30. package/src/security/cors.ts +85 -31
  31. package/src/security/csrf.ts +84 -0
  32. package/src/security/hash.ts +8 -2
  33. package/src/security/headers.ts +12 -3
  34. package/src/security/idempotency.ts +118 -0
  35. package/src/security/rateLimit.ts +1 -6
  36. package/src/security/resilience.ts +91 -0
  37. package/src/security/timeout.ts +32 -0
  38. package/src/security/validators.ts +201 -5
  39. package/src/utils/compress.ts +49 -0
  40. package/src/utils/health.ts +65 -0
  41. package/src/utils/logger.ts +66 -0
  42. package/src/utils/openapi.ts +59 -14
  43. package/src/utils/static.ts +71 -5
@@ -30,9 +30,10 @@ const errorJSON = (data: any, status = 400) =>
30
30
  export const typebox = (schema: any): Middleware => {
31
31
  const check = Compiler.TypeCompiler.Compile(schema);
32
32
 
33
- const mw: Middleware = async (ctx: Context, next?: Next) => {
33
+ const mw: Middleware = async (ctx: any, next?: Next) => {
34
34
  try {
35
- const body = await ctx.jsonBody();
35
+ const isCtx = ctx instanceof Object && 'req' in ctx;
36
+ const body = isCtx ? await ctx.jsonBody() : await ctx.json();
36
37
 
37
38
  if (!check.Check(body)) {
38
39
  const error = check.Errors(body).First();
@@ -44,7 +45,7 @@ export const typebox = (schema: any): Middleware => {
44
45
  });
45
46
  }
46
47
 
47
- (ctx as any).body = body;
48
+ if (isCtx) (ctx as any).body = body;
48
49
  return next ? next() : undefined;
49
50
  } catch {
50
51
  return errorJSON({ status: 'error', message: 'Malformed JSON payload' });
@@ -61,6 +62,7 @@ export const native = (schema: any): Middleware => {
61
62
  const props = schema.properties || {};
62
63
  const keys = Object.keys(props);
63
64
  const kLen = keys.length;
65
+ const reqSet = Array.isArray(schema.required) ? new Set<string>(schema.required) : null;
64
66
 
65
67
  const mw: Middleware = async (ctx: any, next?: any) => {
66
68
  try {
@@ -73,7 +75,19 @@ export const native = (schema: any): Middleware => {
73
75
 
74
76
  for (let i = 0; i < kLen; i++) {
75
77
  const k = keys[i]!;
76
- if (!Object.hasOwn(body, k) || typeof body[k] !== props[k]?.type) {
78
+ const hasKey = Object.hasOwn(body, k) && body[k] !== undefined;
79
+ if (!hasKey) {
80
+ if (!reqSet || reqSet.has(k)) {
81
+ return errorJSON({
82
+ status: 'error',
83
+ code: 'TYPE_MISMATCH',
84
+ message: `Field '${k}' must be of type ${props[k]?.type}`,
85
+ field: k
86
+ });
87
+ }
88
+ continue;
89
+ }
90
+ if (typeof body[k] !== props[k]?.type) {
77
91
  return errorJSON({
78
92
  status: 'error',
79
93
  code: 'TYPE_MISMATCH',
@@ -135,4 +149,186 @@ export const validate = (schema: any): Middleware => {
135
149
  return native(schema);
136
150
  };
137
151
 
138
- export { typebox as t, zod as z, native as n, validate as v };
152
+ export { typebox as t, zod as z, native as n, validate as v };
153
+
154
+ export interface RouteDetail {
155
+ summary?: string;
156
+ description?: string;
157
+ tags?: string[];
158
+ }
159
+
160
+ export interface RouteSchemas {
161
+ body?: any;
162
+ query?: any;
163
+ params?: any;
164
+ headers?: any;
165
+ response?: any;
166
+ /** Strip undeclared properties from validated body using JIT projector (prevents Mass Assignment) */
167
+ stripUnknown?: boolean;
168
+ detail?: RouteDetail;
169
+ maxBodySize?: number;
170
+ }
171
+
172
+ const compileSingleSchema = (schema: any): ((val: any) => { ok: boolean; data?: any; error?: any }) => {
173
+ if (schema && '_def' in schema) {
174
+ return (val: any) => {
175
+ const r = schema.safeParse(val);
176
+ return r.success ? { ok: true, data: r.data } : { ok: false, error: r.error.flatten() };
177
+ };
178
+ }
179
+ const check = Compiler.TypeCompiler.Compile(schema);
180
+ return (val: any) => {
181
+ if (check.Check(val)) return { ok: true, data: val };
182
+ const first = check.Errors(val).First();
183
+ return { ok: false, error: { message: first?.message || 'Invalid input', path: first?.path } };
184
+ };
185
+ };
186
+
187
+ const buildProjectorExpr = (schema: any, accessor: string): string | null => {
188
+ const props = schema?.properties;
189
+ if (!props || typeof props !== 'object') return null;
190
+ const entries: string[] = [];
191
+ for (const [k, subSchema] of Object.entries<any>(props)) {
192
+ const keyLit = JSON.stringify(k);
193
+ const propAccess = `${accessor}[${keyLit}]`;
194
+ const nestedExpr = buildProjectorExpr(subSchema, propAccess);
195
+ if (nestedExpr) {
196
+ entries.push(`${keyLit}: (${propAccess} && typeof ${propAccess} === 'object' && !Array.isArray(${propAccess})) ? ${nestedExpr} : ${propAccess}`);
197
+ } else {
198
+ entries.push(`${keyLit}: ${propAccess}`);
199
+ }
200
+ }
201
+ return `{ ${entries.join(', ')} }`;
202
+ };
203
+
204
+ const compileProjector = (schema: any): ((val: any) => any) | null => {
205
+ if (!schema || '_def' in schema) return null; // Zod safeParse strips unknown keys natively
206
+ if (schema.type === 'array' && schema.items) {
207
+ const itemExpr = buildProjectorExpr(schema.items, 'item');
208
+ if (!itemExpr) return null;
209
+ return new Function(
210
+ `return function(arr) {
211
+ if (!Array.isArray(arr)) return arr;
212
+ const len = arr.length;
213
+ const out = new Array(len);
214
+ for (let i = 0; i < len; i++) {
215
+ const item = arr[i];
216
+ out[i] = (item && typeof item === 'object' && !Array.isArray(item)) ? ${itemExpr} : item;
217
+ }
218
+ return out;
219
+ }`
220
+ )();
221
+ }
222
+ const objExpr = buildProjectorExpr(schema, 'o');
223
+ if (!objExpr) return null;
224
+ return new Function(
225
+ `return function(o) {
226
+ if (!o || typeof o !== 'object' || Array.isArray(o)) return o;
227
+ return ${objExpr};
228
+ }`
229
+ )();
230
+ };
231
+
232
+ export const createResponseFilter = (schema: any): ((val: any) => any) => {
233
+ const check = compileSingleSchema(schema);
234
+ const project = compileProjector(schema);
235
+
236
+ return (val: any) => {
237
+ if (val instanceof Response) return val;
238
+ const filtered = project ? project(val) : val;
239
+ const r = check(filtered);
240
+ if (!r.ok) {
241
+ return errorJSON({ status: 'error', code: 'RESPONSE_VALIDATION_FAILED', error: r.error }, 500);
242
+ }
243
+ return r.data;
244
+ };
245
+ };
246
+
247
+ const coerceFields = (obj: Record<string, any>, schema: any): Record<string, any> => {
248
+ const props = schema?.properties || (schema?._def?.shape ? (typeof schema._def.shape === 'function' ? schema._def.shape() : schema._def.shape) : null);
249
+ if (!props) return obj;
250
+ const out: Record<string, any> = { ...obj };
251
+ for (const [k, propSchema] of Object.entries<any>(props)) {
252
+ if (!Object.hasOwn(out, k)) continue;
253
+ const val = out[k];
254
+ if (typeof val !== 'string') continue;
255
+ const tType = propSchema?.type || propSchema?._def?.typeName;
256
+ if (tType === 'number' || tType === 'integer' || tType === 'ZodNumber') {
257
+ if (val.trim() !== '') {
258
+ const n = Number(val);
259
+ if (!Number.isNaN(n)) out[k] = n;
260
+ }
261
+ } else if (tType === 'boolean' || tType === 'ZodBoolean') {
262
+ if (val === 'true') out[k] = true;
263
+ else if (val === 'false') out[k] = false;
264
+ }
265
+ }
266
+ return out;
267
+ };
268
+
269
+ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
270
+ const bodyCheck = schemas.body ? compileSingleSchema(schemas.body) : null;
271
+ const queryCheck = schemas.query ? compileSingleSchema(schemas.query) : null;
272
+ const paramsCheck = schemas.params ? compileSingleSchema(schemas.params) : null;
273
+ const headersCheck = schemas.headers ? compileSingleSchema(schemas.headers) : null;
274
+ const bodyProjector = schemas.stripUnknown && schemas.body ? compileProjector(schemas.body) : null;
275
+ const responseFilter = schemas.response ? createResponseFilter(schemas.response) : null;
276
+ const maxBodySize = schemas.maxBodySize ?? 1048576;
277
+
278
+ const validateSyncParts = (ctx: Context): Response | undefined => {
279
+ if (paramsCheck) {
280
+ const coerced = coerceFields(ctx.params, schemas.params);
281
+ const r = paramsCheck(coerced);
282
+ if (!r.ok) return errorJSON({ status: 'error', code: 'PARAMS_INVALID', error: r.error });
283
+ ctx.params = r.data;
284
+ }
285
+ if (queryCheck) {
286
+ const coerced = coerceFields(ctx.query, schemas.query);
287
+ const r = queryCheck(coerced);
288
+ if (!r.ok) return errorJSON({ status: 'error', code: 'QUERY_INVALID', error: r.error });
289
+ ctx._query = r.data;
290
+ }
291
+ if (headersCheck) {
292
+ const hdrObj: Record<string, string> = {};
293
+ ctx.req.headers.forEach((v, k) => { hdrObj[k.toLowerCase()] = v; });
294
+ const r = headersCheck(hdrObj);
295
+ if (!r.ok) return errorJSON({ status: 'error', code: 'HEADERS_INVALID', error: r.error });
296
+ }
297
+ return undefined;
298
+ };
299
+
300
+ if (!bodyCheck) {
301
+ const syncMw: Middleware = (ctx: Context, next?: Next) => {
302
+ const errRes = validateSyncParts(ctx);
303
+ if (errRes) return errRes;
304
+ return next ? next() : undefined;
305
+ };
306
+ (syncMw as any).__routeSchemas = schemas;
307
+ if (responseFilter) (syncMw as any).__responseFilter = responseFilter;
308
+ return syncMw;
309
+ }
310
+
311
+ const mw: Middleware = async (ctx: Context, next?: Next) => {
312
+ const errRes = validateSyncParts(ctx);
313
+ if (errRes) return errRes;
314
+
315
+ let body: any;
316
+ try {
317
+ body = await ctx.jsonBody(maxBodySize);
318
+ } catch (e: any) {
319
+ if (e?.status === 413) {
320
+ return errorJSON({ status: 'error', code: 'PAYLOAD_TOO_LARGE', message: 'Payload Too Large' }, 413);
321
+ }
322
+ return errorJSON({ status: 'error', message: 'Malformed JSON payload' });
323
+ }
324
+ const r = bodyCheck(body);
325
+ if (!r.ok) return errorJSON({ status: 'error', code: 'VALIDATION_FAILED', error: r.error });
326
+ ctx.body = bodyProjector ? bodyProjector(r.data) : r.data;
327
+
328
+ return next ? next() : undefined;
329
+ };
330
+ (mw as any).__schema = schemas.body;
331
+ (mw as any).__routeSchemas = schemas;
332
+ if (responseFilter) (mw as any).__responseFilter = responseFilter;
333
+ return mw;
334
+ };
@@ -0,0 +1,49 @@
1
+ import type { Context, Middleware, Next } from '../core/context';
2
+
3
+ export interface CompressOptions {
4
+ /** Minimum response size in bytes before gzip compression is applied (default: 1024) */
5
+ minSize?: number;
6
+ /** Gzip compression level 0-9 (default: 6) */
7
+ level?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
8
+ }
9
+
10
+ /**
11
+ * Zero-dependency Gzip compression middleware powered by Bun.gzipSync (native C/Zig).
12
+ * Skips streaming SSE responses, already-encoded responses, and payloads below minSize.
13
+ */
14
+ export const compress = (options: CompressOptions = {}): Middleware => {
15
+ const minSize = options.minSize ?? 1024;
16
+ const level = options.level ?? 6;
17
+
18
+ const applyCompress = async (ctx: Context, res: any) => {
19
+ if (ctx.req.method === 'HEAD') return res;
20
+ const accept = ctx.req.headers.get('accept-encoding');
21
+ if (!accept || !accept.includes('gzip')) return res;
22
+ if (!(res instanceof Response)) return res;
23
+ if (res.status === 204 || res.status === 304) return res;
24
+ if (res.headers.has('content-encoding')) return res;
25
+
26
+ const ct = res.headers.get('content-type') || '';
27
+ if (ct.includes('text/event-stream')) return res;
28
+
29
+ const buf = await res.arrayBuffer();
30
+ if (buf.byteLength < minSize) {
31
+ return new Response(buf, { status: res.status, headers: res.headers });
32
+ }
33
+
34
+ const gz = Bun.gzipSync(new Uint8Array(buf), { level });
35
+ const headers = new Headers(res.headers);
36
+ headers.set('Content-Encoding', 'gzip');
37
+ headers.set('Vary', 'Accept-Encoding');
38
+ headers.delete('Content-Length');
39
+
40
+ return new Response(gz, { status: res.status, headers });
41
+ };
42
+
43
+ const mw: Middleware = async (ctx: Context, next?: Next) => {
44
+ const res = await (next ? next() : undefined);
45
+ return applyCompress(ctx, res);
46
+ };
47
+ (mw as any).__compress = applyCompress;
48
+ return mw;
49
+ };
@@ -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> => {
@@ -52,19 +56,36 @@ export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {})
52
56
 
53
57
  const method = route.method.toLowerCase();
54
58
  const params: any[] = [];
55
- const paramMatches = route.path.matchAll(/:([a-zA-Z0-9_]+)/g);
56
- for (const m of paramMatches) {
57
- params.push({
58
- name: m[1],
59
- in: 'path',
60
- required: true,
61
- schema: { type: 'string' }
62
- });
63
- }
64
-
65
59
  let requestBody: any = undefined;
60
+ let responseSchema: any = undefined;
61
+ let detail: any = undefined;
62
+ let paramSchemaObj: Record<string, any> | null = null;
63
+
66
64
  for (const h of route.handlers) {
67
- if (h && (h as any).__schema) {
65
+ if (!h) continue;
66
+ const rs = (h as any).__routeSchemas;
67
+ if (rs) {
68
+ if (rs.detail) detail = rs.detail;
69
+ if (rs.params) paramSchemaObj = extractSchema(rs.params);
70
+ if (rs.query) {
71
+ const qSchema = extractSchema(rs.query);
72
+ const qReq = new Set<string>(qSchema.required || []);
73
+ for (const [k, prop] of Object.entries(qSchema.properties || {})) {
74
+ params.push({ name: k, in: 'query', required: qReq.has(k), schema: prop });
75
+ }
76
+ }
77
+ if (rs.headers) {
78
+ const hSchema = extractSchema(rs.headers);
79
+ const hReq = new Set<string>(hSchema.required || []);
80
+ for (const [k, prop] of Object.entries(hSchema.properties || {})) {
81
+ params.push({ name: k, in: 'header', required: hReq.has(k), schema: prop });
82
+ }
83
+ }
84
+ if (rs.response) {
85
+ responseSchema = extractSchema(rs.response);
86
+ }
87
+ }
88
+ if ((h as any).__schema && !requestBody) {
68
89
  requestBody = {
69
90
  required: true,
70
91
  content: {
@@ -73,16 +94,34 @@ export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {})
73
94
  }
74
95
  }
75
96
  };
76
- break;
77
97
  }
78
98
  }
79
99
 
100
+ const paramMatches = route.path.matchAll(/:([a-zA-Z0-9_]+)/g);
101
+ for (const m of paramMatches) {
102
+ const pName = m[1]!;
103
+ const pProp = paramSchemaObj?.properties?.[pName] || { type: 'string' };
104
+ params.unshift({
105
+ name: pName,
106
+ in: 'path',
107
+ required: true,
108
+ schema: pProp
109
+ });
110
+ }
111
+
80
112
  paths[openApiPath][method] = {
81
- summary: `${route.method} ${openApiPath}`,
113
+ summary: detail?.summary || `${route.method} ${openApiPath}`,
114
+ ...(detail?.description ? { description: detail.description } : {}),
115
+ ...(detail?.tags ? { tags: detail.tags } : {}),
82
116
  ...(params.length ? { parameters: params } : {}),
83
117
  ...(requestBody ? { requestBody } : {}),
84
118
  responses: {
85
- '200': { description: 'Success' }
119
+ '200': {
120
+ description: 'Success',
121
+ ...(responseSchema
122
+ ? { content: { 'application/json': { schema: responseSchema } } }
123
+ : {})
124
+ }
86
125
  }
87
126
  };
88
127
  }
@@ -94,6 +133,12 @@ export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {})
94
133
  version: options.version || '1.0.0',
95
134
  ...(options.description ? { description: options.description } : {})
96
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 } : {}),
97
142
  paths
98
143
  };
99
144
  };
@@ -1,10 +1,19 @@
1
1
  import { resolve, sep } from 'node:path';
2
+ import { stat, realpath } from 'node:fs/promises';
2
3
 
3
- export const staticFile = (root: string = 'public') => {
4
+ export interface StaticOptions {
5
+ maxAge?: number;
6
+ etag?: boolean;
7
+ }
8
+
9
+ export const staticFile = (root: string = 'public', options: StaticOptions = {}) => {
4
10
  const rootDir = resolve(process.cwd(), root);
5
11
  const rootPrefix = rootDir.endsWith(sep) ? rootDir : rootDir + sep;
12
+ let realRootPromise: Promise<string> | null = null;
13
+ const maxAge = options.maxAge ?? 3600;
14
+ const enableEtag = options.etag !== false;
6
15
 
7
- return async (ctx: any, next: any) => {
16
+ const mw = async (ctx: any, next: any) => {
8
17
  const method = ctx.req.method;
9
18
  if (method !== 'GET' && method !== 'HEAD') return next();
10
19
 
@@ -33,11 +42,68 @@ export const staticFile = (root: string = 'public') => {
33
42
  return ctx.status(403).send('Forbidden');
34
43
  }
35
44
 
45
+ let fileSize = 0;
46
+ 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');
55
+ }
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
+ }
36
63
  const file = Bun.file(filePath);
37
- if (await file.exists()) {
38
- return new Response(file);
64
+
65
+ const headers: Record<string, string> = {
66
+ 'Cache-Control': `public, max-age=${maxAge}`,
67
+ 'Accept-Ranges': 'bytes'
68
+ };
69
+
70
+ if (enableEtag) {
71
+ const etag = `W/"${fileSize.toString(16)}-${mtimeMs.toString(16)}"`;
72
+ headers['ETag'] = etag;
73
+ const ifNoneMatch = ctx.req.headers?.get?.('if-none-match');
74
+ if (ifNoneMatch && ifNoneMatch === etag) {
75
+ return new Response(null, { status: 304, headers });
76
+ }
77
+ }
78
+
79
+ const rangeHeader = ctx.req.headers?.get?.('range');
80
+ if (rangeHeader && rangeHeader.startsWith('bytes=') && fileSize > 0) {
81
+ const [startStr, endStr] = rangeHeader.slice(6).split('-');
82
+ let start = startStr ? Number(startStr) : 0;
83
+ let end = endStr ? Number(endStr) : fileSize - 1;
84
+ if (!startStr && endStr) {
85
+ start = Math.max(0, fileSize - Number(endStr));
86
+ end = fileSize - 1;
87
+ }
88
+ if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end >= fileSize || start > end) {
89
+ return new Response(null, {
90
+ status: 416,
91
+ headers: { ...headers, 'Content-Range': `bytes */${fileSize}` }
92
+ });
93
+ }
94
+ headers['Content-Range'] = `bytes ${start}-${end}/${fileSize}`;
95
+ headers['Content-Length'] = String(end - start + 1);
96
+ if (file.type) headers['Content-Type'] = file.type;
97
+ return new Response(method === 'HEAD' ? null : file.slice(start, end + 1), {
98
+ status: 206,
99
+ headers
100
+ });
39
101
  }
40
102
 
41
- return next();
103
+ if (file.type) headers['Content-Type'] = file.type;
104
+ headers['Content-Length'] = String(fileSize);
105
+ return new Response(method === 'HEAD' ? null : file, { status: 200, headers });
42
106
  };
107
+ (mw as any).__isStatic = true;
108
+ return mw;
43
109
  };