barejs 0.1.58 → 0.1.59

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.
@@ -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
- }): Bun.Server<WebSocketRouteHandler> | Bun.Server<undefined>;
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,2 @@
1
+ import type { RuntimeDriver } from './types';
2
+ export declare const bunDriver: RuntimeDriver;
@@ -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,2 @@
1
+ import type { RuntimeDriver } from './types';
2
+ export declare const nodeDriver: RuntimeDriver;
@@ -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 (413 tests / 6,205 assertions)**.
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, 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 (423 tests / 6,249 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.58",
3
+ "version": "0.1.59",
4
4
  "author": "xarhang",
5
- "description": "High-performance JIT-specialized web framework for Bun",
5
+ "description": "Full-featured, batteries-included Bun web framework combining O(1) JIT routing and object pooling with built-in TypeBox/Zod validation, OpenAPI 3.1, WebSockets, JSON-RPC 2.0, and zero-trust 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
- "import": "./dist/index.js",
13
- "types": "./dist/types/index.d.ts"
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
- "fastest",
34
- "jit",
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 { 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?: ReturnType<typeof Bun.serve>;
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
- this.tree.insert(route.path, route.method, this.compileHandler(route.handlers, isLog));
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
- this.tree.insert(route.path, 'OPTIONS', this.compileHandler(preflightPipeline, isLog));
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 routerCode = tree.jitCompile(register, 0, 'url', 's', [], (hName: string) =>
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}
@@ -1131,7 +1183,7 @@ export class BareJS<
1131
1183
  \x1b[33m |____/ \\__,_|_| \\___| \\___/|_____|\x1b[0m
1132
1184
 
1133
1185
  \x1b[32m🚀 ${this.name} is running in development mode\x1b[0m
1134
- \x1b[90m⚙️ Pool Size: ${this.maxPool} | JIT: Enabled | Port: ${finalPort}\x1b[0m
1186
+ \x1b[90m⚙️ Runtime: ${runtime.name} | Pool Size: ${this.maxPool} | JIT: Enabled | Port: ${finalPort}\x1b[0m
1135
1187
  \x1b[36m🛡️ Hash: ${BARE_CONFIG.hash.algorithm} (${BARE_CONFIG.hash.memoryCost / 1024}MB) | Iterations: ${BARE_CONFIG.hash.timeCost}\x1b[0m
1136
1188
  `);
1137
1189
  }
@@ -1140,66 +1192,16 @@ export class BareJS<
1140
1192
  const self = this;
1141
1193
  const hasWs = wsRoutes.size > 0;
1142
1194
 
1143
- const server = hasWs
1144
- ? Bun.serve<WebSocketRouteHandler>({
1145
- port: finalPort,
1146
- hostname,
1147
- reusePort,
1148
- maxRequestBodySize,
1149
- fetch(req: Request, srv: any) {
1150
- if (req.headers.get('upgrade')?.toLowerCase() === 'websocket') {
1151
- const url = req.url;
1152
- const s = url.indexOf('/', 8);
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
- });
1195
+ const server = runtime.serve({
1196
+ port: finalPort,
1197
+ hostname,
1198
+ reusePort,
1199
+ maxRequestBodySize,
1200
+ fetch(req: Request, peerIp?: string) {
1201
+ return self.fetch(req, peerIp);
1202
+ },
1203
+ ws: hasWs ? { routes: wsRoutes, adapter: this.wsAdapter } : undefined
1204
+ });
1203
1205
 
1204
1206
  this.server = server;
1205
1207
  for (const hook of this.startHooks) {
@@ -1237,7 +1239,7 @@ export class BareJS<
1237
1239
  };
1238
1240
  this.ipcDrainHandler = onIpcMessage;
1239
1241
  process.on("message", onIpcMessage);
1240
- return server;
1242
+ return server.raw;
1241
1243
  }
1242
1244
  }
1243
1245
 
@@ -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 = Bun.peek(tp);
359
+ const peeked = _peek !== undefined ? _peek(tp) : tp;
358
360
  if (typeof peeked === "string") {
359
361
  try {
360
362
  return this._parseAndSanitizeJson(peeked, maxBytes);
@@ -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 configPath = join(process.cwd(), "bare.config.ts");
11
- if (!existsSync(configPath)) {
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 bare.config.ts:`, err?.message || err);
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
+ }
package/src/node.ts ADDED
@@ -0,0 +1,6 @@
1
+ import { setRuntime } from './runtime';
2
+ import { nodeDriver } from './runtime/node';
3
+
4
+ setRuntime(nodeDriver);
5
+
6
+ export * from './index';
@@ -0,0 +1,87 @@
1
+ import type { RuntimeDriver, RuntimeFileHandle, RuntimePasswordConfig, ServeOptions, ServerHandle } from './types';
2
+ import { matchWsRoute, type WebSocketRouteHandler } from '../core/ws-match';
3
+
4
+ const _zstd = typeof (globalThis as any).Bun?.zstdCompressSync === 'function'
5
+ ? (data: Uint8Array): Uint8Array => (globalThis as any).Bun.zstdCompressSync(data)
6
+ : undefined;
7
+
8
+ export const bunDriver: RuntimeDriver = {
9
+ name: 'bun',
10
+
11
+ serve(opts: ServeOptions): ServerHandle {
12
+ const wsCfg = opts.ws;
13
+ const server = wsCfg
14
+ ? Bun.serve<WebSocketRouteHandler>({
15
+ port: opts.port,
16
+ hostname: opts.hostname,
17
+ reusePort: opts.reusePort,
18
+ maxRequestBodySize: opts.maxRequestBodySize,
19
+ fetch(req: Request, srv: any) {
20
+ if (req.headers.get('upgrade')?.toLowerCase() === 'websocket') {
21
+ const matched = matchWsRoute(wsCfg.routes, req.url);
22
+ if (
23
+ matched &&
24
+ srv.upgrade(req, {
25
+ data: matched.params ? { ...matched.handler, params: matched.params } : matched.handler
26
+ })
27
+ ) {
28
+ return undefined as any;
29
+ }
30
+ }
31
+ return opts.fetch(req, srv?.requestIP?.(req)?.address);
32
+ },
33
+ websocket: wsCfg.adapter
34
+ })
35
+ : Bun.serve({
36
+ port: opts.port,
37
+ hostname: opts.hostname,
38
+ reusePort: opts.reusePort,
39
+ maxRequestBodySize: opts.maxRequestBodySize,
40
+ fetch(req: Request, srv: any) {
41
+ return opts.fetch(req, srv?.requestIP?.(req)?.address);
42
+ }
43
+ });
44
+
45
+ return {
46
+ stop(closeActiveConnections = false) {
47
+ server.stop(closeActiveConnections);
48
+ },
49
+ port: server.port ?? opts.port,
50
+ raw: server
51
+ };
52
+ },
53
+
54
+ gzip(data: Uint8Array, level: number): Uint8Array {
55
+ return Bun.gzipSync(data as any, { level: level as any });
56
+ },
57
+
58
+ zstd: _zstd,
59
+
60
+ openFile(path: string): RuntimeFileHandle {
61
+ const file = Bun.file(path);
62
+ return {
63
+ get type() {
64
+ return file.type;
65
+ },
66
+ full() {
67
+ return file;
68
+ },
69
+ slice(start: number, endExclusive: number) {
70
+ return file.slice(start, endExclusive);
71
+ }
72
+ };
73
+ },
74
+
75
+ password: {
76
+ hash(data: string, cfg: RuntimePasswordConfig): Promise<string> {
77
+ if (cfg.algorithm === 'bcrypt') {
78
+ const cost = Math.max(4, Math.min(31, cfg.timeCost));
79
+ return Bun.password.hash(data, { algorithm: 'bcrypt', cost });
80
+ }
81
+ return Bun.password.hash(data, cfg);
82
+ },
83
+ verify(data: string, hash: string): Promise<boolean> {
84
+ return Bun.password.verify(data, hash);
85
+ }
86
+ }
87
+ };