barejs 0.1.58 → 0.1.60
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 +85 -346
- package/dist/index.js +171 -161
- package/dist/node.js +362 -0
- package/dist/types/core/bare.d.ts +3 -7
- package/dist/types/core/ws-match.d.ts +15 -0
- package/dist/types/node.d.ts +1 -0
- package/dist/types/runtime/bun.d.ts +2 -0
- package/dist/types/runtime/index.d.ts +10 -0
- package/dist/types/runtime/node.d.ts +2 -0
- package/dist/types/runtime/types.d.ts +44 -0
- package/llms.txt +4 -4
- package/package.json +43 -7
- package/src/core/bare.ts +107 -76
- package/src/core/context.ts +3 -1
- package/src/core/loader.ts +5 -3
- package/src/core/ws-match.ts +60 -0
- package/src/node.ts +6 -0
- package/src/runtime/bun.ts +87 -0
- package/src/runtime/index.ts +24 -0
- package/src/runtime/node.ts +374 -0
- package/src/runtime/types.ts +49 -0
- package/src/security/hash.ts +3 -6
- package/src/utils/compress.ts +4 -3
- package/src/utils/static.ts +3 -2
|
@@ -4,6 +4,8 @@ import { Type as typebox, Type as t } from '@sinclair/typebox';
|
|
|
4
4
|
import { type OpenAPIOptions } from "../utils/openapi";
|
|
5
5
|
import type { RouteSchemas } from "../security/validators";
|
|
6
6
|
import type { RouteSchema } from "../client/index";
|
|
7
|
+
import { type WebSocketRouteHandler } from "./ws-match";
|
|
8
|
+
export type { WebSocketRouteHandler };
|
|
7
9
|
export declare function normalizePoolSize(poolSize: number, defaultSize?: number, maximumSize?: number): number;
|
|
8
10
|
export interface CronOptions {
|
|
9
11
|
/** Execute the cron job immediately upon registration (default: false) */
|
|
@@ -11,12 +13,6 @@ export interface CronOptions {
|
|
|
11
13
|
/** Optional error handler when the cron callback throws or rejects */
|
|
12
14
|
onError?: (err: any) => void;
|
|
13
15
|
}
|
|
14
|
-
export interface WebSocketRouteHandler {
|
|
15
|
-
open?: (ws: any) => void;
|
|
16
|
-
message?: (ws: any, message: string | Buffer) => void;
|
|
17
|
-
close?: (ws: any, code: number, reason: string) => void;
|
|
18
|
-
drain?: (ws: any) => void;
|
|
19
|
-
}
|
|
20
16
|
export interface NotFoundResponse {
|
|
21
17
|
status: number;
|
|
22
18
|
message: string;
|
|
@@ -140,6 +136,6 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
|
|
|
140
136
|
listen(port?: number, hostname?: string, reusePort?: boolean, options?: {
|
|
141
137
|
maxRequestBodySize?: number;
|
|
142
138
|
trustProxy?: boolean;
|
|
143
|
-
}):
|
|
139
|
+
}): any;
|
|
144
140
|
}
|
|
145
141
|
export { Context, typebox, t };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export interface WebSocketRouteHandler {
|
|
2
|
+
open?: (ws: any) => void;
|
|
3
|
+
message?: (ws: any, message: string | Buffer) => void;
|
|
4
|
+
close?: (ws: any, code: number, reason: string) => void;
|
|
5
|
+
drain?: (ws: any) => void;
|
|
6
|
+
}
|
|
7
|
+
export interface WsMatchResult {
|
|
8
|
+
handler: WebSocketRouteHandler;
|
|
9
|
+
params?: Record<string, string>;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Matches a request URL (or path) against registered WebSocket route patterns
|
|
13
|
+
* supporting exact paths, `:param` segments, and `*` catch-all wildcards.
|
|
14
|
+
*/
|
|
15
|
+
export declare function matchWsRoute(wsRoutes: Map<string, WebSocketRouteHandler>, urlOrPath: string): WsMatchResult | undefined;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './index';
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { RuntimeDriver } from './types';
|
|
2
|
+
export type { RuntimeDriver, RuntimeFileHandle, RuntimePasswordConfig, ServeOptions, ServerHandle } from './types';
|
|
3
|
+
export { bunDriver } from './bun';
|
|
4
|
+
export { nodeDriver } from './node';
|
|
5
|
+
/**
|
|
6
|
+
* Active runtime driver, resolved ONCE at module load.
|
|
7
|
+
* Bun gets bunDriver with zero per-request overhead; Node.js / Deno get nodeDriver.
|
|
8
|
+
*/
|
|
9
|
+
export declare let runtime: RuntimeDriver;
|
|
10
|
+
export declare function setRuntime(driver: RuntimeDriver): void;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { WebSocketRouteHandler } from '../core/ws-match';
|
|
2
|
+
export interface ServeOptions {
|
|
3
|
+
port: number;
|
|
4
|
+
hostname: string;
|
|
5
|
+
reusePort: boolean;
|
|
6
|
+
maxRequestBodySize: number;
|
|
7
|
+
fetch: (req: Request, peerIp?: string) => Response | Promise<Response>;
|
|
8
|
+
ws?: {
|
|
9
|
+
routes: Map<string, WebSocketRouteHandler>;
|
|
10
|
+
adapter: {
|
|
11
|
+
open(ws: any): void;
|
|
12
|
+
message(ws: any, msg: any): void;
|
|
13
|
+
close(ws: any, code: any, reason: any): void;
|
|
14
|
+
drain(ws: any): void;
|
|
15
|
+
};
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
export interface ServerHandle {
|
|
19
|
+
stop(closeActiveConnections?: boolean): void | Promise<void>;
|
|
20
|
+
port: number;
|
|
21
|
+
/** Underlying runtime server instance (e.g. Bun Server or node:http Server) */
|
|
22
|
+
raw: any;
|
|
23
|
+
}
|
|
24
|
+
export interface RuntimeFileHandle {
|
|
25
|
+
readonly type: string;
|
|
26
|
+
full(): any;
|
|
27
|
+
slice(start: number, endExclusive: number): any;
|
|
28
|
+
}
|
|
29
|
+
export interface RuntimePasswordConfig {
|
|
30
|
+
algorithm: 'argon2id' | 'bcrypt';
|
|
31
|
+
memoryCost: number;
|
|
32
|
+
timeCost: number;
|
|
33
|
+
}
|
|
34
|
+
export interface RuntimeDriver {
|
|
35
|
+
readonly name: 'bun' | 'node';
|
|
36
|
+
serve(opts: ServeOptions): ServerHandle;
|
|
37
|
+
gzip(data: Uint8Array, level: number): Uint8Array;
|
|
38
|
+
zstd?: (data: Uint8Array) => Uint8Array;
|
|
39
|
+
openFile(path: string): RuntimeFileHandle;
|
|
40
|
+
password: {
|
|
41
|
+
hash(data: string, cfg: RuntimePasswordConfig): Promise<string>;
|
|
42
|
+
verify(data: string, hash: string): Promise<boolean>;
|
|
43
|
+
};
|
|
44
|
+
}
|
package/llms.txt
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
# BareJS (`barejs`) — AI Quick Reference (`llms.txt`)
|
|
2
2
|
|
|
3
|
-
> BareJS is an ultra-fast, zero-allocation JIT-compiled web framework for **Bun** (`>= 1.1`) with built-in security (Argon2id, HS256 JWT, HMAC-signed HttpOnly cookies, CSRF, Rate Limiting, Circuit Breaker, Idempotency-Key double-charge protection, Singleflight request coalescing, Mass-Assignment `stripUnknown`, Native Gzip `compress`, `app.cron`, Security Headers, DoS limits) and **100% Function & Line Test Coverage (
|
|
3
|
+
> BareJS is an ultra-fast, zero-allocation JIT-compiled web framework for **Bun** (`>= 1.1`), **Node.js** (`>= 20` via `barejs/node`), and **Deno** with built-in security (Argon2id/scrypt, HS256/RS256/ES256 JWT, HMAC-signed HttpOnly cookies, CSRF, Rate Limiting, Circuit Breaker, Idempotency-Key double-charge protection, Singleflight request coalescing, Mass-Assignment `stripUnknown`, Native Gzip/Brotli/Zstd `compress`, `app.cron`, Security Headers, DoS limits) and **100% Function & Line Test Coverage (424 tests / 6,253 assertions)**.
|
|
4
4
|
|
|
5
|
-
## 1. Installation & Minimal App
|
|
5
|
+
## 1. Installation & Minimal App (Bun, Node.js, Deno)
|
|
6
6
|
```ts
|
|
7
|
-
import { BareJS, Context, Type } from 'barejs';
|
|
7
|
+
import { BareJS, Context, Type } from 'barejs'; // Use 'barejs/node' on Node.js (>= 20)
|
|
8
8
|
|
|
9
9
|
// Optional poolSize (0..65536, default 1024): lazy bounded LIFO Context pool with in-flight slot clearing, shared state across JIT recompiles, & dev-mode UAF guard (0 overhead in prod)
|
|
10
10
|
const app = new BareJS();
|
|
@@ -16,7 +16,7 @@ app.get('/ping', () => 'pong');
|
|
|
16
16
|
// Wildcard catch-all route (`ctx.params['*']`)
|
|
17
17
|
app.get('/files/*', (ctx: Context) => ({ filePath: ctx.params['*'] }));
|
|
18
18
|
|
|
19
|
-
app.listen(3000);
|
|
19
|
+
app.listen(3000); // Or on Deno: Deno.serve({ port: 3000 }, (req, info) => app.fetch(req, info.remoteAddr.hostname));
|
|
20
20
|
```
|
|
21
21
|
|
|
22
22
|
## 2. Routing, Plugins & Unified Schema Validation
|
package/package.json
CHANGED
|
@@ -1,18 +1,28 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "barejs",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.60",
|
|
4
4
|
"author": "xarhang",
|
|
5
|
-
"description": "
|
|
5
|
+
"description": "Batteries-included web framework for Bun, Node.js, and Deno with O(1) JIT routing, TypeBox/Zod validation, OpenAPI 3.1, WebSockets, JSON-RPC 2.0, and built-in security.",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"module": "./dist/index.js",
|
|
8
8
|
"types": "./dist/types/index.d.ts",
|
|
9
9
|
"type": "module",
|
|
10
10
|
"exports": {
|
|
11
11
|
".": {
|
|
12
|
-
"
|
|
13
|
-
"
|
|
12
|
+
"types": "./dist/types/index.d.ts",
|
|
13
|
+
"bun": "./dist/index.js",
|
|
14
|
+
"node": "./dist/node.js",
|
|
15
|
+
"import": "./dist/index.js"
|
|
16
|
+
},
|
|
17
|
+
"./node": {
|
|
18
|
+
"types": "./dist/types/node.d.ts",
|
|
19
|
+
"import": "./dist/node.js"
|
|
14
20
|
}
|
|
15
21
|
},
|
|
22
|
+
"engines": {
|
|
23
|
+
"bun": ">=1.1.0",
|
|
24
|
+
"node": ">=20.0.0"
|
|
25
|
+
},
|
|
16
26
|
"sideEffects": false,
|
|
17
27
|
"repository": {
|
|
18
28
|
"type": "git",
|
|
@@ -29,18 +39,35 @@
|
|
|
29
39
|
},
|
|
30
40
|
"keywords": [
|
|
31
41
|
"bun",
|
|
42
|
+
"nodejs",
|
|
43
|
+
"deno",
|
|
44
|
+
"web-framework",
|
|
32
45
|
"framework",
|
|
33
|
-
"
|
|
34
|
-
"
|
|
46
|
+
"typescript",
|
|
47
|
+
"batteries-included",
|
|
48
|
+
"openapi",
|
|
49
|
+
"swagger",
|
|
50
|
+
"validation",
|
|
35
51
|
"typebox",
|
|
36
52
|
"zod",
|
|
53
|
+
"websocket",
|
|
54
|
+
"sse",
|
|
55
|
+
"json-rpc",
|
|
56
|
+
"type-safe",
|
|
57
|
+
"security",
|
|
58
|
+
"jit",
|
|
59
|
+
"high-performance",
|
|
60
|
+
"fastest",
|
|
37
61
|
"barejs",
|
|
38
62
|
"http-server"
|
|
39
63
|
],
|
|
40
64
|
"license": "MIT",
|
|
41
65
|
"peerDependencies": {
|
|
42
66
|
"@sinclair/typebox": "^0.34.46",
|
|
43
|
-
"zod": "^3.0.0"
|
|
67
|
+
"zod": "^3.0.0",
|
|
68
|
+
"ws": "^8.0.0",
|
|
69
|
+
"@node-rs/argon2": "^2.0.0",
|
|
70
|
+
"bcryptjs": "^2.4.3"
|
|
44
71
|
},
|
|
45
72
|
"peerDependenciesMeta": {
|
|
46
73
|
"@sinclair/typebox": {
|
|
@@ -48,6 +75,15 @@
|
|
|
48
75
|
},
|
|
49
76
|
"zod": {
|
|
50
77
|
"optional": true
|
|
78
|
+
},
|
|
79
|
+
"ws": {
|
|
80
|
+
"optional": true
|
|
81
|
+
},
|
|
82
|
+
"@node-rs/argon2": {
|
|
83
|
+
"optional": true
|
|
84
|
+
},
|
|
85
|
+
"bcryptjs": {
|
|
86
|
+
"optional": true
|
|
51
87
|
}
|
|
52
88
|
},
|
|
53
89
|
"devDependencies": {
|
package/src/core/bare.ts
CHANGED
|
@@ -9,6 +9,10 @@ import { BARE_CONFIG } from "./config";
|
|
|
9
9
|
import { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from "../utils/openapi";
|
|
10
10
|
import type { RouteSchemas } from "../security/validators";
|
|
11
11
|
import type { RouteSchema } from "../client/index";
|
|
12
|
+
import { runtime, type ServerHandle } from "../runtime";
|
|
13
|
+
import { matchWsRoute, type WebSocketRouteHandler } from "./ws-match";
|
|
14
|
+
|
|
15
|
+
export type { WebSocketRouteHandler };
|
|
12
16
|
|
|
13
17
|
export function normalizePoolSize(
|
|
14
18
|
poolSize: number,
|
|
@@ -26,13 +30,6 @@ export interface CronOptions {
|
|
|
26
30
|
onError?: (err: any) => void;
|
|
27
31
|
}
|
|
28
32
|
|
|
29
|
-
export interface WebSocketRouteHandler {
|
|
30
|
-
open?: (ws: any) => void;
|
|
31
|
-
message?: (ws: any, message: string | Buffer) => void;
|
|
32
|
-
close?: (ws: any, code: number, reason: string) => void;
|
|
33
|
-
drain?: (ws: any) => void;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
33
|
export interface NotFoundResponse {
|
|
37
34
|
status: number;
|
|
38
35
|
message: string;
|
|
@@ -94,7 +91,7 @@ export class BareJS<
|
|
|
94
91
|
private stopHooks: (() => void | Promise<void>)[] = [];
|
|
95
92
|
private drainHooks: (() => void | Promise<void>)[] = [];
|
|
96
93
|
private crons: Array<{ name: string; timer: ReturnType<typeof setInterval> }> = [];
|
|
97
|
-
private server?:
|
|
94
|
+
private server?: ServerHandle;
|
|
98
95
|
private shutdownHandler?: () => Promise<void>;
|
|
99
96
|
private ipcDrainHandler?: (msg: any) => void;
|
|
100
97
|
private _draining = false;
|
|
@@ -716,9 +713,18 @@ export class BareJS<
|
|
|
716
713
|
const isLog = this._useLog;
|
|
717
714
|
this.tree = new RadixNode();
|
|
718
715
|
const explicitOptionsPaths = new Set<string>();
|
|
716
|
+
const staticRoutesList: Array<{ path: string; method: string; fn: Function }> = [];
|
|
717
|
+
const normStatic = (p: string) => {
|
|
718
|
+
const c = p.replace(/\/+/g, '/');
|
|
719
|
+
return c.length > 1 && c.endsWith('/') ? c.slice(0, -1) : (c || '/');
|
|
720
|
+
};
|
|
719
721
|
for (const route of this.routes) {
|
|
720
722
|
if (route.method === 'OPTIONS') explicitOptionsPaths.add(route.path);
|
|
721
|
-
|
|
723
|
+
const compiledFn = this.compileHandler(route.handlers, isLog);
|
|
724
|
+
this.tree.insert(route.path, route.method, compiledFn);
|
|
725
|
+
if (!route.path.includes(':') && !route.path.includes('*')) {
|
|
726
|
+
staticRoutesList.push({ path: normStatic(route.path), method: route.method, fn: compiledFn });
|
|
727
|
+
}
|
|
722
728
|
}
|
|
723
729
|
for (const route of this.routes) {
|
|
724
730
|
if (route.method === 'OPTIONS' || explicitOptionsPaths.has(route.path)) continue;
|
|
@@ -735,7 +741,11 @@ export class BareJS<
|
|
|
735
741
|
...route.handlers.slice(0, lastCorsIdx + 1).filter((h: any, idx: number) => idx === lastCorsIdx || !h?.__isCors),
|
|
736
742
|
() => new Response(null, { status: 204 })
|
|
737
743
|
];
|
|
738
|
-
|
|
744
|
+
const preflightFn = this.compileHandler(preflightPipeline, isLog);
|
|
745
|
+
this.tree.insert(route.path, 'OPTIONS', preflightFn);
|
|
746
|
+
if (!route.path.includes(':') && !route.path.includes('*')) {
|
|
747
|
+
staticRoutesList.push({ path: normStatic(route.path), method: 'OPTIONS', fn: preflightFn });
|
|
748
|
+
}
|
|
739
749
|
}
|
|
740
750
|
}
|
|
741
751
|
|
|
@@ -809,9 +819,13 @@ export class BareJS<
|
|
|
809
819
|
};
|
|
810
820
|
|
|
811
821
|
const hoistedHandlers: Function[] = [];
|
|
822
|
+
const handlerToName = new Map<Function, string>();
|
|
812
823
|
const register = (h: Function) => {
|
|
824
|
+
const existing = handlerToName.get(h);
|
|
825
|
+
if (existing) return existing;
|
|
813
826
|
const name = `h${hoistedHandlers.length}`;
|
|
814
827
|
hoistedHandlers.push(h);
|
|
828
|
+
handlerToName.set(h, name);
|
|
815
829
|
return name;
|
|
816
830
|
};
|
|
817
831
|
|
|
@@ -890,7 +904,7 @@ export class BareJS<
|
|
|
890
904
|
const useCompactEmit = this.routes.length > 16;
|
|
891
905
|
const relArgs = isDevUaf ? 'rawCtx, _uaf' : 'ctx';
|
|
892
906
|
const errArgs = isDevUaf ? `e, rawCtx, _uaf${isLog ? ', doLog' : ''}` : `e, ctx${isLog ? ', doLog' : ''}`;
|
|
893
|
-
const
|
|
907
|
+
const emitInvoke = (hName: string) =>
|
|
894
908
|
useCompactEmit
|
|
895
909
|
? `out = ${hName}${callSuffix};
|
|
896
910
|
if (out && out.then) return out.then((v) => { _rel(${relArgs}); return v; }, (e) => _onErr(${errArgs}));
|
|
@@ -899,8 +913,43 @@ export class BareJS<
|
|
|
899
913
|
: `out = ${hName}${callSuffix};
|
|
900
914
|
if (out && out.then) return out.then((v) => { ${releaseCode} return v; }, (e) => { ${handleErrCode} });
|
|
901
915
|
${releaseCode}
|
|
902
|
-
return out
|
|
903
|
-
|
|
916
|
+
return out;`;
|
|
917
|
+
|
|
918
|
+
const routerCode = tree.jitCompile(register, 0, 'url', 's', [], emitInvoke);
|
|
919
|
+
|
|
920
|
+
let staticFastPathCode = '';
|
|
921
|
+
if (staticRoutesList.length > 0) {
|
|
922
|
+
const grouped = new Map<string, Map<string, string>>();
|
|
923
|
+
for (const entry of staticRoutesList) {
|
|
924
|
+
const hName = handlerToName.get(entry.fn);
|
|
925
|
+
if (!hName) continue;
|
|
926
|
+
let mMap = grouped.get(entry.path);
|
|
927
|
+
if (!mMap) {
|
|
928
|
+
mMap = new Map<string, string>();
|
|
929
|
+
grouped.set(entry.path, mMap);
|
|
930
|
+
}
|
|
931
|
+
mMap.set(entry.method, hName);
|
|
932
|
+
}
|
|
933
|
+
if (grouped.size > 0) {
|
|
934
|
+
let cases = '';
|
|
935
|
+
for (const [p, mMap] of grouped) {
|
|
936
|
+
let mCases = '';
|
|
937
|
+
let allHandler: string | undefined;
|
|
938
|
+
for (const [m, hName] of mMap) {
|
|
939
|
+
if (m === 'ALL') {
|
|
940
|
+
allHandler = hName;
|
|
941
|
+
} else {
|
|
942
|
+
mCases += `case ${JSON.stringify(m)}: ${emitInvoke(hName)}\n`;
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
if (allHandler) {
|
|
946
|
+
mCases += `default: ${emitInvoke(allHandler)}\n`;
|
|
947
|
+
}
|
|
948
|
+
cases += `case ${JSON.stringify(p)}:\n switch (method) {\n ${mCases} }\n break;\n`;
|
|
949
|
+
}
|
|
950
|
+
staticFastPathCode = `switch (rawPath) {\n${cases}}`;
|
|
951
|
+
}
|
|
952
|
+
}
|
|
904
953
|
|
|
905
954
|
const hNames = hoistedHandlers.map((_, i) => `h${i}`);
|
|
906
955
|
|
|
@@ -1028,6 +1077,7 @@ export class BareJS<
|
|
|
1028
1077
|
let s = url.indexOf('/', 8);
|
|
1029
1078
|
const q = s === -1 ? -1 : url.indexOf('?', s);
|
|
1030
1079
|
const urlLen = q === -1 ? url.length : q;
|
|
1080
|
+
${staticFastPathCode ? "const rawPath = s === -1 ? '/' : url.slice(s, urlLen);" : ''}
|
|
1031
1081
|
if (s !== -1) s++;
|
|
1032
1082
|
else s = urlLen;
|
|
1033
1083
|
|
|
@@ -1048,6 +1098,8 @@ export class BareJS<
|
|
|
1048
1098
|
${ctxVar}.req = req;
|
|
1049
1099
|
${ctxVar}._peerIp = peerIp;
|
|
1050
1100
|
|
|
1101
|
+
${staticFastPathCode}
|
|
1102
|
+
|
|
1051
1103
|
${routerCode}
|
|
1052
1104
|
|
|
1053
1105
|
${optionsFallback}
|
|
@@ -1067,7 +1119,36 @@ export class BareJS<
|
|
|
1067
1119
|
};
|
|
1068
1120
|
`;
|
|
1069
1121
|
|
|
1070
|
-
|
|
1122
|
+
const compiledFetch = new Function(...args, fnBody)(...values);
|
|
1123
|
+
const denoUpgrade = (globalThis as any).Deno?.upgradeWebSocket;
|
|
1124
|
+
if (this.wsRoutes.size > 0 && typeof denoUpgrade === 'function') {
|
|
1125
|
+
const wsRoutes = this.wsRoutes;
|
|
1126
|
+
this.hotFetch = (req: Request, peerIp?: string) => {
|
|
1127
|
+
if (req.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
|
1128
|
+
const matched = matchWsRoute(wsRoutes, req.url);
|
|
1129
|
+
if (matched) {
|
|
1130
|
+
const { socket, response } = denoUpgrade(req);
|
|
1131
|
+
(socket as any).data = matched.params
|
|
1132
|
+
? { ...matched.handler, params: matched.params }
|
|
1133
|
+
: matched.handler;
|
|
1134
|
+
if (matched.handler.open) socket.onopen = () => matched.handler.open!(socket);
|
|
1135
|
+
if (matched.handler.message) {
|
|
1136
|
+
socket.onmessage = (ev: MessageEvent) => {
|
|
1137
|
+
const payload = ev.data instanceof ArrayBuffer ? new Uint8Array(ev.data) : ev.data;
|
|
1138
|
+
matched.handler.message!(socket, payload as any);
|
|
1139
|
+
};
|
|
1140
|
+
}
|
|
1141
|
+
if (matched.handler.close) {
|
|
1142
|
+
socket.onclose = (ev: CloseEvent) => matched.handler.close!(socket, ev.code, ev.reason);
|
|
1143
|
+
}
|
|
1144
|
+
return response;
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
return compiledFetch(req, peerIp);
|
|
1148
|
+
};
|
|
1149
|
+
} else {
|
|
1150
|
+
this.hotFetch = compiledFetch;
|
|
1151
|
+
}
|
|
1071
1152
|
this.compiled = true;
|
|
1072
1153
|
this.fetch = this.hotFetch!;
|
|
1073
1154
|
}
|
|
@@ -1131,7 +1212,7 @@ export class BareJS<
|
|
|
1131
1212
|
\x1b[33m |____/ \\__,_|_| \\___| \\___/|_____|\x1b[0m
|
|
1132
1213
|
|
|
1133
1214
|
\x1b[32m🚀 ${this.name} is running in development mode\x1b[0m
|
|
1134
|
-
\x1b[90m⚙️ Pool Size: ${this.maxPool} | JIT: Enabled | Port: ${finalPort}\x1b[0m
|
|
1215
|
+
\x1b[90m⚙️ Runtime: ${runtime.name} | Pool Size: ${this.maxPool} | JIT: Enabled | Port: ${finalPort}\x1b[0m
|
|
1135
1216
|
\x1b[36m🛡️ Hash: ${BARE_CONFIG.hash.algorithm} (${BARE_CONFIG.hash.memoryCost / 1024}MB) | Iterations: ${BARE_CONFIG.hash.timeCost}\x1b[0m
|
|
1136
1217
|
`);
|
|
1137
1218
|
}
|
|
@@ -1140,66 +1221,16 @@ export class BareJS<
|
|
|
1140
1221
|
const self = this;
|
|
1141
1222
|
const hasWs = wsRoutes.size > 0;
|
|
1142
1223
|
|
|
1143
|
-
const server =
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
const q = s === -1 ? -1 : url.indexOf('?', s);
|
|
1154
|
-
const path = s === -1 ? '/' : (q === -1 ? url.slice(s) : url.slice(s, q));
|
|
1155
|
-
const collapsed = path.replace(/\/+/g, '/');
|
|
1156
|
-
const normalized = collapsed.length > 1 && collapsed.endsWith('/') ? collapsed.slice(0, -1) : collapsed;
|
|
1157
|
-
let handler = wsRoutes.get(normalized);
|
|
1158
|
-
let params: Record<string, string> | undefined;
|
|
1159
|
-
if (!handler) {
|
|
1160
|
-
const reqParts = normalized.split('/').filter(Boolean);
|
|
1161
|
-
for (const [pattern, h] of wsRoutes) {
|
|
1162
|
-
if (!pattern.includes(':') && !pattern.includes('*')) continue;
|
|
1163
|
-
const patParts = pattern.split('/').filter(Boolean);
|
|
1164
|
-
const matched: Record<string, string> = {};
|
|
1165
|
-
let ok = true;
|
|
1166
|
-
for (let i = 0; i < patParts.length; i++) {
|
|
1167
|
-
const pp = patParts[i]!;
|
|
1168
|
-
if (pp === '*') {
|
|
1169
|
-
matched['*'] = reqParts.slice(i).join('/');
|
|
1170
|
-
break;
|
|
1171
|
-
}
|
|
1172
|
-
if (i >= reqParts.length) { ok = false; break; }
|
|
1173
|
-
if (pp.startsWith(':')) {
|
|
1174
|
-
matched[pp.slice(1)] = reqParts[i]!;
|
|
1175
|
-
} else if (pp !== reqParts[i]) {
|
|
1176
|
-
ok = false; break;
|
|
1177
|
-
}
|
|
1178
|
-
}
|
|
1179
|
-
if (ok && (patParts.includes('*') || patParts.length === reqParts.length)) {
|
|
1180
|
-
handler = h;
|
|
1181
|
-
params = matched;
|
|
1182
|
-
break;
|
|
1183
|
-
}
|
|
1184
|
-
}
|
|
1185
|
-
}
|
|
1186
|
-
if (handler && srv.upgrade(req, { data: params ? { ...handler, params } : handler })) {
|
|
1187
|
-
return undefined as any;
|
|
1188
|
-
}
|
|
1189
|
-
}
|
|
1190
|
-
return self.fetch(req, srv?.requestIP?.(req)?.address);
|
|
1191
|
-
},
|
|
1192
|
-
websocket: this.wsAdapter
|
|
1193
|
-
})
|
|
1194
|
-
: Bun.serve({
|
|
1195
|
-
port: finalPort,
|
|
1196
|
-
hostname,
|
|
1197
|
-
reusePort,
|
|
1198
|
-
maxRequestBodySize,
|
|
1199
|
-
fetch(req: Request, srv: any) {
|
|
1200
|
-
return self.fetch(req, srv?.requestIP?.(req)?.address);
|
|
1201
|
-
}
|
|
1202
|
-
});
|
|
1224
|
+
const server = runtime.serve({
|
|
1225
|
+
port: finalPort,
|
|
1226
|
+
hostname,
|
|
1227
|
+
reusePort,
|
|
1228
|
+
maxRequestBodySize,
|
|
1229
|
+
fetch(req: Request, peerIp?: string) {
|
|
1230
|
+
return self.fetch(req, peerIp);
|
|
1231
|
+
},
|
|
1232
|
+
ws: hasWs ? { routes: wsRoutes, adapter: this.wsAdapter } : undefined
|
|
1233
|
+
});
|
|
1203
1234
|
|
|
1204
1235
|
this.server = server;
|
|
1205
1236
|
for (const hook of this.startHooks) {
|
|
@@ -1237,7 +1268,7 @@ export class BareJS<
|
|
|
1237
1268
|
};
|
|
1238
1269
|
this.ipcDrainHandler = onIpcMessage;
|
|
1239
1270
|
process.on("message", onIpcMessage);
|
|
1240
|
-
return server;
|
|
1271
|
+
return server.raw;
|
|
1241
1272
|
}
|
|
1242
1273
|
}
|
|
1243
1274
|
|
package/src/core/context.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
2
2
|
|
|
3
|
+
const _peek: ((p: any) => any) | undefined = (globalThis as any).Bun?.peek;
|
|
4
|
+
|
|
3
5
|
let _userStreamsCreated = 0;
|
|
4
6
|
const _userStreams = new WeakSet<ReadableStream>();
|
|
5
7
|
if (typeof globalThis.ReadableStream === 'function' && !(globalThis.ReadableStream as any).__bareTracked) {
|
|
@@ -354,7 +356,7 @@ export class Context {
|
|
|
354
356
|
);
|
|
355
357
|
}
|
|
356
358
|
const tp = this.req.text();
|
|
357
|
-
const peeked =
|
|
359
|
+
const peeked = _peek !== undefined ? _peek(tp) : tp;
|
|
358
360
|
if (typeof peeked === "string") {
|
|
359
361
|
try {
|
|
360
362
|
return this._parseAndSanitizeJson(peeked, maxBytes);
|
package/src/core/loader.ts
CHANGED
|
@@ -7,8 +7,10 @@ import { initConfig } from "./config";
|
|
|
7
7
|
const req = createRequire(import.meta.url);
|
|
8
8
|
|
|
9
9
|
export async function bootstrapConfig() {
|
|
10
|
-
const
|
|
11
|
-
|
|
10
|
+
const cwd = process.cwd();
|
|
11
|
+
const candidates = ["bare.config.ts", "bare.config.js", "bare.config.mjs"];
|
|
12
|
+
const configPath = candidates.map((f) => join(cwd, f)).find((p) => existsSync(p));
|
|
13
|
+
if (!configPath) {
|
|
12
14
|
return initConfig();
|
|
13
15
|
}
|
|
14
16
|
try {
|
|
@@ -17,7 +19,7 @@ export async function bootstrapConfig() {
|
|
|
17
19
|
const userModule = req(resolved);
|
|
18
20
|
return initConfig(userModule?.default ?? userModule);
|
|
19
21
|
} catch (err: any) {
|
|
20
|
-
console.warn(`[BareJS] Failed to load
|
|
22
|
+
console.warn(`[BareJS] Failed to load ${configPath}:`, err?.message || err);
|
|
21
23
|
return initConfig();
|
|
22
24
|
}
|
|
23
25
|
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
export interface WebSocketRouteHandler {
|
|
2
|
+
open?: (ws: any) => void;
|
|
3
|
+
message?: (ws: any, message: string | Buffer) => void;
|
|
4
|
+
close?: (ws: any, code: number, reason: string) => void;
|
|
5
|
+
drain?: (ws: any) => void;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface WsMatchResult {
|
|
9
|
+
handler: WebSocketRouteHandler;
|
|
10
|
+
params?: Record<string, string>;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Matches a request URL (or path) against registered WebSocket route patterns
|
|
15
|
+
* supporting exact paths, `:param` segments, and `*` catch-all wildcards.
|
|
16
|
+
*/
|
|
17
|
+
export function matchWsRoute(
|
|
18
|
+
wsRoutes: Map<string, WebSocketRouteHandler>,
|
|
19
|
+
urlOrPath: string
|
|
20
|
+
): WsMatchResult | undefined {
|
|
21
|
+
let path = urlOrPath;
|
|
22
|
+
if (urlOrPath.startsWith('http://') || urlOrPath.startsWith('https://') || urlOrPath.startsWith('ws://') || urlOrPath.startsWith('wss://')) {
|
|
23
|
+
const s = urlOrPath.indexOf('/', 8);
|
|
24
|
+
const q = s === -1 ? -1 : urlOrPath.indexOf('?', s);
|
|
25
|
+
path = s === -1 ? '/' : (q === -1 ? urlOrPath.slice(s) : urlOrPath.slice(s, q));
|
|
26
|
+
} else {
|
|
27
|
+
const q = urlOrPath.indexOf('?');
|
|
28
|
+
if (q !== -1) path = urlOrPath.slice(0, q);
|
|
29
|
+
}
|
|
30
|
+
const collapsed = path.replace(/\/+/g, '/');
|
|
31
|
+
const normalized = collapsed.length > 1 && collapsed.endsWith('/') ? collapsed.slice(0, -1) : collapsed;
|
|
32
|
+
|
|
33
|
+
const exact = wsRoutes.get(normalized);
|
|
34
|
+
if (exact) return { handler: exact };
|
|
35
|
+
|
|
36
|
+
const reqParts = normalized.split('/').filter(Boolean);
|
|
37
|
+
for (const [pattern, h] of wsRoutes) {
|
|
38
|
+
if (!pattern.includes(':') && !pattern.includes('*')) continue;
|
|
39
|
+
const patParts = pattern.split('/').filter(Boolean);
|
|
40
|
+
const matched: Record<string, string> = {};
|
|
41
|
+
let ok = true;
|
|
42
|
+
for (let i = 0; i < patParts.length; i++) {
|
|
43
|
+
const pp = patParts[i]!;
|
|
44
|
+
if (pp === '*') {
|
|
45
|
+
matched['*'] = reqParts.slice(i).join('/');
|
|
46
|
+
break;
|
|
47
|
+
}
|
|
48
|
+
if (i >= reqParts.length) { ok = false; break; }
|
|
49
|
+
if (pp.startsWith(':')) {
|
|
50
|
+
matched[pp.slice(1)] = reqParts[i]!;
|
|
51
|
+
} else if (pp !== reqParts[i]) {
|
|
52
|
+
ok = false; break;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (ok && (patParts.includes('*') || patParts.length === reqParts.length)) {
|
|
56
|
+
return { handler: h, params: matched };
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|