barejs 0.1.49 → 0.1.51
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 +257 -98
- package/dist/index.js +157 -94
- package/dist/types/client/index.d.ts +24 -22
- package/dist/types/core/bare.d.ts +83 -3
- package/dist/types/core/context.d.ts +47 -1
- package/dist/types/core/radix.d.ts +1 -0
- package/dist/types/core/router.d.ts +21 -10
- package/dist/types/index.d.ts +16 -8
- package/dist/types/security/auth.d.ts +10 -1
- package/dist/types/security/cors.d.ts +7 -3
- package/dist/types/security/csrf.d.ts +12 -0
- package/dist/types/security/idempotency.d.ts +22 -0
- package/dist/types/security/resilience.d.ts +17 -0
- package/dist/types/security/timeout.d.ts +6 -0
- package/dist/types/security/validators.d.ts +18 -0
- package/dist/types/utils/compress.d.ts +12 -0
- package/dist/types/utils/health.d.ts +17 -0
- package/dist/types/utils/logger.d.ts +22 -0
- package/dist/types/utils/openapi.d.ts +23 -1
- package/dist/types/utils/static.d.ts +5 -1
- package/llms.txt +138 -0
- package/package.json +3 -1
- package/src/client/index.ts +61 -18
- package/src/core/bare.ts +409 -49
- package/src/core/context.ts +266 -32
- package/src/core/radix.ts +37 -3
- package/src/core/router.ts +43 -16
- package/src/index.ts +25 -9
- package/src/security/auth.ts +68 -11
- package/src/security/cors.ts +85 -31
- package/src/security/csrf.ts +84 -0
- package/src/security/hash.ts +8 -2
- package/src/security/headers.ts +12 -3
- package/src/security/idempotency.ts +118 -0
- package/src/security/rateLimit.ts +1 -6
- package/src/security/resilience.ts +91 -0
- package/src/security/timeout.ts +32 -0
- package/src/security/validators.ts +201 -5
- package/src/utils/compress.ts +49 -0
- package/src/utils/health.ts +65 -0
- package/src/utils/logger.ts +66 -0
- package/src/utils/openapi.ts +59 -14
- package/src/utils/static.ts +71 -5
package/src/core/bare.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BareRouter } from './router';
|
|
1
|
+
import { BareRouter, type InferSchema } from './router';
|
|
2
2
|
import { RadixNode } from './radix';
|
|
3
3
|
import { Context } from './context';
|
|
4
4
|
import { Type as typebox, Type as t } from '@sinclair/typebox';
|
|
@@ -6,6 +6,15 @@ import { join } from "node:path";
|
|
|
6
6
|
import { readFileSync } from "node:fs";
|
|
7
7
|
import { bootstrapConfig } from "./loader";
|
|
8
8
|
import { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from "../utils/openapi";
|
|
9
|
+
import type { RouteSchemas } from "../security/validators";
|
|
10
|
+
import type { RouteSchema } from "../client/index";
|
|
11
|
+
|
|
12
|
+
export interface CronOptions {
|
|
13
|
+
/** Execute the cron job immediately upon registration (default: false) */
|
|
14
|
+
runOnStart?: boolean;
|
|
15
|
+
/** Optional error handler when the cron callback throws or rejects */
|
|
16
|
+
onError?: (err: any) => void;
|
|
17
|
+
}
|
|
9
18
|
|
|
10
19
|
export interface WebSocketRouteHandler {
|
|
11
20
|
open?: (ws: any) => void;
|
|
@@ -19,7 +28,40 @@ export interface NotFoundResponse {
|
|
|
19
28
|
message: string;
|
|
20
29
|
[key: string]: any;
|
|
21
30
|
}
|
|
22
|
-
|
|
31
|
+
|
|
32
|
+
type TypedRouteHandler<Derived, S extends RouteSchemas, Res> = (
|
|
33
|
+
ctx: Context & Derived & {
|
|
34
|
+
body: S extends { body: infer B } ? InferSchema<B> : any;
|
|
35
|
+
query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, string>;
|
|
36
|
+
params: S extends { params: infer Pa } ? InferSchema<Pa> : Record<string, any>;
|
|
37
|
+
}
|
|
38
|
+
) => Res | Promise<Res>;
|
|
39
|
+
|
|
40
|
+
type AddRoute<Derived extends Record<string, any>, Routes extends RouteSchema, M extends string> = {
|
|
41
|
+
<P extends string, S extends RouteSchemas, Res = S extends { response: infer R } ? InferSchema<R> : any>(
|
|
42
|
+
path: P,
|
|
43
|
+
schemas: S,
|
|
44
|
+
handler: TypedRouteHandler<Derived, S, Res>
|
|
45
|
+
): BareJS<Derived, Routes & Record<`${M} ${P}`, {
|
|
46
|
+
method: M;
|
|
47
|
+
path: P;
|
|
48
|
+
params: S extends { params: infer Pa } ? InferSchema<Pa> : Record<string, any>;
|
|
49
|
+
query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, any>;
|
|
50
|
+
headers: S extends { headers: infer H } ? InferSchema<H> : Record<string, string>;
|
|
51
|
+
body: S extends { body: infer B } ? InferSchema<B> : any;
|
|
52
|
+
response: S extends { response: infer R } ? InferSchema<R> : Awaited<Res>;
|
|
53
|
+
}>>;
|
|
54
|
+
<P extends string, Res = any>(
|
|
55
|
+
path: P,
|
|
56
|
+
...handlers: any[]
|
|
57
|
+
): BareJS<Derived, Routes & Record<`${M} ${P}`, { method: M; path: P; response: Awaited<Res> }>>;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
export class BareJS<
|
|
61
|
+
Derived extends Record<string, any> = {},
|
|
62
|
+
Routes extends RouteSchema = {}
|
|
63
|
+
> extends BareRouter<Routes> {
|
|
64
|
+
declare readonly __routes: Routes;
|
|
23
65
|
private tree = new RadixNode();
|
|
24
66
|
private pool: Context[] = [];
|
|
25
67
|
// private poolIdx = 0;
|
|
@@ -29,11 +71,82 @@ export class BareJS extends BareRouter {
|
|
|
29
71
|
private _useLog: boolean = false;
|
|
30
72
|
private errorHandler?: (err: any, ctx: Context) => any;
|
|
31
73
|
private wsRoutes = new Map<string, WebSocketRouteHandler>();
|
|
74
|
+
private startHooks: (() => void | Promise<void>)[] = [];
|
|
75
|
+
private stopHooks: (() => void | Promise<void>)[] = [];
|
|
76
|
+
private crons: Array<{ name: string; timer: ReturnType<typeof setInterval> }> = [];
|
|
77
|
+
private server?: ReturnType<typeof Bun.serve>;
|
|
78
|
+
private shutdownHandler?: () => Promise<void>;
|
|
79
|
+
private wsAdapter = {
|
|
80
|
+
open(ws: any) { ws.data?.open?.(ws); },
|
|
81
|
+
message(ws: any, msg: any) { ws.data?.message?.(ws, msg); },
|
|
82
|
+
close(ws: any, code: any, reason: any) { ws.data?.close?.(ws, code, reason); },
|
|
83
|
+
drain(ws: any) { ws.data?.drain?.(ws); }
|
|
84
|
+
};
|
|
32
85
|
|
|
33
86
|
public useLog(enabled: boolean = true): this {
|
|
34
87
|
this._useLog = enabled;
|
|
35
88
|
return this;
|
|
36
89
|
}
|
|
90
|
+
|
|
91
|
+
public onStart(fn: () => void | Promise<void>): this {
|
|
92
|
+
this.startHooks.push(fn);
|
|
93
|
+
return this;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
public onStop(fn: () => void | Promise<void>): this {
|
|
97
|
+
this.stopHooks.push(fn);
|
|
98
|
+
return this;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Built-in overlap-safe background interval scheduler.
|
|
103
|
+
* Automatically cleared when app.stop() is called.
|
|
104
|
+
*/
|
|
105
|
+
public cron(
|
|
106
|
+
name: string,
|
|
107
|
+
intervalMs: number,
|
|
108
|
+
fn: () => void | Promise<void>,
|
|
109
|
+
options: CronOptions = {}
|
|
110
|
+
): this {
|
|
111
|
+
let running = false;
|
|
112
|
+
const tick = async () => {
|
|
113
|
+
if (running) return;
|
|
114
|
+
running = true;
|
|
115
|
+
try {
|
|
116
|
+
await fn();
|
|
117
|
+
} catch (err) {
|
|
118
|
+
options.onError?.(err);
|
|
119
|
+
} finally {
|
|
120
|
+
running = false;
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
const timer = setInterval(tick, intervalMs);
|
|
124
|
+
this.crons.push({ name, timer });
|
|
125
|
+
if (options.runOnStart) {
|
|
126
|
+
void tick();
|
|
127
|
+
}
|
|
128
|
+
return this;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
public async stop(closeActiveConnections = false): Promise<void> {
|
|
132
|
+
for (const c of this.crons) {
|
|
133
|
+
clearInterval(c.timer);
|
|
134
|
+
}
|
|
135
|
+
this.crons.length = 0;
|
|
136
|
+
|
|
137
|
+
if (this.shutdownHandler) {
|
|
138
|
+
process.off("SIGINT", this.shutdownHandler);
|
|
139
|
+
process.off("SIGTERM", this.shutdownHandler);
|
|
140
|
+
this.shutdownHandler = undefined;
|
|
141
|
+
}
|
|
142
|
+
if (this.server) {
|
|
143
|
+
this.server.stop(closeActiveConnections);
|
|
144
|
+
this.server = undefined;
|
|
145
|
+
}
|
|
146
|
+
for (const hook of this.stopHooks) {
|
|
147
|
+
await hook();
|
|
148
|
+
}
|
|
149
|
+
}
|
|
37
150
|
constructor(poolSize: number = 1024) {
|
|
38
151
|
super();
|
|
39
152
|
bootstrapConfig();
|
|
@@ -129,6 +242,9 @@ export class BareJS extends BareRouter {
|
|
|
129
242
|
return ctx.status(400).json({ jsonrpc: '2.0', error: { code: -32700, message: 'Parse error' }, id: null });
|
|
130
243
|
}
|
|
131
244
|
if (Array.isArray(payload)) {
|
|
245
|
+
if (payload.length === 0) {
|
|
246
|
+
return ctx.status(400).json({ jsonrpc: '2.0', error: { code: -32600, message: 'Invalid Request' }, id: null });
|
|
247
|
+
}
|
|
132
248
|
const results = (await Promise.all(payload.map((item) => execCall(item, ctx)))).filter(Boolean);
|
|
133
249
|
return results.length > 0 ? results : new Response(null, { status: 204 });
|
|
134
250
|
}
|
|
@@ -140,10 +256,91 @@ export class BareJS extends BareRouter {
|
|
|
140
256
|
}
|
|
141
257
|
|
|
142
258
|
|
|
259
|
+
declare public get: AddRoute<Derived, Routes, 'GET'>;
|
|
260
|
+
declare public post: AddRoute<Derived, Routes, 'POST'>;
|
|
261
|
+
declare public put: AddRoute<Derived, Routes, 'PUT'>;
|
|
262
|
+
declare public patch: AddRoute<Derived, Routes, 'PATCH'>;
|
|
263
|
+
declare public delete: AddRoute<Derived, Routes, 'DELETE'>;
|
|
264
|
+
declare public options: AddRoute<Derived, Routes, 'OPTIONS'>;
|
|
265
|
+
declare public head: AddRoute<Derived, Routes, 'HEAD'>;
|
|
266
|
+
declare public all: AddRoute<Derived, Routes, 'ALL'>;
|
|
267
|
+
|
|
268
|
+
declare public use: {
|
|
269
|
+
<R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareJS<Derived, Routes & R2>;
|
|
270
|
+
(mw: any): BareJS<Derived, Routes>;
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
private _hasDerive = false;
|
|
274
|
+
public derive<T extends Record<string, any>>(fn: (ctx: Context & Derived) => Promise<T> | T): BareJS<Derived & T, Routes> {
|
|
275
|
+
this._hasDerive = true;
|
|
276
|
+
this.use(async (ctx: any, next: any) => {
|
|
277
|
+
const derived = await fn(ctx);
|
|
278
|
+
if (derived && typeof derived === 'object') {
|
|
279
|
+
const keys = Object.keys(derived);
|
|
280
|
+
if (!ctx._derivedKeys) ctx._derivedKeys = [];
|
|
281
|
+
for (let i = 0; i < keys.length; i++) {
|
|
282
|
+
const k = keys[i]!;
|
|
283
|
+
if (k !== '__proto__' && k !== 'constructor' && k !== 'prototype') {
|
|
284
|
+
ctx[k] = (derived as any)[k];
|
|
285
|
+
ctx._derivedKeys.push(k);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
return next();
|
|
290
|
+
});
|
|
291
|
+
return this as any;
|
|
292
|
+
}
|
|
293
|
+
|
|
143
294
|
// inherited use() from BareRouter handles router merging now
|
|
144
295
|
|
|
145
296
|
private compileHandler(pipeline: any[], isLog: boolean): Function {
|
|
297
|
+
const timeoutMw = pipeline.find((fn) => fn?.__timeout);
|
|
298
|
+
if (timeoutMw) {
|
|
299
|
+
const { ms, status, message } = timeoutMw.__timeout;
|
|
300
|
+
const innerPipeline = pipeline.filter((fn) => !fn?.__timeout);
|
|
301
|
+
const innerCompiled = this.compileHandler(innerPipeline, isLog);
|
|
302
|
+
return async (ctx: Context, doLog?: any) => {
|
|
303
|
+
const res = innerCompiled(ctx, doLog);
|
|
304
|
+
if (!res || !res.then) return res;
|
|
305
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
306
|
+
try {
|
|
307
|
+
const timeoutPromise = new Promise<Response>((resolve) => {
|
|
308
|
+
timer = setTimeout(() => {
|
|
309
|
+
resolve(Response.json({ status: 'error', code: 'REQUEST_TIMEOUT', message }, { status }));
|
|
310
|
+
}, ms);
|
|
311
|
+
});
|
|
312
|
+
return await Promise.race([res, timeoutPromise]);
|
|
313
|
+
} finally {
|
|
314
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
315
|
+
}
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const cbMw = pipeline.find((fn) => fn?.__circuitBreaker);
|
|
320
|
+
if (cbMw) {
|
|
321
|
+
const runWithBreaker = cbMw.__circuitBreaker;
|
|
322
|
+
const innerPipeline = pipeline.filter((fn) => !fn?.__circuitBreaker);
|
|
323
|
+
const innerCompiled = this.compileHandler(innerPipeline, isLog);
|
|
324
|
+
return (ctx: Context, doLog?: any) => runWithBreaker(() => innerCompiled(ctx, doLog));
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
const compMw = pipeline.find((fn) => fn?.__compress);
|
|
328
|
+
if (compMw) {
|
|
329
|
+
const applyCompress = compMw.__compress;
|
|
330
|
+
const innerPipeline = pipeline.filter((fn) => !fn?.__compress);
|
|
331
|
+
const innerCompiled = this.compileHandler(innerPipeline, isLog);
|
|
332
|
+
return async (ctx: Context, doLog?: any) => {
|
|
333
|
+
const res = await innerCompiled(ctx, doLog);
|
|
334
|
+
return applyCompress(ctx, res);
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
|
|
146
338
|
const len = pipeline.length;
|
|
339
|
+
const rFilterMw = pipeline.find((fn) => fn?.__responseFilter);
|
|
340
|
+
const rFilter = rFilterMw?.__responseFilter;
|
|
341
|
+
const idemMw = pipeline.find((fn) => fn?.__idempotencyCommit);
|
|
342
|
+
const idemCommit = idemMw?.__idempotencyCommit;
|
|
343
|
+
const idemRelease = idemMw?.__idempotencyRelease;
|
|
147
344
|
|
|
148
345
|
// Static ResponseInit for 200 OK (Zero Allocation)
|
|
149
346
|
const json200 = { status: 200, headers: { "content-type": "application/json" } };
|
|
@@ -154,42 +351,102 @@ export class BareJS extends BareRouter {
|
|
|
154
351
|
|
|
155
352
|
// Inline Finalizer
|
|
156
353
|
const finalizeCode = `
|
|
354
|
+
${rFilter ? 'res = rFilter(res);' : ''}
|
|
157
355
|
if (res instanceof Response) {
|
|
356
|
+
${idemRelease ? 'idemRelease(ctx);' : ''}
|
|
357
|
+
if (ctx._headers) {
|
|
358
|
+
for (const k in ctx._headers) {
|
|
359
|
+
if (!res.headers.has(k)) res.headers.set(k, ctx._headers[k]);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
if (ctx._setCookies) {
|
|
363
|
+
for (let i = 0; i < ctx._setCookies.length; i++) res.headers.append('Set-Cookie', ctx._setCookies[i]);
|
|
364
|
+
}
|
|
158
365
|
${logResCode}
|
|
159
366
|
return res;
|
|
160
367
|
}
|
|
161
368
|
|
|
162
369
|
const finalStatus = ctx._status || 200;
|
|
370
|
+
${idemCommit ? 'idemCommit(ctx, res, finalStatus);' : ''}
|
|
163
371
|
${logStatusCode}
|
|
164
372
|
|
|
373
|
+
let outRes;
|
|
165
374
|
if (typeof res === 'string') {
|
|
166
|
-
if (finalStatus === 200 && !ctx._headers)
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
375
|
+
if (finalStatus === 200 && !ctx._headers) {
|
|
376
|
+
outRes = new Response(res, text200);
|
|
377
|
+
} else {
|
|
378
|
+
outRes = new Response(res, {
|
|
379
|
+
status: finalStatus,
|
|
380
|
+
headers: ctx._headers || text200.headers
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
} else if (finalStatus === 200 && !ctx._headers) {
|
|
384
|
+
outRes = Response.json(res ?? null, json200);
|
|
385
|
+
} else {
|
|
386
|
+
outRes = Response.json(res ?? null, {
|
|
170
387
|
status: finalStatus,
|
|
171
|
-
headers:
|
|
388
|
+
headers: ctx._headers || json200.headers
|
|
172
389
|
});
|
|
173
390
|
}
|
|
174
|
-
|
|
175
|
-
if (
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
return
|
|
179
|
-
status: finalStatus,
|
|
180
|
-
headers: h || json200.headers
|
|
181
|
-
});
|
|
391
|
+
|
|
392
|
+
if (ctx._setCookies) {
|
|
393
|
+
for (let i = 0; i < ctx._setCookies.length; i++) outRes.headers.append('Set-Cookie', ctx._setCookies[i]);
|
|
394
|
+
}
|
|
395
|
+
return outRes;
|
|
182
396
|
`;
|
|
183
397
|
|
|
184
398
|
const argSig = isLog ? 'ctx, doLog' : 'ctx';
|
|
185
399
|
|
|
400
|
+
const extraNames = [
|
|
401
|
+
...(rFilter ? ['rFilter'] : []),
|
|
402
|
+
...(idemCommit ? ['idemCommit'] : []),
|
|
403
|
+
...(idemRelease ? ['idemRelease'] : [])
|
|
404
|
+
];
|
|
405
|
+
const extraVals = [
|
|
406
|
+
...(rFilter ? [rFilter] : []),
|
|
407
|
+
...(idemCommit ? [idemCommit] : []),
|
|
408
|
+
...(idemRelease ? [idemRelease] : [])
|
|
409
|
+
];
|
|
410
|
+
|
|
411
|
+
const wrapIdem = (compiled: Function): Function => {
|
|
412
|
+
if (!idemRelease) return compiled;
|
|
413
|
+
return (ctx: Context, doLog?: any) => {
|
|
414
|
+
try {
|
|
415
|
+
const out = compiled(ctx, doLog);
|
|
416
|
+
if (out && typeof out.then === 'function') {
|
|
417
|
+
return out.then(
|
|
418
|
+
(v: any) => v,
|
|
419
|
+
(err: any) => {
|
|
420
|
+
idemRelease(ctx);
|
|
421
|
+
throw err;
|
|
422
|
+
}
|
|
423
|
+
);
|
|
424
|
+
}
|
|
425
|
+
return out;
|
|
426
|
+
} catch (err) {
|
|
427
|
+
idemRelease(ctx);
|
|
428
|
+
throw err;
|
|
429
|
+
}
|
|
430
|
+
};
|
|
431
|
+
};
|
|
432
|
+
|
|
186
433
|
if (len === 1) {
|
|
187
|
-
const fn0 = pipeline[0]
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
434
|
+
const fn0 = pipeline[0]!;
|
|
435
|
+
if (fn0.constructor.name === 'AsyncFunction') {
|
|
436
|
+
return wrapIdem(
|
|
437
|
+
new Function('fn0', 'json200', 'text200', ...extraNames, `return async function(${argSig}) {
|
|
438
|
+
const res = await fn0(ctx);
|
|
439
|
+
${finalizeCode}
|
|
440
|
+
}`)(fn0, json200, text200, ...extraVals)
|
|
441
|
+
);
|
|
442
|
+
}
|
|
443
|
+
return wrapIdem(
|
|
444
|
+
new Function('fn0', 'json200', 'text200', ...extraNames, `return function(${argSig}) {
|
|
445
|
+
const res = fn0(ctx);
|
|
446
|
+
if (res && res.then) return res.then(v => { const res = v; ${finalizeCode} });
|
|
447
|
+
${finalizeCode}
|
|
448
|
+
}`)(fn0, json200, text200, ...extraVals)
|
|
449
|
+
);
|
|
193
450
|
}
|
|
194
451
|
|
|
195
452
|
// Check async
|
|
@@ -218,8 +475,8 @@ export class BareJS extends BareRouter {
|
|
|
218
475
|
code += `if (r${i} && r${i} instanceof Response) { ${isLog ? 'doLog(r' + i + '.status);' : ''} return r${i}; }\n`;
|
|
219
476
|
}
|
|
220
477
|
code += `
|
|
221
|
-
|
|
222
|
-
if (res && res.then) return res.then(v => {
|
|
478
|
+
let res = fn${len - 1}(ctx);
|
|
479
|
+
if (res && res.then) return res.then(v => { let res = v; ${finalizeCode} });
|
|
223
480
|
${finalizeCode}
|
|
224
481
|
`;
|
|
225
482
|
}
|
|
@@ -229,7 +486,9 @@ export class BareJS extends BareRouter {
|
|
|
229
486
|
? `return async function(${argSig})`
|
|
230
487
|
: `return function(${argSig})`;
|
|
231
488
|
|
|
232
|
-
return
|
|
489
|
+
return wrapIdem(
|
|
490
|
+
new Function(...fnNames, 'noop', 'json200', 'text200', ...extraNames, `${fnHeader} { ${code} }`)(...pipeline, noop, json200, text200, ...extraVals)
|
|
491
|
+
);
|
|
233
492
|
}
|
|
234
493
|
|
|
235
494
|
public compile() {
|
|
@@ -252,6 +511,12 @@ export class BareJS extends BareRouter {
|
|
|
252
511
|
if (typeof res === 'string') return new Response(res, { status });
|
|
253
512
|
return Response.json(res ?? null, { status });
|
|
254
513
|
}
|
|
514
|
+
if (err?.status >= 400 && err?.status < 500) {
|
|
515
|
+
return Response.json({
|
|
516
|
+
status: err.status,
|
|
517
|
+
message: err.message || 'Bad Request'
|
|
518
|
+
}, { status: err.status });
|
|
519
|
+
}
|
|
255
520
|
return Response.json({
|
|
256
521
|
status: 500,
|
|
257
522
|
message: process.env.NODE_ENV === 'development' ? (err?.message || "Internal Server Error") : "Internal Server Error",
|
|
@@ -270,12 +535,26 @@ export class BareJS extends BareRouter {
|
|
|
270
535
|
const EMPTY_PARAMS = Object.freeze({});
|
|
271
536
|
const hNames = hoistedHandlers.map((_, i) => `h${i}`);
|
|
272
537
|
|
|
538
|
+
const hasIdem = this.routes.some((r: any) => r.handlers.some((h: any) => h?.__idempotencyCommit));
|
|
539
|
+
const deriveCleanup = this._hasDerive
|
|
540
|
+
? `if (ctx._derivedKeys) { for (let i = 0; i < ctx._derivedKeys.length; i++) delete ctx[ctx._derivedKeys[i]]; ctx._derivedKeys = undefined; }`
|
|
541
|
+
: '';
|
|
542
|
+
const idemCleanup = hasIdem
|
|
543
|
+
? `if (ctx._idempotencyKey) { ctx._idemInFlight.delete(ctx._idempotencyKey); ctx._idempotencyKey = undefined; ctx._idemInFlight = undefined; }`
|
|
544
|
+
: '';
|
|
545
|
+
|
|
273
546
|
const releaseCode = `
|
|
274
547
|
if (ctx.store.size > 0) ctx.store.clear();
|
|
548
|
+
${deriveCleanup}
|
|
549
|
+
${idemCleanup}
|
|
275
550
|
ctx.req = undefined;
|
|
551
|
+
ctx._status = 200;
|
|
276
552
|
ctx.body = undefined;
|
|
277
553
|
ctx._query = undefined;
|
|
554
|
+
ctx._cookies = undefined;
|
|
555
|
+
ctx._setCookies = undefined;
|
|
278
556
|
ctx._headers = undefined;
|
|
557
|
+
ctx._requestId = undefined;
|
|
279
558
|
ctx.params = EMPTY_PARAMS;
|
|
280
559
|
if (poolTop < maxPool) pool[poolTop++] = ctx;
|
|
281
560
|
`;
|
|
@@ -300,8 +579,50 @@ export class BareJS extends BareRouter {
|
|
|
300
579
|
}`
|
|
301
580
|
: '';
|
|
302
581
|
|
|
303
|
-
const
|
|
304
|
-
const
|
|
582
|
+
const staticMws = this.groupMiddleware.filter((m: any) => m.__isStatic);
|
|
583
|
+
const hasStaticMw = staticMws.length > 0;
|
|
584
|
+
const runStatic = hasStaticMw
|
|
585
|
+
? async (ctx: Context) => {
|
|
586
|
+
const noop = () => {};
|
|
587
|
+
for (let i = 0; i < staticMws.length; i++) {
|
|
588
|
+
const r = await staticMws[i](ctx, noop);
|
|
589
|
+
if (r instanceof Response) {
|
|
590
|
+
if (ctx._headers) {
|
|
591
|
+
for (const k in ctx._headers) {
|
|
592
|
+
const val = ctx._headers[k];
|
|
593
|
+
if (val !== undefined && !r.headers.has(k)) r.headers.set(k, val);
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
return r;
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
return undefined;
|
|
600
|
+
}
|
|
601
|
+
: undefined;
|
|
602
|
+
|
|
603
|
+
const staticFallback = hasStaticMw
|
|
604
|
+
? `if (method === 'GET' || method === 'HEAD') {
|
|
605
|
+
out = runStatic(ctx);
|
|
606
|
+
if (out && out.then) {
|
|
607
|
+
return out.then((v) => {
|
|
608
|
+
if (v instanceof Response) { ${isLog ? 'doLog(v.status);' : ''} ${releaseCode} return v; }
|
|
609
|
+
const errorBody = hNotFound();
|
|
610
|
+
const status = errorBody.status || 404;
|
|
611
|
+
${isLog ? 'doLog(status);' : ''}
|
|
612
|
+
${releaseCode}
|
|
613
|
+
return Response.json(errorBody, { status });
|
|
614
|
+
}, (e) => {
|
|
615
|
+
const errRes = hError(e, ctx);
|
|
616
|
+
${releaseCode}
|
|
617
|
+
${isLog ? 'doLog(errRes.status || 500);' : ''}
|
|
618
|
+
return errRes;
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
}`
|
|
622
|
+
: '';
|
|
623
|
+
|
|
624
|
+
const args = ['pool', 'maxPool', 'Context', 'hNotFound', 'hError', 'EMPTY_PARAMS', ...(hasGlobalMw ? ['hOptions'] : []), ...(hasStaticMw ? ['runStatic'] : []), ...hNames];
|
|
625
|
+
const values = [pool, maxPool, Context, hNotFound, hError, EMPTY_PARAMS, ...(hasGlobalMw ? [hOptions] : []), ...(hasStaticMw ? [runStatic] : []), ...hoistedHandlers];
|
|
305
626
|
|
|
306
627
|
const logInit = isLog ? `
|
|
307
628
|
const start = performance.now();
|
|
@@ -333,17 +654,13 @@ export class BareJS extends BareRouter {
|
|
|
333
654
|
|
|
334
655
|
try {
|
|
335
656
|
ctx.req = req;
|
|
336
|
-
ctx._status = 200;
|
|
337
|
-
ctx._headers = undefined;
|
|
338
|
-
if (ctx.store.size > 0) ctx.store.clear();
|
|
339
|
-
ctx.params = EMPTY_PARAMS;
|
|
340
|
-
ctx.body = undefined;
|
|
341
|
-
ctx._query = undefined;
|
|
342
657
|
|
|
343
658
|
${routerCode}
|
|
344
659
|
|
|
345
660
|
${optionsFallback}
|
|
346
661
|
|
|
662
|
+
${staticFallback}
|
|
663
|
+
|
|
347
664
|
const errorBody = hNotFound();
|
|
348
665
|
const status = errorBody.status || 404;
|
|
349
666
|
${isLog ? 'doLog(status);' : ''}
|
|
@@ -373,13 +690,27 @@ export class BareJS extends BareRouter {
|
|
|
373
690
|
};
|
|
374
691
|
public name: string = "App";
|
|
375
692
|
|
|
376
|
-
public
|
|
377
|
-
|
|
693
|
+
public trustProxy(enabled: boolean = true): this {
|
|
694
|
+
for (let i = 0; i < this.pool.length; i++) {
|
|
695
|
+
this.pool[i]!._trustProxy = enabled;
|
|
696
|
+
}
|
|
697
|
+
return this;
|
|
698
|
+
}
|
|
378
699
|
|
|
700
|
+
public listen(
|
|
701
|
+
port?: number,
|
|
702
|
+
hostname: string = '0.0.0.0',
|
|
703
|
+
reusePort: boolean = true,
|
|
704
|
+
options: { maxRequestBodySize?: number; trustProxy?: boolean } = {}
|
|
705
|
+
) {
|
|
706
|
+
if (!this.compiled) this.compile();
|
|
707
|
+
if (options.trustProxy !== undefined) {
|
|
708
|
+
this.trustProxy(options.trustProxy);
|
|
709
|
+
}
|
|
710
|
+
const maxRequestBodySize = options.maxRequestBodySize ?? 10 * 1024 * 1024;
|
|
379
711
|
|
|
380
712
|
const { BARE_CONFIG } = require("./config");
|
|
381
713
|
|
|
382
|
-
|
|
383
714
|
const finalPort = port || BARE_CONFIG.port || 3000;
|
|
384
715
|
const isProd = process.env.NODE_ENV === 'production';
|
|
385
716
|
|
|
@@ -406,54 +737,83 @@ export class BareJS extends BareRouter {
|
|
|
406
737
|
port: finalPort,
|
|
407
738
|
hostname,
|
|
408
739
|
reusePort,
|
|
740
|
+
maxRequestBodySize,
|
|
409
741
|
fetch(req: Request, srv: any) {
|
|
410
|
-
if (req.headers.get('upgrade') === 'websocket') {
|
|
742
|
+
if (req.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
|
411
743
|
const url = req.url;
|
|
412
744
|
const s = url.indexOf('/', 8);
|
|
413
745
|
const q = s === -1 ? -1 : url.indexOf('?', s);
|
|
414
746
|
const path = s === -1 ? '/' : (q === -1 ? url.slice(s) : url.slice(s, q));
|
|
415
747
|
const normalized = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;
|
|
416
|
-
|
|
417
|
-
|
|
748
|
+
let handler = wsRoutes.get(normalized);
|
|
749
|
+
let params: Record<string, string> | undefined;
|
|
750
|
+
if (!handler) {
|
|
751
|
+
const reqParts = normalized.split('/').filter(Boolean);
|
|
752
|
+
for (const [pattern, h] of wsRoutes) {
|
|
753
|
+
if (!pattern.includes(':') && !pattern.includes('*')) continue;
|
|
754
|
+
const patParts = pattern.split('/').filter(Boolean);
|
|
755
|
+
const matched: Record<string, string> = {};
|
|
756
|
+
let ok = true;
|
|
757
|
+
for (let i = 0; i < patParts.length; i++) {
|
|
758
|
+
const pp = patParts[i]!;
|
|
759
|
+
if (pp === '*') {
|
|
760
|
+
matched['*'] = reqParts.slice(i).join('/');
|
|
761
|
+
break;
|
|
762
|
+
}
|
|
763
|
+
if (i >= reqParts.length) { ok = false; break; }
|
|
764
|
+
if (pp.startsWith(':')) {
|
|
765
|
+
matched[pp.slice(1)] = reqParts[i]!;
|
|
766
|
+
} else if (pp !== reqParts[i]) {
|
|
767
|
+
ok = false; break;
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
if (ok && (patParts.includes('*') || patParts.length === reqParts.length)) {
|
|
771
|
+
handler = h;
|
|
772
|
+
params = matched;
|
|
773
|
+
break;
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
if (handler && srv.upgrade(req, { data: params ? { ...handler, params } : handler })) {
|
|
418
778
|
return undefined as any;
|
|
419
779
|
}
|
|
420
780
|
}
|
|
421
781
|
return baseFetch(req);
|
|
422
782
|
},
|
|
423
|
-
websocket:
|
|
424
|
-
open(ws) { ws.data?.open?.(ws); },
|
|
425
|
-
message(ws, msg) { ws.data?.message?.(ws, msg); },
|
|
426
|
-
close(ws, code, reason) { ws.data?.close?.(ws, code, reason); },
|
|
427
|
-
drain(ws) { ws.data?.drain?.(ws); }
|
|
428
|
-
}
|
|
783
|
+
websocket: this.wsAdapter
|
|
429
784
|
})
|
|
430
785
|
: Bun.serve({
|
|
431
786
|
port: finalPort,
|
|
432
787
|
hostname,
|
|
433
788
|
reusePort,
|
|
789
|
+
maxRequestBodySize,
|
|
434
790
|
fetch: baseFetch
|
|
435
791
|
});
|
|
436
792
|
|
|
437
|
-
|
|
793
|
+
this.server = server;
|
|
794
|
+
for (const hook of this.startHooks) {
|
|
795
|
+
Promise.resolve(hook()).catch((e) => console.error(`[${this.name}] onStart error:`, e));
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
const shutdown = async () => {
|
|
438
799
|
const isProd = process.env.NODE_ENV === 'production';
|
|
439
800
|
const serverName = this.name;
|
|
440
801
|
const supportsEmoji = process.stdout.isTTY;
|
|
441
802
|
|
|
442
803
|
if (isProd) {
|
|
443
804
|
console.log(`[${serverName}] INFO: Stopping server...`);
|
|
805
|
+
await this.stop(false);
|
|
444
806
|
} else {
|
|
445
|
-
|
|
446
807
|
const stopIcon = supportsEmoji ? "🛑" : "!";
|
|
447
808
|
const checkIcon = supportsEmoji ? "✅" : "v";
|
|
448
|
-
|
|
449
|
-
|
|
450
809
|
process.stdout.write(`\n\x1b[31m${stopIcon} Stopping ${serverName}...\x1b[0m\n`);
|
|
451
|
-
|
|
810
|
+
await this.stop(false);
|
|
452
811
|
process.stdout.write(`\x1b[32m${checkIcon} ${serverName} has been stopped.\x1b[0m\n`);
|
|
453
812
|
}
|
|
454
813
|
process.exit(0);
|
|
455
814
|
};
|
|
456
815
|
|
|
816
|
+
this.shutdownHandler = shutdown;
|
|
457
817
|
process.on("SIGINT", shutdown);
|
|
458
818
|
process.on("SIGTERM", shutdown);
|
|
459
819
|
return server;
|