barejs 0.2.4 → 0.2.5
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 +62 -33
- package/dist/edge.js +75 -0
- package/dist/index.js +185 -178
- package/dist/node.js +184 -177
- package/dist/types/client/index.d.ts +57 -0
- package/dist/types/core/bare.d.ts +4 -1
- package/dist/types/core/context.d.ts +1 -0
- package/dist/types/core/router.d.ts +6 -0
- package/dist/types/edge.d.ts +98 -0
- package/dist/types/index.d.ts +3 -3
- package/dist/types/runtime/types.d.ts +15 -0
- package/dist/types/security/validators.d.ts +33 -0
- package/llms.txt +9 -6
- package/package.json +5 -1
- package/src/client/index.ts +294 -6
- package/src/core/bare.ts +15 -5
- package/src/core/context.ts +10 -3
- package/src/core/router.ts +2 -1
- package/src/edge.ts +492 -0
- package/src/index.ts +11 -3
- package/src/runtime/bun.ts +12 -0
- package/src/runtime/node.ts +21 -3
- package/src/runtime/types.ts +16 -0
- package/src/runtime/uws.ts +10 -2
- package/src/security/auth.ts +7 -5
- package/src/security/validators.ts +194 -37
package/src/edge.ts
ADDED
|
@@ -0,0 +1,492 @@
|
|
|
1
|
+
import { BareRouter } from './core/router';
|
|
2
|
+
import { Type, Type as t } from '@sinclair/typebox';
|
|
3
|
+
import { Z, Z as z, native, standard } from './security/validators';
|
|
4
|
+
import { bareClient, bareTreaty } from './client/index';
|
|
5
|
+
import { cors } from './security/cors';
|
|
6
|
+
import { securityHeaders } from './security/headers';
|
|
7
|
+
import { rateLimit } from './security/rateLimit';
|
|
8
|
+
import { timeout } from './security/timeout';
|
|
9
|
+
import { circuitBreaker } from './security/resilience';
|
|
10
|
+
import { redisStore } from './security/store';
|
|
11
|
+
import { healthcheck } from './utils/health';
|
|
12
|
+
import { logger } from './utils/logger';
|
|
13
|
+
import { generateOpenAPISpec, renderDocsHTML } from './utils/openapi';
|
|
14
|
+
|
|
15
|
+
export type EdgeNext = () => Promise<any> | any;
|
|
16
|
+
export type EdgeMiddleware<Env = Record<string, any>> = (ctx: EdgeContext<Env>, next: EdgeNext) => Promise<any> | any;
|
|
17
|
+
export type EdgeHandler<Env = Record<string, any>> = (ctx: EdgeContext<Env>) => Promise<any> | any;
|
|
18
|
+
|
|
19
|
+
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Pure Web-Standard request/response Context for Edge runtimes
|
|
23
|
+
* (Cloudflare Workers, Vercel Edge, Deno Deploy, Fastly Compute, Bun).
|
|
24
|
+
* Zero `node:*` imports.
|
|
25
|
+
*/
|
|
26
|
+
export class EdgeContext<Env = Record<string, any>> {
|
|
27
|
+
public req: Request;
|
|
28
|
+
public params: Record<string, string>;
|
|
29
|
+
public env: Env;
|
|
30
|
+
public executionCtx: any;
|
|
31
|
+
public store: Map<string, any> = new Map();
|
|
32
|
+
public body: any = undefined;
|
|
33
|
+
public user: any = undefined;
|
|
34
|
+
|
|
35
|
+
public _status: number = 200;
|
|
36
|
+
public _headers: Record<string, string> | undefined = undefined;
|
|
37
|
+
public _setCookies: string[] | undefined = undefined;
|
|
38
|
+
private _query: Record<string, string> | null = null;
|
|
39
|
+
private _cookies: Record<string, string> | null = null;
|
|
40
|
+
private _jsonCache: any = undefined;
|
|
41
|
+
private _jsonParsed: boolean = false;
|
|
42
|
+
private _requestId: string | null = null;
|
|
43
|
+
|
|
44
|
+
constructor(req: Request, params: Record<string, string> = {}, env: Env = {} as Env, executionCtx?: any) {
|
|
45
|
+
this.req = req;
|
|
46
|
+
this.params = params;
|
|
47
|
+
this.env = env;
|
|
48
|
+
this.executionCtx = executionCtx;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
public get requestId(): string {
|
|
52
|
+
if (!this._requestId) {
|
|
53
|
+
this._requestId = this.req.headers.get('x-request-id') || crypto.randomUUID();
|
|
54
|
+
}
|
|
55
|
+
return this._requestId;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
public get ip(): string {
|
|
59
|
+
return (
|
|
60
|
+
this.req.headers.get('cf-connecting-ip') ||
|
|
61
|
+
this.req.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ||
|
|
62
|
+
this.req.headers.get('x-real-ip') ||
|
|
63
|
+
'127.0.0.1'
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
public get query(): Record<string, string> {
|
|
68
|
+
if (this._query) return this._query;
|
|
69
|
+
const out: Record<string, string> = Object.create(null);
|
|
70
|
+
const qIdx = this.req.url.indexOf('?');
|
|
71
|
+
if (qIdx !== -1) {
|
|
72
|
+
const sp = new URLSearchParams(this.req.url.slice(qIdx + 1));
|
|
73
|
+
for (const [k, v] of sp) {
|
|
74
|
+
if (!FORBIDDEN_KEYS.has(k)) out[k] = v;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
this._query = out;
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
public get cookies(): Record<string, string> {
|
|
82
|
+
if (this._cookies) return this._cookies;
|
|
83
|
+
const out: Record<string, string> = Object.create(null);
|
|
84
|
+
const header = this.req.headers.get('cookie');
|
|
85
|
+
if (header) {
|
|
86
|
+
for (const pair of header.split(';')) {
|
|
87
|
+
const eq = pair.indexOf('=');
|
|
88
|
+
if (eq === -1) continue;
|
|
89
|
+
const k = pair.slice(0, eq).trim();
|
|
90
|
+
if (!k || FORBIDDEN_KEYS.has(k)) continue;
|
|
91
|
+
try {
|
|
92
|
+
out[k] = decodeURIComponent(pair.slice(eq + 1).trim());
|
|
93
|
+
} catch {
|
|
94
|
+
out[k] = pair.slice(eq + 1).trim();
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
this._cookies = out;
|
|
99
|
+
return out;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
public get(key: string): any {
|
|
103
|
+
return this.store.get(key);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
public set(key: string, value: any): this {
|
|
107
|
+
this.store.set(key, value);
|
|
108
|
+
return this;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
public status(code: number): this {
|
|
112
|
+
this._status = code;
|
|
113
|
+
return this;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
public setHeader(name: string, value: string): this {
|
|
117
|
+
if (!this._headers) this._headers = Object.create(null);
|
|
118
|
+
else if (Object.getPrototypeOf(this._headers) === Object.prototype) {
|
|
119
|
+
this._headers = { ...this._headers };
|
|
120
|
+
}
|
|
121
|
+
const safeName = (name.indexOf('\r') !== -1 || name.indexOf('\n') !== -1) ? name.replace(/[\r\n]+/g, '') : name;
|
|
122
|
+
const safeVal = (value.indexOf('\r') !== -1 || value.indexOf('\n') !== -1) ? value.replace(/[\r\n]+/g, '') : value;
|
|
123
|
+
this._headers![safeName.toLowerCase()] = safeVal;
|
|
124
|
+
return this;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
public appendHeader(name: string, value: string): this {
|
|
128
|
+
if (name.toLowerCase() === 'set-cookie') {
|
|
129
|
+
if (!this._setCookies) this._setCookies = [];
|
|
130
|
+
this._setCookies.push(value);
|
|
131
|
+
return this;
|
|
132
|
+
}
|
|
133
|
+
return this.setHeader(name, value);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
public setCookie(
|
|
137
|
+
name: string,
|
|
138
|
+
value: string,
|
|
139
|
+
opts: { maxAge?: number; path?: string; domain?: string; httpOnly?: boolean; secure?: boolean; sameSite?: 'Strict' | 'Lax' | 'None' } = {}
|
|
140
|
+
): this {
|
|
141
|
+
const cleanName = name.replace(/[\r\n;= ]+/g, '');
|
|
142
|
+
const parts = [`${cleanName}=${encodeURIComponent(value)}`];
|
|
143
|
+
parts.push(`Path=${(opts.path ?? '/').replace(/[\r\n;]+/g, '')}`);
|
|
144
|
+
if (opts.maxAge !== undefined) parts.push(`Max-Age=${Math.floor(opts.maxAge)}`);
|
|
145
|
+
if (opts.domain) parts.push(`Domain=${opts.domain.replace(/[\r\n;]+/g, '')}`);
|
|
146
|
+
if (opts.httpOnly !== false) parts.push('HttpOnly');
|
|
147
|
+
if (opts.secure) parts.push('Secure');
|
|
148
|
+
parts.push(`SameSite=${opts.sameSite ?? 'Lax'}`);
|
|
149
|
+
return this.appendHeader('Set-Cookie', parts.join('; '));
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
public deleteCookie(name: string, path: string = '/'): this {
|
|
153
|
+
return this.setCookie(name, '', { maxAge: 0, path });
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
public async jsonBody(maxBytes: number = 1024 * 1024): Promise<any> {
|
|
157
|
+
if (this._jsonParsed) return this._jsonCache;
|
|
158
|
+
const raw = await this.req.text();
|
|
159
|
+
if (new TextEncoder().encode(raw).byteLength > maxBytes) {
|
|
160
|
+
const err: any = new Error('Payload Too Large');
|
|
161
|
+
err.status = 413;
|
|
162
|
+
throw err;
|
|
163
|
+
}
|
|
164
|
+
try {
|
|
165
|
+
this._jsonCache = raw ? JSON.parse(raw) : null;
|
|
166
|
+
} catch {
|
|
167
|
+
const err: any = new Error('Malformed JSON payload');
|
|
168
|
+
err.status = 400;
|
|
169
|
+
throw err;
|
|
170
|
+
}
|
|
171
|
+
this._jsonParsed = true;
|
|
172
|
+
return this._jsonCache;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
public async textBody(): Promise<string> {
|
|
176
|
+
return this.req.text();
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
private buildHeaders(defaultContentType: string): Headers {
|
|
180
|
+
const h = new Headers();
|
|
181
|
+
if (this._headers) {
|
|
182
|
+
for (const k in this._headers) {
|
|
183
|
+
h.set(k, this._headers[k]!);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
if (this._setCookies) {
|
|
187
|
+
for (let i = 0; i < this._setCookies.length; i++) {
|
|
188
|
+
h.append('set-cookie', this._setCookies[i]!);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (!h.has('content-type')) h.set('content-type', defaultContentType);
|
|
192
|
+
return h;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
public json(data: any, status?: number): Response {
|
|
196
|
+
return new Response(JSON.stringify(data), {
|
|
197
|
+
status: status ?? this._status,
|
|
198
|
+
headers: this.buildHeaders('application/json; charset=utf-8')
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
public text(data: string, status?: number): Response {
|
|
203
|
+
return new Response(data, {
|
|
204
|
+
status: status ?? this._status,
|
|
205
|
+
headers: this.buildHeaders('text/plain; charset=utf-8')
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
public html(data: string, status?: number): Response {
|
|
210
|
+
return new Response(data, {
|
|
211
|
+
status: status ?? this._status,
|
|
212
|
+
headers: this.buildHeaders('text/html; charset=utf-8')
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
public send(msg: string, extra?: Record<string, any>): Response {
|
|
217
|
+
return this.json({ status: this._status, msg, ...extra });
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
public redirect(url: string, status: number = 302): Response {
|
|
221
|
+
const h = new Headers();
|
|
222
|
+
if (this._headers) {
|
|
223
|
+
for (const k in this._headers) h.set(k, this._headers[k]!);
|
|
224
|
+
}
|
|
225
|
+
h.set('location', url.replace(/[\r\n]+/g, ''));
|
|
226
|
+
return new Response(null, { status, headers: h });
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
interface EdgeRouteEntry<Env> {
|
|
231
|
+
middlewares: EdgeMiddleware<Env>[];
|
|
232
|
+
handler: EdgeHandler<Env>;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
class EdgeRadixNode<Env> {
|
|
236
|
+
children: Record<string, EdgeRadixNode<Env>> = Object.create(null);
|
|
237
|
+
paramNode: EdgeRadixNode<Env> | null = null;
|
|
238
|
+
wildcardNode: EdgeRadixNode<Env> | null = null;
|
|
239
|
+
entry: EdgeRouteEntry<Env> | null = null;
|
|
240
|
+
paramNames: string[] = [];
|
|
241
|
+
|
|
242
|
+
insert(path: string, entry: EdgeRouteEntry<Env>): void {
|
|
243
|
+
let node: EdgeRadixNode<Env> = this;
|
|
244
|
+
const parts = path.split('/').filter(Boolean);
|
|
245
|
+
const paramNames: string[] = [];
|
|
246
|
+
for (const part of parts) {
|
|
247
|
+
if (part === '*') {
|
|
248
|
+
if (!node.wildcardNode) node.wildcardNode = new EdgeRadixNode<Env>();
|
|
249
|
+
node = node.wildcardNode;
|
|
250
|
+
break;
|
|
251
|
+
} else if (part.startsWith(':')) {
|
|
252
|
+
if (!node.paramNode) node.paramNode = new EdgeRadixNode<Env>();
|
|
253
|
+
paramNames.push(part.slice(1));
|
|
254
|
+
node = node.paramNode;
|
|
255
|
+
} else {
|
|
256
|
+
if (!node.children[part]) node.children[part] = new EdgeRadixNode<Env>();
|
|
257
|
+
node = node.children[part]!;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
node.entry = entry;
|
|
261
|
+
node.paramNames = paramNames;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
search(pathname: string): { entry: EdgeRouteEntry<Env>; params: Record<string, string> } | null {
|
|
265
|
+
const parts = pathname.split('/').filter(Boolean);
|
|
266
|
+
const match = (
|
|
267
|
+
node: EdgeRadixNode<Env>,
|
|
268
|
+
idx: number,
|
|
269
|
+
vals: string[]
|
|
270
|
+
): { entry: EdgeRouteEntry<Env>; params: Record<string, string> } | null => {
|
|
271
|
+
if (idx === parts.length) {
|
|
272
|
+
if (!node.entry) return null;
|
|
273
|
+
const params: Record<string, string> = Object.create(null);
|
|
274
|
+
for (let i = 0; i < node.paramNames.length; i++) {
|
|
275
|
+
const name = node.paramNames[i]!;
|
|
276
|
+
if (!FORBIDDEN_KEYS.has(name)) params[name] = vals[i]!;
|
|
277
|
+
}
|
|
278
|
+
return { entry: node.entry, params };
|
|
279
|
+
}
|
|
280
|
+
const seg = parts[idx]!;
|
|
281
|
+
const child = node.children[seg];
|
|
282
|
+
if (child) {
|
|
283
|
+
const res = match(child, idx + 1, vals);
|
|
284
|
+
if (res) return res;
|
|
285
|
+
}
|
|
286
|
+
if (node.paramNode) {
|
|
287
|
+
vals.push(seg);
|
|
288
|
+
const res = match(node.paramNode, idx + 1, vals);
|
|
289
|
+
if (res) return res;
|
|
290
|
+
vals.pop();
|
|
291
|
+
}
|
|
292
|
+
if (node.wildcardNode && node.wildcardNode.entry) {
|
|
293
|
+
const params: Record<string, string> = Object.create(null);
|
|
294
|
+
for (let i = 0; i < node.wildcardNode.paramNames.length; i++) {
|
|
295
|
+
const name = node.wildcardNode.paramNames[i]!;
|
|
296
|
+
if (!FORBIDDEN_KEYS.has(name)) params[name] = vals[i]!;
|
|
297
|
+
}
|
|
298
|
+
params['*'] = parts.slice(idx).join('/');
|
|
299
|
+
return { entry: node.wildcardNode.entry, params };
|
|
300
|
+
}
|
|
301
|
+
return null;
|
|
302
|
+
};
|
|
303
|
+
return match(this, 0, []);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Zero-Node Edge Web Framework (`barejs/edge`).
|
|
309
|
+
* Drop-in `export default app` for Cloudflare Workers, Vercel Edge, Deno Deploy, and Bun.
|
|
310
|
+
*/
|
|
311
|
+
export class BareEdge<Env = Record<string, any>> {
|
|
312
|
+
private staticRoutes: Map<string, EdgeRouteEntry<Env>> = new Map();
|
|
313
|
+
private dynamicTrees: Map<string, EdgeRadixNode<Env>> = new Map();
|
|
314
|
+
private middlewares: EdgeMiddleware<Env>[] = [];
|
|
315
|
+
private requestHooks: Array<(ctx: EdgeContext<Env>) => Promise<void> | void> = [];
|
|
316
|
+
private responseHooks: Array<(ctx: EdgeContext<Env>, res: Response) => Promise<void> | void> = [];
|
|
317
|
+
private errorHandler: ((err: any, ctx: EdgeContext<Env>) => Response | Promise<Response>) | null = null;
|
|
318
|
+
|
|
319
|
+
public use(mw: EdgeMiddleware<Env>): this {
|
|
320
|
+
this.middlewares.push(mw);
|
|
321
|
+
return this;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
public onRequest(fn: (ctx: EdgeContext<Env>) => Promise<void> | void): this {
|
|
325
|
+
this.requestHooks.push(fn);
|
|
326
|
+
return this;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
public onResponse(fn: (ctx: EdgeContext<Env>, res: Response) => Promise<void> | void): this {
|
|
330
|
+
this.responseHooks.push(fn);
|
|
331
|
+
return this;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
public onError(fn: (err: any, ctx: EdgeContext<Env>) => Response | Promise<Response>): this {
|
|
335
|
+
this.errorHandler = fn;
|
|
336
|
+
return this;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
private add(method: string, path: string, ...fns: EdgeMiddleware<Env>[]): this {
|
|
340
|
+
if (fns.length === 0) return this;
|
|
341
|
+
const handler = fns[fns.length - 1] as EdgeHandler<Env>;
|
|
342
|
+
const middlewares = fns.slice(0, -1);
|
|
343
|
+
const cleanPath = path.startsWith('/') ? path : `/${path}`;
|
|
344
|
+
const entry: EdgeRouteEntry<Env> = { middlewares, handler };
|
|
345
|
+
|
|
346
|
+
if (!cleanPath.includes(':') && !cleanPath.includes('*')) {
|
|
347
|
+
this.staticRoutes.set(`${method}:${cleanPath}`, entry);
|
|
348
|
+
} else {
|
|
349
|
+
let tree = this.dynamicTrees.get(method);
|
|
350
|
+
if (!tree) {
|
|
351
|
+
tree = new EdgeRadixNode<Env>();
|
|
352
|
+
this.dynamicTrees.set(method, tree);
|
|
353
|
+
}
|
|
354
|
+
tree.insert(cleanPath, entry);
|
|
355
|
+
}
|
|
356
|
+
return this;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
public get(path: string, ...fns: EdgeMiddleware<Env>[]): this { return this.add('GET', path, ...fns); }
|
|
360
|
+
public post(path: string, ...fns: EdgeMiddleware<Env>[]): this { return this.add('POST', path, ...fns); }
|
|
361
|
+
public put(path: string, ...fns: EdgeMiddleware<Env>[]): this { return this.add('PUT', path, ...fns); }
|
|
362
|
+
public patch(path: string, ...fns: EdgeMiddleware<Env>[]): this { return this.add('PATCH', path, ...fns); }
|
|
363
|
+
public delete(path: string, ...fns: EdgeMiddleware<Env>[]): this { return this.add('DELETE', path, ...fns); }
|
|
364
|
+
public options(path: string, ...fns: EdgeMiddleware<Env>[]): this { return this.add('OPTIONS', path, ...fns); }
|
|
365
|
+
public head(path: string, ...fns: EdgeMiddleware<Env>[]): this { return this.add('HEAD', path, ...fns); }
|
|
366
|
+
public all(path: string, ...fns: EdgeMiddleware<Env>[]): this {
|
|
367
|
+
for (const m of ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD']) {
|
|
368
|
+
this.add(m, path, ...fns);
|
|
369
|
+
}
|
|
370
|
+
return this;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
private normalizeResponse(ctx: EdgeContext<Env>, out: any): Response {
|
|
374
|
+
if (out instanceof Response) return out;
|
|
375
|
+
if (typeof out === 'string') return ctx.text(out);
|
|
376
|
+
if (out === null || out === undefined) return new Response(null, { status: 204 });
|
|
377
|
+
return ctx.json(out);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
public fetch = async (req: Request, env?: Env, executionCtx?: any): Promise<Response> => {
|
|
381
|
+
const url = req.url;
|
|
382
|
+
const pathStart = url.indexOf('/', 8);
|
|
383
|
+
const qStart = pathStart === -1 ? -1 : url.indexOf('?', pathStart);
|
|
384
|
+
const pathname = pathStart === -1 ? '/' : (qStart === -1 ? url.slice(pathStart) : url.slice(pathStart, qStart));
|
|
385
|
+
const method = req.method;
|
|
386
|
+
|
|
387
|
+
let entry: EdgeRouteEntry<Env> | undefined = this.staticRoutes.get(`${method}:${pathname}`);
|
|
388
|
+
let params: Record<string, string> = {};
|
|
389
|
+
|
|
390
|
+
if (!entry) {
|
|
391
|
+
const tree = this.dynamicTrees.get(method);
|
|
392
|
+
if (tree) {
|
|
393
|
+
const matched = tree.search(pathname);
|
|
394
|
+
if (matched) {
|
|
395
|
+
entry = matched.entry;
|
|
396
|
+
params = matched.params;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
const ctx = new EdgeContext<Env>(req, params, env ?? ({} as Env), executionCtx);
|
|
402
|
+
|
|
403
|
+
try {
|
|
404
|
+
for (let i = 0; i < this.requestHooks.length; i++) {
|
|
405
|
+
await this.requestHooks[i]!(ctx);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
const chain: EdgeMiddleware<Env>[] = entry
|
|
409
|
+
? [...this.middlewares, ...entry.middlewares, entry.handler]
|
|
410
|
+
: [...this.middlewares, () => new Response(JSON.stringify({ status: 404, message: 'Not Found' }), {
|
|
411
|
+
status: 404,
|
|
412
|
+
headers: { 'content-type': 'application/json; charset=utf-8' }
|
|
413
|
+
})];
|
|
414
|
+
|
|
415
|
+
let idx = -1;
|
|
416
|
+
const dispatch = async (i: number): Promise<any> => {
|
|
417
|
+
if (i <= idx) throw new Error('next() called multiple times');
|
|
418
|
+
idx = i;
|
|
419
|
+
const fn = chain[i];
|
|
420
|
+
if (!fn) return undefined;
|
|
421
|
+
return fn(ctx, () => dispatch(i + 1));
|
|
422
|
+
};
|
|
423
|
+
|
|
424
|
+
const raw = await dispatch(0);
|
|
425
|
+
const res = this.normalizeResponse(ctx, raw);
|
|
426
|
+
|
|
427
|
+
for (let i = 0; i < this.responseHooks.length; i++) {
|
|
428
|
+
await this.responseHooks[i]!(ctx, res);
|
|
429
|
+
}
|
|
430
|
+
return res;
|
|
431
|
+
} catch (err: any) {
|
|
432
|
+
if (this.errorHandler) {
|
|
433
|
+
return this.errorHandler(err, ctx);
|
|
434
|
+
}
|
|
435
|
+
const status = err?.status >= 400 && err?.status < 600 ? err.status : 500;
|
|
436
|
+
return new Response(
|
|
437
|
+
JSON.stringify({ status, message: status < 500 ? (err?.message || 'Bad Request') : 'Internal Server Error' }),
|
|
438
|
+
{ status, headers: { 'content-type': 'application/json; charset=utf-8' } }
|
|
439
|
+
);
|
|
440
|
+
}
|
|
441
|
+
};
|
|
442
|
+
|
|
443
|
+
public request(path: string, init?: RequestInit, env?: Env): Promise<Response> {
|
|
444
|
+
const url = path.startsWith('http://') || path.startsWith('https://')
|
|
445
|
+
? path
|
|
446
|
+
: `http://localhost${path.startsWith('/') ? path : `/${path}`}`;
|
|
447
|
+
return this.fetch(new Request(url, init), env);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
export function createSingleflight() {
|
|
452
|
+
const inflight = new Map<string, Promise<any>>();
|
|
453
|
+
return {
|
|
454
|
+
do<T>(key: string, fn: () => Promise<T>): Promise<T> {
|
|
455
|
+
const existing = inflight.get(key);
|
|
456
|
+
if (existing) return existing;
|
|
457
|
+
const p = Promise.resolve()
|
|
458
|
+
.then(fn)
|
|
459
|
+
.finally(() => {
|
|
460
|
+
inflight.delete(key);
|
|
461
|
+
});
|
|
462
|
+
inflight.set(key, p);
|
|
463
|
+
return p;
|
|
464
|
+
},
|
|
465
|
+
size(): number {
|
|
466
|
+
return inflight.size;
|
|
467
|
+
}
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
export {
|
|
472
|
+
BareEdge as BareJS,
|
|
473
|
+
BareRouter,
|
|
474
|
+
Type,
|
|
475
|
+
t,
|
|
476
|
+
Z,
|
|
477
|
+
z,
|
|
478
|
+
native,
|
|
479
|
+
standard,
|
|
480
|
+
bareClient,
|
|
481
|
+
bareTreaty,
|
|
482
|
+
cors,
|
|
483
|
+
securityHeaders,
|
|
484
|
+
rateLimit,
|
|
485
|
+
timeout,
|
|
486
|
+
circuitBreaker,
|
|
487
|
+
redisStore,
|
|
488
|
+
healthcheck,
|
|
489
|
+
logger,
|
|
490
|
+
generateOpenAPISpec,
|
|
491
|
+
renderDocsHTML
|
|
492
|
+
};
|
package/src/index.ts
CHANGED
|
@@ -37,7 +37,7 @@ import { Type } from "@sinclair/typebox";
|
|
|
37
37
|
export { Type, Type as T, Type as TypeBox };
|
|
38
38
|
|
|
39
39
|
// --- 4. The Validation Suite (Engines - สำหรับเป็น Middleware) ---
|
|
40
|
-
import { typebox, zod, native, validate, schemaValidator, createResponseFilter, Z, type RouteSchemas, type RouteDetail } from './security/validators';
|
|
40
|
+
import { typebox, zod, native, standard, validate, schemaValidator, createResponseFilter, Z, type RouteSchemas, type RouteDetail, type StandardSchemaV1 } from './security/validators';
|
|
41
41
|
export {
|
|
42
42
|
// TypeBox Engine
|
|
43
43
|
typebox,
|
|
@@ -50,6 +50,8 @@ export {
|
|
|
50
50
|
// Native Engine
|
|
51
51
|
native,
|
|
52
52
|
native as n,
|
|
53
|
+
// Standard Schema v1 Engine (Valibot, ArkType, Zod 4, Effect, etc.)
|
|
54
|
+
standard,
|
|
53
55
|
// Auto-Detect Engine
|
|
54
56
|
validate,
|
|
55
57
|
validate as v,
|
|
@@ -57,7 +59,8 @@ export {
|
|
|
57
59
|
schemaValidator,
|
|
58
60
|
createResponseFilter,
|
|
59
61
|
type RouteSchemas,
|
|
60
|
-
type RouteDetail
|
|
62
|
+
type RouteDetail,
|
|
63
|
+
type StandardSchemaV1
|
|
61
64
|
};
|
|
62
65
|
|
|
63
66
|
// --- 5. Middlewares & Utilities ---
|
|
@@ -89,10 +92,15 @@ export { bareAuth, createToken, basicAuth, hasRole, revokeToken, isTokenRevoked,
|
|
|
89
92
|
// --- 7. Hashing ---
|
|
90
93
|
export { Hash as Password, Hash } from './security/hash';
|
|
91
94
|
|
|
92
|
-
// --- 8. Type-Safe RPC Client ---
|
|
95
|
+
// --- 8. Type-Safe RPC Client & Treaty ---
|
|
93
96
|
export {
|
|
94
97
|
bareClient,
|
|
98
|
+
bareTreaty,
|
|
95
99
|
type BareClient,
|
|
100
|
+
type BareSafeClient,
|
|
101
|
+
type BareTreatyNode,
|
|
102
|
+
type BareClientResult,
|
|
103
|
+
type BareWsClient,
|
|
96
104
|
type BareClientOptions,
|
|
97
105
|
type ClientRequestOptions,
|
|
98
106
|
type RouteEndpoint,
|
package/src/runtime/bun.ts
CHANGED
|
@@ -11,6 +11,16 @@ export const bunDriver: RuntimeDriver = {
|
|
|
11
11
|
serve(opts: ServeOptions): ServerHandle {
|
|
12
12
|
const wsCfg = opts.ws;
|
|
13
13
|
const routes = opts.routes;
|
|
14
|
+
const toBunPem = (v?: string | Uint8Array) =>
|
|
15
|
+
typeof v === 'string' && !v.includes('-----BEGIN') ? Bun.file(v) : v;
|
|
16
|
+
const tls = opts.tls
|
|
17
|
+
? {
|
|
18
|
+
key: toBunPem(opts.tls.keyFileName ?? opts.tls.key),
|
|
19
|
+
cert: toBunPem(opts.tls.certFileName ?? opts.tls.cert),
|
|
20
|
+
...(opts.tls.passphrase ? { passphrase: opts.tls.passphrase } : {}),
|
|
21
|
+
...(opts.tls.ca ? { ca: toBunPem(opts.tls.ca) } : {})
|
|
22
|
+
}
|
|
23
|
+
: undefined;
|
|
14
24
|
let server: any;
|
|
15
25
|
try {
|
|
16
26
|
server = wsCfg
|
|
@@ -20,6 +30,7 @@ export const bunDriver: RuntimeDriver = {
|
|
|
20
30
|
reusePort: opts.reusePort,
|
|
21
31
|
maxRequestBodySize: opts.maxRequestBodySize,
|
|
22
32
|
...(routes ? { routes } : {}),
|
|
33
|
+
...(tls ? { tls } : {}),
|
|
23
34
|
fetch(req: Request, srv: any) {
|
|
24
35
|
if (req.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
|
25
36
|
const matched = matchWsRoute(wsCfg.routes, req.url);
|
|
@@ -42,6 +53,7 @@ export const bunDriver: RuntimeDriver = {
|
|
|
42
53
|
reusePort: opts.reusePort,
|
|
43
54
|
maxRequestBodySize: opts.maxRequestBodySize,
|
|
44
55
|
...(routes ? { routes } : {}),
|
|
56
|
+
...(tls ? { tls } : {}),
|
|
45
57
|
fetch(req: Request, srv: any) {
|
|
46
58
|
return opts.fetch(req, srv?.requestIP?.(req)?.address);
|
|
47
59
|
}
|
package/src/runtime/node.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createHash, randomBytes, scrypt, timingSafeEqual } from 'node:crypto';
|
|
2
2
|
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
|
|
3
|
-
import {
|
|
3
|
+
import { createServer as createHttpsServer } from 'node:https';
|
|
4
|
+
import { createReadStream, readFileSync } from 'node:fs';
|
|
4
5
|
import { extname } from 'node:path';
|
|
5
6
|
import { Readable } from 'node:stream';
|
|
6
7
|
import * as zlib from 'node:zlib';
|
|
@@ -206,7 +207,7 @@ export const nodeDriver: RuntimeDriver = {
|
|
|
206
207
|
throw new Error("[BareJS] engine: 'uws' was requested, but 'uWebSockets.js' is not installed.");
|
|
207
208
|
}
|
|
208
209
|
}
|
|
209
|
-
const
|
|
210
|
+
const reqHandler = async (req: IncomingMessage, res: ServerResponse) => {
|
|
210
211
|
const parsed = toWebRequest(req, opts.maxRequestBodySize);
|
|
211
212
|
if (parsed.errorStatus === 413 || !parsed.request) {
|
|
212
213
|
res.writeHead(413, { 'content-type': 'application/json' });
|
|
@@ -228,7 +229,24 @@ export const nodeDriver: RuntimeDriver = {
|
|
|
228
229
|
res.end();
|
|
229
230
|
}
|
|
230
231
|
}
|
|
231
|
-
}
|
|
232
|
+
};
|
|
233
|
+
const toNodePem = (v?: string | Uint8Array): string | Buffer | undefined =>
|
|
234
|
+
v === undefined
|
|
235
|
+
? undefined
|
|
236
|
+
: typeof v === 'string'
|
|
237
|
+
? (v.includes('-----BEGIN') ? v : readFileSync(v))
|
|
238
|
+
: Buffer.from(v);
|
|
239
|
+
const server = opts.tls
|
|
240
|
+
? createHttpsServer(
|
|
241
|
+
{
|
|
242
|
+
key: toNodePem(opts.tls.keyFileName ?? opts.tls.key),
|
|
243
|
+
cert: toNodePem(opts.tls.certFileName ?? opts.tls.cert),
|
|
244
|
+
...(opts.tls.passphrase ? { passphrase: opts.tls.passphrase } : {}),
|
|
245
|
+
...(opts.tls.ca ? { ca: toNodePem(opts.tls.ca) } : {})
|
|
246
|
+
},
|
|
247
|
+
reqHandler
|
|
248
|
+
)
|
|
249
|
+
: createServer(reqHandler);
|
|
232
250
|
|
|
233
251
|
if (opts.ws) {
|
|
234
252
|
const wsCfg = opts.ws;
|
package/src/runtime/types.ts
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
import type { WebSocketRouteHandler } from '../core/ws-match';
|
|
2
2
|
|
|
3
|
+
export interface ServeTlsOptions {
|
|
4
|
+
/** Path to TLS private key file, or PEM string/bytes (Bun & Node https) */
|
|
5
|
+
key?: string | Uint8Array;
|
|
6
|
+
/** Path to TLS certificate file, or PEM string/bytes (Bun & Node https) */
|
|
7
|
+
cert?: string | Uint8Array;
|
|
8
|
+
/** Optional key file path alias (uWebSockets.js parity) */
|
|
9
|
+
keyFileName?: string;
|
|
10
|
+
/** Optional cert file path alias (uWebSockets.js parity) */
|
|
11
|
+
certFileName?: string;
|
|
12
|
+
/** Optional passphrase for encrypted private key */
|
|
13
|
+
passphrase?: string;
|
|
14
|
+
/** Optional CA certificate file path or PEM bytes */
|
|
15
|
+
ca?: string | Uint8Array;
|
|
16
|
+
}
|
|
17
|
+
|
|
3
18
|
export interface ServeOptions {
|
|
4
19
|
port: number;
|
|
5
20
|
hostname: string;
|
|
@@ -8,6 +23,7 @@ export interface ServeOptions {
|
|
|
8
23
|
fetch: (req: Request, peerIp?: string) => Response | Promise<Response>;
|
|
9
24
|
routes?: Record<string, any>;
|
|
10
25
|
engine?: 'auto' | 'http' | 'uws';
|
|
26
|
+
tls?: ServeTlsOptions;
|
|
11
27
|
uwsRoutes?: any[];
|
|
12
28
|
ws?: {
|
|
13
29
|
routes: Map<string, WebSocketRouteHandler>;
|
package/src/runtime/uws.ts
CHANGED
|
@@ -348,7 +348,15 @@ export function serveUws(
|
|
|
348
348
|
opts: ServeOptions & { uwsRoutes?: UwsRouteEntry[] },
|
|
349
349
|
uwsMod: any
|
|
350
350
|
): ServerHandle {
|
|
351
|
-
const
|
|
351
|
+
const isTls = Boolean(opts.tls);
|
|
352
|
+
const app = opts.tls
|
|
353
|
+
? uwsMod.SSLApp({
|
|
354
|
+
key_file_name: opts.tls.keyFileName ?? (typeof opts.tls.key === 'string' ? opts.tls.key : undefined),
|
|
355
|
+
cert_file_name: opts.tls.certFileName ?? (typeof opts.tls.cert === 'string' ? opts.tls.cert : undefined),
|
|
356
|
+
...(opts.tls.passphrase ? { passphrase: opts.tls.passphrase } : {}),
|
|
357
|
+
...(opts.tls.ca && typeof opts.tls.ca === 'string' ? { ca_file_name: opts.tls.ca } : {})
|
|
358
|
+
})
|
|
359
|
+
: uwsMod.App();
|
|
352
360
|
const isProd = process.env.NODE_ENV === 'production';
|
|
353
361
|
const pool: UwsContext[] = [];
|
|
354
362
|
const maxPool = 4096;
|
|
@@ -477,7 +485,7 @@ export function serveUws(
|
|
|
477
485
|
if (k === 'host') host = v;
|
|
478
486
|
headers.append(k, v);
|
|
479
487
|
});
|
|
480
|
-
const fullUrl =
|
|
488
|
+
const fullUrl = `${isTls ? 'https' : 'http'}://${host}${urlPath}${queryStr ? `?${queryStr}` : ''}`;
|
|
481
489
|
let peerIp = '127.0.0.1';
|
|
482
490
|
try {
|
|
483
491
|
peerIp = Buffer.from(res.getRemoteAddressAsText()).toString() || '127.0.0.1';
|