barejs 0.1.47 → 0.1.49
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/LICENSE +20 -20
- package/README.md +221 -184
- package/dist/index.js +122 -187
- package/dist/types/client/index.d.ts +48 -0
- package/dist/types/core/bare.d.ts +14 -1
- package/dist/types/core/context.d.ts +9 -1
- package/dist/types/core/router.d.ts +1 -0
- package/dist/types/index.d.ts +6 -2
- package/dist/types/security/auth.d.ts +2 -2
- package/dist/types/security/headers.d.ts +9 -0
- package/dist/types/security/rateLimit.d.ts +9 -0
- package/dist/types/utils/openapi.d.ts +15 -0
- package/package.json +68 -68
- package/src/client/index.ts +121 -0
- package/src/core/bare.ts +463 -318
- package/src/core/config.ts +31 -31
- package/src/core/context.ts +205 -111
- package/src/core/loader.ts +12 -12
- package/src/core/radix.ts +184 -171
- package/src/core/router.ts +61 -62
- package/src/index.ts +73 -61
- package/src/security/auth.ts +174 -153
- package/src/security/cors.ts +45 -26
- package/src/security/hash.ts +22 -19
- package/src/security/headers.ts +59 -0
- package/src/security/rateLimit.ts +76 -0
- package/src/security/validators.ts +137 -133
- package/src/utils/openapi.ts +116 -0
- package/src/utils/static.ts +42 -25
|
@@ -1,134 +1,138 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* BareJS Ultimate Validation Engines
|
|
3
|
-
* All comments must be in English [2026-01-06]
|
|
4
|
-
* Optimized for Bun Runtime & Mechanical Sympathy [2026-01-05]
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
import * as Compiler from '@sinclair/typebox/compiler';
|
|
8
|
-
import { z } from 'zod';
|
|
9
|
-
import type { Context, Middleware, Next } from '../core/context';
|
|
10
|
-
|
|
11
|
-
// --- Types & Constants ---
|
|
12
|
-
export const Z = z;
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
* Standardized High-Performance Error Response
|
|
16
|
-
* Uses Bun's native Response.json for speed.
|
|
17
|
-
*/
|
|
18
|
-
const errorJSON = (data: any, status = 400) =>
|
|
19
|
-
Response.json(data, {
|
|
20
|
-
status,
|
|
21
|
-
headers: { 'Content-Type': 'application/json' }
|
|
22
|
-
});
|
|
23
|
-
|
|
24
|
-
// --- Engines ---
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* TypeBox JIT Engine (t)
|
|
28
|
-
* Pre-compiled JIT validation to outperform competitors by 55% [2026-01-05].
|
|
29
|
-
*/
|
|
30
|
-
export const typebox = (schema: any): Middleware => {
|
|
31
|
-
const check = Compiler.TypeCompiler.Compile(schema);
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
try {
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
return
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
};
|
|
56
|
-
|
|
57
|
-
/**
|
|
58
|
-
* Native Engine (n)
|
|
59
|
-
*/
|
|
60
|
-
export const native = (schema: any): Middleware => {
|
|
61
|
-
const props = schema.properties || {};
|
|
62
|
-
const keys = Object.keys(props);
|
|
63
|
-
const kLen = keys.length;
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
try {
|
|
67
|
-
const isCtx = ctx instanceof Object && 'req' in ctx;
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
return
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
const
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
return
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
return
|
|
132
|
-
|
|
133
|
-
|
|
1
|
+
/**
|
|
2
|
+
* BareJS Ultimate Validation Engines
|
|
3
|
+
* All comments must be in English [2026-01-06]
|
|
4
|
+
* Optimized for Bun Runtime & Mechanical Sympathy [2026-01-05]
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import * as Compiler from '@sinclair/typebox/compiler';
|
|
8
|
+
import { z } from 'zod';
|
|
9
|
+
import type { Context, Middleware, Next } from '../core/context';
|
|
10
|
+
|
|
11
|
+
// --- Types & Constants ---
|
|
12
|
+
export const Z = z;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Standardized High-Performance Error Response
|
|
16
|
+
* Uses Bun's native Response.json for speed.
|
|
17
|
+
*/
|
|
18
|
+
const errorJSON = (data: any, status = 400) =>
|
|
19
|
+
Response.json(data, {
|
|
20
|
+
status,
|
|
21
|
+
headers: { 'Content-Type': 'application/json' }
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
// --- Engines ---
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* TypeBox JIT Engine (t)
|
|
28
|
+
* Pre-compiled JIT validation to outperform competitors by 55% [2026-01-05].
|
|
29
|
+
*/
|
|
30
|
+
export const typebox = (schema: any): Middleware => {
|
|
31
|
+
const check = Compiler.TypeCompiler.Compile(schema);
|
|
32
|
+
|
|
33
|
+
const mw: Middleware = async (ctx: Context, next?: Next) => {
|
|
34
|
+
try {
|
|
35
|
+
const body = await ctx.jsonBody();
|
|
36
|
+
|
|
37
|
+
if (!check.Check(body)) {
|
|
38
|
+
const error = check.Errors(body).First();
|
|
39
|
+
return errorJSON({
|
|
40
|
+
status: 'error',
|
|
41
|
+
code: 'VALIDATION_FAILED',
|
|
42
|
+
message: error?.message || 'Invalid input',
|
|
43
|
+
path: error?.path || 'body'
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
(ctx as any).body = body;
|
|
48
|
+
return next ? next() : undefined;
|
|
49
|
+
} catch {
|
|
50
|
+
return errorJSON({ status: 'error', message: 'Malformed JSON payload' });
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
(mw as any).__schema = schema;
|
|
54
|
+
return mw;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Native Engine (n)
|
|
59
|
+
*/
|
|
60
|
+
export const native = (schema: any): Middleware => {
|
|
61
|
+
const props = schema.properties || {};
|
|
62
|
+
const keys = Object.keys(props);
|
|
63
|
+
const kLen = keys.length;
|
|
64
|
+
|
|
65
|
+
const mw: Middleware = async (ctx: any, next?: any) => {
|
|
66
|
+
try {
|
|
67
|
+
const isCtx = ctx instanceof Object && 'req' in ctx;
|
|
68
|
+
const body = isCtx ? await ctx.jsonBody() : await ctx.json();
|
|
69
|
+
|
|
70
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) {
|
|
71
|
+
return errorJSON({ status: 'error', message: 'Invalid JSON object payload' });
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
for (let i = 0; i < kLen; i++) {
|
|
75
|
+
const k = keys[i]!;
|
|
76
|
+
if (!Object.hasOwn(body, k) || typeof body[k] !== props[k]?.type) {
|
|
77
|
+
return errorJSON({
|
|
78
|
+
status: 'error',
|
|
79
|
+
code: 'TYPE_MISMATCH',
|
|
80
|
+
message: `Field '${k}' must be of type ${props[k]?.type}`,
|
|
81
|
+
field: k
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (isCtx) (ctx as any).body = body;
|
|
87
|
+
|
|
88
|
+
return next ? next() : undefined;
|
|
89
|
+
} catch {
|
|
90
|
+
return errorJSON({ status: 'error', message: 'Invalid JSON payload' });
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
(mw as any).__schema = schema;
|
|
94
|
+
return mw;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Zod Engine (z)
|
|
99
|
+
*/
|
|
100
|
+
export const zod = (schema: z.ZodSchema): Middleware => {
|
|
101
|
+
const mw: Middleware = async (ctx: any, next?: any) => {
|
|
102
|
+
try {
|
|
103
|
+
const isCtx = ctx instanceof Object && 'req' in ctx;
|
|
104
|
+
const body = isCtx ? await ctx.jsonBody() : await ctx.json();
|
|
105
|
+
|
|
106
|
+
const result = await schema.safeParseAsync(body);
|
|
107
|
+
|
|
108
|
+
if (!result.success) {
|
|
109
|
+
return errorJSON({
|
|
110
|
+
status: 'error',
|
|
111
|
+
code: 'ZOD_ERROR',
|
|
112
|
+
errors: result.error.flatten()
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
if (isCtx) (ctx as any).body = result.data;
|
|
117
|
+
|
|
118
|
+
return next ? next() : undefined;
|
|
119
|
+
} catch {
|
|
120
|
+
return errorJSON({ status: 'error', message: 'Invalid JSON payload' });
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
(mw as any).__schema = schema;
|
|
124
|
+
return mw;
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Smart Dispatcher (v)
|
|
129
|
+
*/
|
|
130
|
+
export const validate = (schema: any): Middleware => {
|
|
131
|
+
if (schema && '_def' in schema) return zod(schema);
|
|
132
|
+
if (schema && (schema.kind || schema.type || schema[Symbol.for('TypeBox.Kind')])) {
|
|
133
|
+
return typebox(schema);
|
|
134
|
+
}
|
|
135
|
+
return native(schema);
|
|
136
|
+
};
|
|
137
|
+
|
|
134
138
|
export { typebox as t, zod as z, native as n, validate as v };
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
export interface OpenAPIOptions {
|
|
2
|
+
title?: string;
|
|
3
|
+
version?: string;
|
|
4
|
+
description?: string;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
const zodToJsonSchema = (schema: any): Record<string, any> => {
|
|
8
|
+
if (!schema || !schema._def) return { type: 'object' };
|
|
9
|
+
const def = schema._def;
|
|
10
|
+
const typeName = def.typeName;
|
|
11
|
+
|
|
12
|
+
if (typeName === 'ZodObject') {
|
|
13
|
+
const shape = typeof def.shape === 'function' ? def.shape() : def.shape;
|
|
14
|
+
const properties: Record<string, any> = {};
|
|
15
|
+
const required: string[] = [];
|
|
16
|
+
for (const [k, v] of Object.entries(shape || {})) {
|
|
17
|
+
const child = v as any;
|
|
18
|
+
properties[k] = zodToJsonSchema(child);
|
|
19
|
+
if (child?._def?.typeName !== 'ZodOptional' && child?._def?.typeName !== 'ZodDefault') {
|
|
20
|
+
required.push(k);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return { type: 'object', properties, ...(required.length ? { required } : {}) };
|
|
24
|
+
}
|
|
25
|
+
if (typeName === 'ZodString') return { type: 'string' };
|
|
26
|
+
if (typeName === 'ZodNumber') return { type: 'number' };
|
|
27
|
+
if (typeName === 'ZodBoolean') return { type: 'boolean' };
|
|
28
|
+
if (typeName === 'ZodArray') return { type: 'array', items: zodToJsonSchema(def.type) };
|
|
29
|
+
if (typeName === 'ZodOptional' || typeName === 'ZodDefault') return zodToJsonSchema(def.innerType);
|
|
30
|
+
if (typeName === 'ZodEnum') return { type: 'string', enum: def.values };
|
|
31
|
+
return { type: 'object' };
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const extractSchema = (schema: any): Record<string, any> => {
|
|
35
|
+
if (!schema) return { type: 'object' };
|
|
36
|
+
if ('_def' in schema) return zodToJsonSchema(schema);
|
|
37
|
+
// TypeBox or plain JSON Schema
|
|
38
|
+
return JSON.parse(JSON.stringify(schema));
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {}) => {
|
|
42
|
+
const paths: Record<string, Record<string, any>> = {};
|
|
43
|
+
|
|
44
|
+
for (const route of routes) {
|
|
45
|
+
if (route.path === '/docs' || route.path === '/docs/json') continue;
|
|
46
|
+
|
|
47
|
+
const openApiPath = ('/' + route.path)
|
|
48
|
+
.replace(/\/+/g, '/')
|
|
49
|
+
.replace(/:([a-zA-Z0-9_]+)/g, '{$1}');
|
|
50
|
+
|
|
51
|
+
if (!paths[openApiPath]) paths[openApiPath] = {};
|
|
52
|
+
|
|
53
|
+
const method = route.method.toLowerCase();
|
|
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
|
+
let requestBody: any = undefined;
|
|
66
|
+
for (const h of route.handlers) {
|
|
67
|
+
if (h && (h as any).__schema) {
|
|
68
|
+
requestBody = {
|
|
69
|
+
required: true,
|
|
70
|
+
content: {
|
|
71
|
+
'application/json': {
|
|
72
|
+
schema: extractSchema((h as any).__schema)
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
break;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
paths[openApiPath][method] = {
|
|
81
|
+
summary: `${route.method} ${openApiPath}`,
|
|
82
|
+
...(params.length ? { parameters: params } : {}),
|
|
83
|
+
...(requestBody ? { requestBody } : {}),
|
|
84
|
+
responses: {
|
|
85
|
+
'200': { description: 'Success' }
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return {
|
|
91
|
+
openapi: '3.1.0',
|
|
92
|
+
info: {
|
|
93
|
+
title: options.title || 'BareJS API',
|
|
94
|
+
version: options.version || '1.0.0',
|
|
95
|
+
...(options.description ? { description: options.description } : {})
|
|
96
|
+
},
|
|
97
|
+
paths
|
|
98
|
+
};
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
export const renderDocsHTML = (specUrl: string, title: string = 'BareJS API Docs'): string => {
|
|
102
|
+
const safeTitle = title.replace(/[<>&"]/g, '');
|
|
103
|
+
const safeSpecUrl = JSON.stringify(specUrl);
|
|
104
|
+
return `<!doctype html>
|
|
105
|
+
<html>
|
|
106
|
+
<head>
|
|
107
|
+
<title>${safeTitle}</title>
|
|
108
|
+
<meta charset="utf-8" />
|
|
109
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
110
|
+
</head>
|
|
111
|
+
<body>
|
|
112
|
+
<script id="api-reference" data-url=${safeSpecUrl}></script>
|
|
113
|
+
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
|
|
114
|
+
</body>
|
|
115
|
+
</html>`;
|
|
116
|
+
};
|
package/src/utils/static.ts
CHANGED
|
@@ -1,26 +1,43 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
export const staticFile = (root: string = 'public') => {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
1
|
+
import { resolve, sep } from 'node:path';
|
|
2
|
+
|
|
3
|
+
export const staticFile = (root: string = 'public') => {
|
|
4
|
+
const rootDir = resolve(process.cwd(), root);
|
|
5
|
+
const rootPrefix = rootDir.endsWith(sep) ? rootDir : rootDir + sep;
|
|
6
|
+
|
|
7
|
+
return async (ctx: any, next: any) => {
|
|
8
|
+
const method = ctx.req.method;
|
|
9
|
+
if (method !== 'GET' && method !== 'HEAD') return next();
|
|
10
|
+
|
|
11
|
+
const rawUrl: string = ctx.req.url;
|
|
12
|
+
const pathStart = rawUrl.indexOf('/', 8);
|
|
13
|
+
const queryStart = pathStart === -1 ? -1 : rawUrl.indexOf('?', pathStart);
|
|
14
|
+
const rawPath = pathStart === -1
|
|
15
|
+
? ''
|
|
16
|
+
: (queryStart === -1 ? rawUrl.slice(pathStart) : rawUrl.slice(pathStart, queryStart));
|
|
17
|
+
|
|
18
|
+
let decodedPath: string;
|
|
19
|
+
try {
|
|
20
|
+
decodedPath = decodeURIComponent(rawPath);
|
|
21
|
+
} catch {
|
|
22
|
+
return ctx.status(400).send('Bad Request');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
if (decodedPath.includes('\0')) {
|
|
26
|
+
return ctx.status(400).send('Bad Request');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const relativePath = decodedPath.replace(/^\/+/, '');
|
|
30
|
+
const filePath = resolve(rootDir, relativePath);
|
|
31
|
+
|
|
32
|
+
if (filePath !== rootDir && !filePath.startsWith(rootPrefix)) {
|
|
33
|
+
return ctx.status(403).send('Forbidden');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const file = Bun.file(filePath);
|
|
37
|
+
if (await file.exists()) {
|
|
38
|
+
return new Response(file);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return next();
|
|
42
|
+
};
|
|
26
43
|
};
|