barejs 0.1.55 → 0.1.56

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.
@@ -22,34 +22,39 @@ export const compress = (options: CompressOptions = {}): Middleware => {
22
22
  const encodings: CompressionEncoding[] = options.encodings ?? ['zstd', 'br', 'gzip'];
23
23
  const hasZstd = typeof (Bun as any).zstdCompressSync === 'function';
24
24
 
25
- const isAccepted = (lower: string, enc: CompressionEncoding): boolean => {
25
+ const negotiate = (accept: string): CompressionEncoding | null => {
26
+ const lower = accept.toLowerCase();
26
27
  const parts = lower.split(',');
28
+ const qMap = new Map<string, number>();
27
29
  for (let i = 0; i < parts.length; i++) {
28
30
  const part = parts[i]!.trim();
29
31
  if (!part) continue;
30
32
  const semi = part.indexOf(';');
31
33
  const name = (semi === -1 ? part : part.slice(0, semi)).trim();
32
- if (name !== enc) continue;
34
+ let qVal = 1;
33
35
  if (semi !== -1) {
34
36
  const qMatch = part.slice(semi + 1).match(/q\s*=\s*([0-9.]+)/);
35
37
  if (qMatch) {
36
- const qVal = parseFloat(qMatch[1]!);
37
- if (Number.isFinite(qVal) && qVal <= 0) return false;
38
+ const parsed = parseFloat(qMatch[1]!);
39
+ if (Number.isFinite(parsed)) qVal = parsed;
38
40
  }
39
41
  }
40
- return true;
42
+ qMap.set(name, qVal);
41
43
  }
42
- return false;
43
- };
44
44
 
45
- const negotiate = (accept: string): CompressionEncoding | null => {
46
- const lower = accept.toLowerCase();
45
+ const wildcardQ = qMap.get('*');
46
+ let bestEnc: CompressionEncoding | null = null;
47
+ let bestQ = 0;
47
48
  for (let i = 0; i < encodings.length; i++) {
48
49
  const enc = encodings[i]!;
49
50
  if (enc === 'zstd' && !hasZstd) continue;
50
- if (isAccepted(lower, enc)) return enc;
51
+ const q = qMap.has(enc) ? qMap.get(enc)! : (wildcardQ ?? 0);
52
+ if (q > bestQ) {
53
+ bestQ = q;
54
+ bestEnc = enc;
55
+ }
51
56
  }
52
- return null;
57
+ return bestEnc;
53
58
  };
54
59
 
55
60
  const applyCompress = async (ctx: Context, res: any) => {
@@ -59,10 +64,10 @@ export const compress = (options: CompressOptions = {}): Middleware => {
59
64
  const chosen = negotiate(accept);
60
65
  if (!chosen) return res;
61
66
  if (!(res instanceof Response)) return res;
62
- if (res.status === 204 || res.status === 304) return res;
67
+ if (res.status === 204 || res.status === 206 || res.status === 304) return res;
63
68
  if (res.headers.has('content-encoding')) return res;
64
69
 
65
- const ct = res.headers.get('content-type') || '';
70
+ const ct = (res.headers.get('content-type') || '').toLowerCase();
66
71
  if (ct.includes('text/event-stream')) return res;
67
72
 
68
73
  const buf = await res.arrayBuffer();
@@ -6,6 +6,7 @@ export interface OpenAPIOptions {
6
6
  tags?: Array<{ name: string; description?: string }>;
7
7
  securitySchemes?: Record<string, Record<string, any>>;
8
8
  security?: Array<Record<string, string[]>>;
9
+ excludePaths?: string[];
9
10
  }
10
11
 
11
12
  const zodToJsonSchema = (schema: any): Record<string, any> => {
@@ -26,11 +27,34 @@ const zodToJsonSchema = (schema: any): Record<string, any> => {
26
27
  }
27
28
  return { type: 'object', properties, ...(required.length ? { required } : {}) };
28
29
  }
29
- if (typeName === 'ZodString') return { type: 'string' };
30
- if (typeName === 'ZodNumber') return { type: 'number' };
30
+ if (typeName === 'ZodString') {
31
+ const out: Record<string, any> = { type: 'string' };
32
+ for (const c of def.checks || []) {
33
+ if (c.kind === 'min') out.minLength = c.value;
34
+ else if (c.kind === 'max') out.maxLength = c.value;
35
+ else if (c.kind === 'email') out.format = 'email';
36
+ else if (c.kind === 'uuid') out.format = 'uuid';
37
+ }
38
+ return out;
39
+ }
40
+ if (typeName === 'ZodNumber') {
41
+ const out: Record<string, any> = { type: 'number' };
42
+ for (const c of def.checks || []) {
43
+ if (c.kind === 'int') out.type = 'integer';
44
+ else if (c.kind === 'min') out[c.inclusive === false ? 'exclusiveMinimum' : 'minimum'] = c.value;
45
+ else if (c.kind === 'max') out[c.inclusive === false ? 'exclusiveMaximum' : 'maximum'] = c.value;
46
+ }
47
+ return out;
48
+ }
49
+ if (typeName === 'ZodNullable') return { anyOf: [zodToJsonSchema(def.innerType), { type: 'null' }] };
31
50
  if (typeName === 'ZodBoolean') return { type: 'boolean' };
32
51
  if (typeName === 'ZodArray') return { type: 'array', items: zodToJsonSchema(def.type) };
33
52
  if (typeName === 'ZodOptional' || typeName === 'ZodDefault') return zodToJsonSchema(def.innerType);
53
+ if (typeName === 'ZodEffects') return zodToJsonSchema(def.schema);
54
+ if (typeName === 'ZodLiteral') return { const: def.value };
55
+ if (typeName === 'ZodDate') return { type: 'string', format: 'date-time' };
56
+ if (typeName === 'ZodRecord') return { type: 'object', additionalProperties: zodToJsonSchema(def.valueType) };
57
+ if (typeName === 'ZodUnion' && Array.isArray(def.options)) return { anyOf: def.options.map(zodToJsonSchema) };
34
58
  if (typeName === 'ZodEnum') return { type: 'string', enum: def.values };
35
59
  return { type: 'object' };
36
60
  };
@@ -44,13 +68,15 @@ const extractSchema = (schema: any): Record<string, any> => {
44
68
 
45
69
  export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {}) => {
46
70
  const paths: Record<string, Record<string, any>> = {};
71
+ const excluded = new Set<string>(['/docs', '/docs/json', ...(options.excludePaths || [])]);
47
72
 
48
73
  for (const route of routes) {
49
- if (route.path === '/docs' || route.path === '/docs/json') continue;
74
+ if (excluded.has(route.path)) continue;
50
75
 
51
76
  const openApiPath = ('/' + route.path)
52
77
  .replace(/\/+/g, '/')
53
- .replace(/:([a-zA-Z0-9_]+)/g, '{$1}');
78
+ .replace(/:([a-zA-Z0-9_]+)/g, '{$1}')
79
+ .replace(/\/\*$/, '/{wildcard}');
54
80
 
55
81
  if (!paths[openApiPath]) paths[openApiPath] = {};
56
82
 
@@ -97,23 +123,28 @@ export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {})
97
123
  }
98
124
  }
99
125
 
126
+ const pathParams: any[] = [];
100
127
  const paramMatches = route.path.matchAll(/:([a-zA-Z0-9_]+)/g);
101
128
  for (const m of paramMatches) {
102
129
  const pName = m[1]!;
103
130
  const pProp = paramSchemaObj?.properties?.[pName] || { type: 'string' };
104
- params.unshift({
131
+ pathParams.push({
105
132
  name: pName,
106
133
  in: 'path',
107
134
  required: true,
108
135
  schema: pProp
109
136
  });
110
137
  }
138
+ if (/\/\*$/.test(route.path)) {
139
+ pathParams.push({ name: 'wildcard', in: 'path', required: true, schema: { type: 'string' } });
140
+ }
141
+ const allParams = [...pathParams, ...params];
111
142
 
112
143
  paths[openApiPath][method] = {
113
144
  summary: detail?.summary || `${route.method} ${openApiPath}`,
114
145
  ...(detail?.description ? { description: detail.description } : {}),
115
146
  ...(detail?.tags ? { tags: detail.tags } : {}),
116
- ...(params.length ? { parameters: params } : {}),
147
+ ...(allParams.length ? { parameters: allParams } : {}),
117
148
  ...(requestBody ? { requestBody } : {}),
118
149
  responses: {
119
150
  '200': {
@@ -143,9 +174,16 @@ export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {})
143
174
  };
144
175
  };
145
176
 
177
+ const escapeHtmlAttr = (s: string): string =>
178
+ s.replace(/&/g, '&amp;')
179
+ .replace(/"/g, '&quot;')
180
+ .replace(/'/g, '&#39;')
181
+ .replace(/</g, '&lt;')
182
+ .replace(/>/g, '&gt;');
183
+
146
184
  export const renderDocsHTML = (specUrl: string, title: string = 'BareJS API Docs'): string => {
147
185
  const safeTitle = title.replace(/[<>&"]/g, '');
148
- const safeSpecUrl = JSON.stringify(specUrl);
186
+ const safeSpecUrl = escapeHtmlAttr(specUrl);
149
187
  return `<!doctype html>
150
188
  <html>
151
189
  <head>
@@ -154,7 +192,7 @@ export const renderDocsHTML = (specUrl: string, title: string = 'BareJS API Docs
154
192
  <meta name="viewport" content="width=device-width, initial-scale=1" />
155
193
  </head>
156
194
  <body>
157
- <script id="api-reference" data-url=${safeSpecUrl}></script>
195
+ <script id="api-reference" data-url="${safeSpecUrl}"></script>
158
196
  <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
159
197
  </body>
160
198
  </html>`;
@@ -110,6 +110,7 @@ export const staticFile = (root: string = 'public', options: StaticOptions = {})
110
110
  });
111
111
  }
112
112
  } catch {
113
+ realRootPromise = null;
113
114
  return next?.();
114
115
  }
115
116
  }
@@ -123,22 +124,47 @@ export const staticFile = (root: string = 'public', options: StaticOptions = {})
123
124
 
124
125
  if (enableEtag) {
125
126
  headers['ETag'] = etag;
126
- const ifNoneMatch = ctx.req.headers?.get?.('if-none-match');
127
- if (ifNoneMatch && ifNoneMatch === etag) {
128
- return new Response(null, { status: 304, headers });
127
+ const ifNoneMatch = ctx.req.headers?.get?.('if-none-match')?.trim();
128
+ if (ifNoneMatch) {
129
+ const matched = ifNoneMatch === '*' || ifNoneMatch.split(',').some((t: string) => t.trim() === etag);
130
+ if (matched) {
131
+ return new Response(null, { status: 304, headers });
132
+ }
129
133
  }
130
134
  }
131
135
 
132
136
  const rangeHeader = ctx.req.headers?.get?.('range');
133
137
  if (rangeHeader && rangeHeader.startsWith('bytes=') && fileSize > 0) {
134
- const [startStr, endStr] = rangeHeader.slice(6).split('-');
138
+ const rangeSpec = rangeHeader.slice(6);
139
+ const parts = rangeSpec.split('-');
140
+ if (parts.length !== 2) {
141
+ return new Response(null, {
142
+ status: 416,
143
+ headers: { ...headers, 'Content-Range': `bytes */${fileSize}` }
144
+ });
145
+ }
146
+ const [startStr, endStr] = parts as [string, string];
147
+ const validDigits = /^\d+$/;
148
+ if ((!startStr && !endStr) || (startStr && !validDigits.test(startStr)) || (endStr && !validDigits.test(endStr))) {
149
+ return new Response(null, {
150
+ status: 416,
151
+ headers: { ...headers, 'Content-Range': `bytes */${fileSize}` }
152
+ });
153
+ }
135
154
  let start = startStr ? Number(startStr) : 0;
136
- let end = endStr ? Number(endStr) : fileSize - 1;
155
+ let end = endStr ? Math.min(Number(endStr), fileSize - 1) : fileSize - 1;
137
156
  if (!startStr && endStr) {
138
- start = Math.max(0, fileSize - Number(endStr));
157
+ const suffixLen = Number(endStr);
158
+ if (suffixLen === 0) {
159
+ return new Response(null, {
160
+ status: 416,
161
+ headers: { ...headers, 'Content-Range': `bytes */${fileSize}` }
162
+ });
163
+ }
164
+ start = Math.max(0, fileSize - suffixLen);
139
165
  end = fileSize - 1;
140
166
  }
141
- if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end >= fileSize || start > end) {
167
+ if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || start >= fileSize || start > end) {
142
168
  return new Response(null, {
143
169
  status: 416,
144
170
  headers: { ...headers, 'Content-Range': `bytes */${fileSize}` }