barejs 0.1.55 → 0.1.57
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.
- package/README.md +13 -13
- package/dist/index.js +216 -132
- package/dist/types/core/bare.d.ts +2 -2
- package/dist/types/core/context.d.ts +5 -0
- package/dist/types/core/radix.d.ts +3 -5
- package/dist/types/core/router.d.ts +1 -1
- package/dist/types/index.d.ts +2 -2
- package/dist/types/security/idempotency.d.ts +6 -1
- package/dist/types/security/store.d.ts +4 -1
- package/dist/types/utils/openapi.d.ts +1 -0
- package/llms.txt +3 -3
- package/package.json +2 -2
- package/src/client/index.ts +41 -13
- package/src/core/bare.ts +316 -95
- package/src/core/config.ts +3 -2
- package/src/core/context.ts +232 -54
- package/src/core/loader.ts +13 -3
- package/src/core/radix.ts +197 -110
- package/src/core/router.ts +39 -12
- package/src/index.ts +2 -2
- package/src/security/auth.ts +98 -9
- package/src/security/cors.ts +59 -9
- package/src/security/csrf.ts +6 -5
- package/src/security/hash.ts +9 -3
- package/src/security/idempotency.ts +169 -52
- package/src/security/rateLimit.ts +15 -5
- package/src/security/resilience.ts +34 -7
- package/src/security/store.ts +52 -8
- package/src/security/timeout.ts +5 -3
- package/src/security/validators.ts +574 -65
- package/src/utils/compress.ts +18 -13
- package/src/utils/openapi.ts +46 -8
- package/src/utils/static.ts +33 -7
package/src/utils/compress.ts
CHANGED
|
@@ -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
|
|
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
|
-
|
|
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
|
|
37
|
-
if (Number.isFinite(
|
|
38
|
+
const parsed = parseFloat(qMatch[1]!);
|
|
39
|
+
if (Number.isFinite(parsed)) qVal = parsed;
|
|
38
40
|
}
|
|
39
41
|
}
|
|
40
|
-
|
|
42
|
+
qMap.set(name, qVal);
|
|
41
43
|
}
|
|
42
|
-
return false;
|
|
43
|
-
};
|
|
44
44
|
|
|
45
|
-
|
|
46
|
-
|
|
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
|
-
|
|
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
|
|
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();
|
package/src/utils/openapi.ts
CHANGED
|
@@ -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')
|
|
30
|
-
|
|
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 (
|
|
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
|
-
|
|
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
|
-
...(
|
|
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, '&')
|
|
179
|
+
.replace(/"/g, '"')
|
|
180
|
+
.replace(/'/g, ''')
|
|
181
|
+
.replace(/</g, '<')
|
|
182
|
+
.replace(/>/g, '>');
|
|
183
|
+
|
|
146
184
|
export const renderDocsHTML = (specUrl: string, title: string = 'BareJS API Docs'): string => {
|
|
147
185
|
const safeTitle = title.replace(/[<>&"]/g, '');
|
|
148
|
-
const safeSpecUrl =
|
|
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
|
|
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>`;
|
package/src/utils/static.ts
CHANGED
|
@@ -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
|
|
128
|
-
|
|
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
|
|
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
|
-
|
|
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 ||
|
|
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}` }
|