barejs 0.1.49 → 0.1.50

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.
@@ -52,19 +52,36 @@ export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {})
52
52
 
53
53
  const method = route.method.toLowerCase();
54
54
  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
55
  let requestBody: any = undefined;
56
+ let responseSchema: any = undefined;
57
+ let detail: any = undefined;
58
+ let paramSchemaObj: Record<string, any> | null = null;
59
+
66
60
  for (const h of route.handlers) {
67
- if (h && (h as any).__schema) {
61
+ if (!h) continue;
62
+ const rs = (h as any).__routeSchemas;
63
+ if (rs) {
64
+ if (rs.detail) detail = rs.detail;
65
+ if (rs.params) paramSchemaObj = extractSchema(rs.params);
66
+ if (rs.query) {
67
+ const qSchema = extractSchema(rs.query);
68
+ const qReq = new Set<string>(qSchema.required || []);
69
+ for (const [k, prop] of Object.entries(qSchema.properties || {})) {
70
+ params.push({ name: k, in: 'query', required: qReq.has(k), schema: prop });
71
+ }
72
+ }
73
+ if (rs.headers) {
74
+ const hSchema = extractSchema(rs.headers);
75
+ const hReq = new Set<string>(hSchema.required || []);
76
+ for (const [k, prop] of Object.entries(hSchema.properties || {})) {
77
+ params.push({ name: k, in: 'header', required: hReq.has(k), schema: prop });
78
+ }
79
+ }
80
+ if (rs.response) {
81
+ responseSchema = extractSchema(rs.response);
82
+ }
83
+ }
84
+ if ((h as any).__schema && !requestBody) {
68
85
  requestBody = {
69
86
  required: true,
70
87
  content: {
@@ -73,16 +90,34 @@ export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {})
73
90
  }
74
91
  }
75
92
  };
76
- break;
77
93
  }
78
94
  }
79
95
 
96
+ const paramMatches = route.path.matchAll(/:([a-zA-Z0-9_]+)/g);
97
+ for (const m of paramMatches) {
98
+ const pName = m[1]!;
99
+ const pProp = paramSchemaObj?.properties?.[pName] || { type: 'string' };
100
+ params.unshift({
101
+ name: pName,
102
+ in: 'path',
103
+ required: true,
104
+ schema: pProp
105
+ });
106
+ }
107
+
80
108
  paths[openApiPath][method] = {
81
- summary: `${route.method} ${openApiPath}`,
109
+ summary: detail?.summary || `${route.method} ${openApiPath}`,
110
+ ...(detail?.description ? { description: detail.description } : {}),
111
+ ...(detail?.tags ? { tags: detail.tags } : {}),
82
112
  ...(params.length ? { parameters: params } : {}),
83
113
  ...(requestBody ? { requestBody } : {}),
84
114
  responses: {
85
- '200': { description: 'Success' }
115
+ '200': {
116
+ description: 'Success',
117
+ ...(responseSchema
118
+ ? { content: { 'application/json': { schema: responseSchema } } }
119
+ : {})
120
+ }
86
121
  }
87
122
  };
88
123
  }
@@ -1,10 +1,18 @@
1
1
  import { resolve, sep } from 'node:path';
2
+ import { stat } 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
+ const maxAge = options.maxAge ?? 3600;
13
+ const enableEtag = options.etag !== false;
6
14
 
7
- return async (ctx: any, next: any) => {
15
+ const mw = async (ctx: any, next: any) => {
8
16
  const method = ctx.req.method;
9
17
  if (method !== 'GET' && method !== 'HEAD') return next();
10
18
 
@@ -33,11 +41,60 @@ export const staticFile = (root: string = 'public') => {
33
41
  return ctx.status(403).send('Forbidden');
34
42
  }
35
43
 
44
+ let fileSize = 0;
45
+ 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();
53
+ }
36
54
  const file = Bun.file(filePath);
37
- if (await file.exists()) {
38
- return new Response(file);
55
+
56
+ const headers: Record<string, string> = {
57
+ 'Cache-Control': `public, max-age=${maxAge}`,
58
+ 'Accept-Ranges': 'bytes'
59
+ };
60
+
61
+ if (enableEtag) {
62
+ const etag = `W/"${fileSize.toString(16)}-${mtimeMs.toString(16)}"`;
63
+ headers['ETag'] = etag;
64
+ const ifNoneMatch = ctx.req.headers?.get?.('if-none-match');
65
+ if (ifNoneMatch && ifNoneMatch === etag) {
66
+ return new Response(null, { status: 304, headers });
67
+ }
68
+ }
69
+
70
+ const rangeHeader = ctx.req.headers?.get?.('range');
71
+ if (rangeHeader && rangeHeader.startsWith('bytes=') && fileSize > 0) {
72
+ const [startStr, endStr] = rangeHeader.slice(6).split('-');
73
+ let start = startStr ? Number(startStr) : 0;
74
+ let end = endStr ? Number(endStr) : fileSize - 1;
75
+ if (!startStr && endStr) {
76
+ start = Math.max(0, fileSize - Number(endStr));
77
+ end = fileSize - 1;
78
+ }
79
+ if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end >= fileSize || start > end) {
80
+ return new Response(null, {
81
+ status: 416,
82
+ headers: { ...headers, 'Content-Range': `bytes */${fileSize}` }
83
+ });
84
+ }
85
+ headers['Content-Range'] = `bytes ${start}-${end}/${fileSize}`;
86
+ headers['Content-Length'] = String(end - start + 1);
87
+ if (file.type) headers['Content-Type'] = file.type;
88
+ return new Response(method === 'HEAD' ? null : file.slice(start, end + 1), {
89
+ status: 206,
90
+ headers
91
+ });
39
92
  }
40
93
 
41
- return next();
94
+ if (file.type) headers['Content-Type'] = file.type;
95
+ headers['Content-Length'] = String(fileSize);
96
+ return new Response(method === 'HEAD' ? null : file, { status: 200, headers });
42
97
  };
98
+ (mw as any).__isStatic = true;
99
+ return mw;
43
100
  };