barejs 0.1.61 → 0.1.63

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.
@@ -133,6 +133,7 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
133
133
  request(path: string, init?: RequestInit): Promise<Response>;
134
134
  name: string;
135
135
  trustProxy(enabled?: boolean): this;
136
+ private buildBunRoutes;
136
137
  listen(port?: number, hostname?: string, reusePort?: boolean, options?: {
137
138
  maxRequestBodySize?: number;
138
139
  trustProxy?: boolean;
@@ -5,6 +5,7 @@ export interface ServeOptions {
5
5
  reusePort: boolean;
6
6
  maxRequestBodySize: number;
7
7
  fetch: (req: Request, peerIp?: string) => Response | Promise<Response>;
8
+ routes?: Record<string, any>;
8
9
  ws?: {
9
10
  routes: Map<string, WebSocketRouteHandler>;
10
11
  adapter: {
package/llms.txt CHANGED
@@ -1,6 +1,6 @@
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`), **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)**.
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 **Full Multi-Runtime Test Suite (427 tests / 6,279 assertions verified in CI across Bun, Node.js 20/22, and Deno 2)**.
4
4
 
5
5
  ## 1. Installation & Minimal App (Bun, Node.js, Deno)
6
6
  ```ts
@@ -121,7 +121,8 @@ app.get('/sso', bareAuth({ algorithms: ['RS256', 'ES256'], jwksUri: 'https://aut
121
121
  ```
122
122
 
123
123
  ## 6. Real-Time, RPC, OpenAPI & Client
124
- - **WebSocket**: `app.ws('/ws/chat', { open(ws){}, message(ws, msg){}, close(ws){}, drain(ws){} })`
124
+ - **WebSocket**: `app.ws('/ws/chat', { open(ws){}, message(ws, msg){}, close(ws){}, drain(ws){} })` (Native on Bun, built-in RFC 6455 or optional `ws` on Node.js, `Deno.upgradeWebSocket` on Deno)
125
+ - **SSE**: `ctx.sse(async (send, close) => { send(data, event?, id?); })` or `ctx.sse(asyncIterable)` (works across Bun, Node.js, Deno)
125
126
  - **JSON-RPC 2.0**: `app.rpc('/rpc', { add: ({ a, b }, ctx) => a + b })` (supports single, batch, notifications, and standard `-32700`/`-32600`/`-32601`/`-32603` error codes)
126
127
  - **OpenAPI 3.1 + Scalar UI**: `app.docs('/docs', { title: 'My API', version: '1.0.0' })` (serves `/docs` & `/docs/json` with full `params`, `query`, `headers`, `body`, `response`, and `detail`)
127
128
  - **Type-Safe Client (URL or Zero-Network In-Memory `app`)**:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barejs",
3
- "version": "0.1.61",
3
+ "version": "0.1.63",
4
4
  "author": "xarhang",
5
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",
@@ -30,6 +30,8 @@
30
30
  },
31
31
  "scripts": {
32
32
  "test": "bun test",
33
+ "test:node": "NODE_OPTIONS=--expose-gc vitest run && node tests/node-smoke.mjs",
34
+ "test:deno": "deno test --allow-all --unstable-sloppy-imports --no-check --v8-flags=--expose-gc --config deno.test.json --ignore=tests/playwright.test.ts,tests/production-db.test.ts tests/ && deno run --allow-net --allow-read --allow-write --allow-env tests/deno-smoke.ts",
33
35
  "benchs": "bun run benchmarks/index.ts",
34
36
  "bench": "bun run benchmarks/head-to-head.ts",
35
37
  "dev": "bun --watch Example/index.ts",
@@ -67,7 +69,7 @@
67
69
  "zod": "^3.0.0",
68
70
  "ws": "^8.0.0",
69
71
  "@node-rs/argon2": "^2.0.0",
70
- "bcryptjs": "^2.4.3"
72
+ "bcryptjs": ""
71
73
  },
72
74
  "peerDependenciesMeta": {
73
75
  "@sinclair/typebox": {
@@ -89,11 +91,14 @@
89
91
  "devDependencies": {
90
92
  "@sinclair/typebox": "^0.34.47",
91
93
  "@types/bun": "^1.3.5",
94
+ "bcryptjs": "^2.4.3",
92
95
  "elysia": "latest",
93
96
  "hono": "latest",
94
97
  "mitata": "^1.0.34",
95
98
  "playwright-core": "^1.65.1",
96
99
  "typescript": "latest",
100
+ "vitest": "^3.2.4",
101
+ "ws": "^8.0.0",
97
102
  "zod": "^3.25.76"
98
103
  },
99
104
  "files": [
package/src/core/bare.ts CHANGED
@@ -23,6 +23,39 @@ export function normalizePoolSize(
23
23
  return Math.min(maximumSize, Math.max(0, requested));
24
24
  }
25
25
 
26
+ const ZERO_ARG_RE = /^\s*(?:async\s+)?(?:\(\s*\)|function\s*(?:\w+\s*)?\(\s*\))/;
27
+ const PURE_STATIC_STR_RE = /^\s*\(\s*\)\s*=>\s*(?:'[^'\\]*'|"[^"\\]*")\s*$/;
28
+
29
+ function isTrulyZeroArg(fn: unknown): fn is (...args: any[]) => any {
30
+ if (typeof fn !== 'function' || fn.length !== 0) return false;
31
+ const src = fn.toString();
32
+ return ZERO_ARG_RE.test(src) && !/\barguments\b/.test(src);
33
+ }
34
+
35
+ function isPureStaticStringFn(fn: unknown): fn is () => string {
36
+ return typeof fn === 'function' && fn.length === 0 && PURE_STATIC_STR_RE.test(fn.toString());
37
+ }
38
+
39
+ function toZeroArgResponse(out: any): Response {
40
+ if (out instanceof Response) return out;
41
+ if (typeof out === 'string') return new Response(out);
42
+ return Response.json(out ?? null);
43
+ }
44
+
45
+ function zeroArgErrorRes(err: any): Response {
46
+ if (err?.status >= 400 && err?.status < 500) {
47
+ return Response.json({
48
+ status: err.status,
49
+ message: err.message || 'Bad Request'
50
+ }, { status: err.status });
51
+ }
52
+ return Response.json({
53
+ status: 500,
54
+ message: process.env.NODE_ENV === 'development' ? (err?.message || "Internal Server Error") : "Internal Server Error",
55
+ stack: process.env.NODE_ENV === 'development' ? err?.stack : undefined
56
+ }, { status: 500 });
57
+ }
58
+
26
59
  export interface CronOptions {
27
60
  /** Execute the cron job immediately upon registration (default: false) */
28
61
  runOnStart?: boolean;
@@ -1188,6 +1221,127 @@ export class BareJS<
1188
1221
  return this;
1189
1222
  }
1190
1223
 
1224
+ private buildBunRoutes(): Record<string, any> | undefined {
1225
+ if (
1226
+ this._useLog ||
1227
+ this.groupMiddleware.length > 0 ||
1228
+ this.errorHandler !== undefined ||
1229
+ this._trustProxyBox.val ||
1230
+ this._hasDerive ||
1231
+ this.routes.length === 0
1232
+ ) {
1233
+ return undefined;
1234
+ }
1235
+
1236
+ const routes: Record<string, Record<string, any>> = {};
1237
+ const pool = this.pool;
1238
+ const poolState = this._poolState;
1239
+ const maxPool = this.maxPool;
1240
+ const isProd = process.env.NODE_ENV === 'production';
1241
+ const normStatic = (p: string) => {
1242
+ const c = p.replace(/\/+/g, '/');
1243
+ return c.length > 1 && c.endsWith('/') ? c.slice(0, -1) : (c || '/');
1244
+ };
1245
+
1246
+ let count = 0;
1247
+ for (const route of this.routes) {
1248
+ if (route.method === 'ALL') continue;
1249
+ if (route.path.includes('*') || route.path.includes('?') || route.path.includes('(')) continue;
1250
+ if (route.handlers.length !== 1) continue;
1251
+
1252
+ const rawHandler = route.handlers[0] as any;
1253
+ if (rawHandler?.__idempotencyCommit || rawHandler?.__isDerive || rawHandler?.__isCors) continue;
1254
+
1255
+ const normPath = normStatic(route.path);
1256
+ if (this.wsRoutes.has(normPath)) continue;
1257
+
1258
+ let methodMap = routes[normPath];
1259
+ if (!methodMap) {
1260
+ methodMap = {};
1261
+ routes[normPath] = methodMap;
1262
+ }
1263
+
1264
+ if (isProd && isPureStaticStringFn(rawHandler)) {
1265
+ methodMap[route.method] = new Response(rawHandler());
1266
+ count++;
1267
+ continue;
1268
+ }
1269
+
1270
+ if (isProd && isTrulyZeroArg(rawHandler)) {
1271
+ const isAsync = rawHandler.constructor?.name === 'AsyncFunction';
1272
+ methodMap[route.method] = isAsync
1273
+ ? () => {
1274
+ try {
1275
+ const out = rawHandler();
1276
+ if (out && typeof out.then === 'function') {
1277
+ return out.then(toZeroArgResponse, zeroArgErrorRes);
1278
+ }
1279
+ return toZeroArgResponse(out);
1280
+ } catch (e) {
1281
+ return zeroArgErrorRes(e);
1282
+ }
1283
+ }
1284
+ : () => {
1285
+ try {
1286
+ const out = rawHandler();
1287
+ if (typeof out === 'string') return new Response(out);
1288
+ if (out instanceof Response) return out;
1289
+ if (out && typeof out.then === 'function') {
1290
+ return out.then(toZeroArgResponse, zeroArgErrorRes);
1291
+ }
1292
+ return Response.json(out ?? null);
1293
+ } catch (e) {
1294
+ return zeroArgErrorRes(e);
1295
+ }
1296
+ };
1297
+ count++;
1298
+ continue;
1299
+ }
1300
+
1301
+ const compiledFn = this.compileHandler([rawHandler], false);
1302
+ const hasParams = normPath.includes(':');
1303
+ methodMap[route.method] = (req: any) => {
1304
+ let ctx: Context;
1305
+ if (poolState.top > 0) {
1306
+ const slot = --poolState.top;
1307
+ ctx = pool[slot]!;
1308
+ pool[slot] = undefined;
1309
+ } else {
1310
+ ctx = new Context(false);
1311
+ }
1312
+ ctx.req = req;
1313
+ if (hasParams) ctx.params = req.params;
1314
+ try {
1315
+ const out = compiledFn(ctx);
1316
+ if (out && typeof out.then === 'function') {
1317
+ return out.then(
1318
+ (v: Response) => {
1319
+ ctx.reset(undefined as any);
1320
+ if (poolState.top < maxPool) pool[poolState.top++] = ctx;
1321
+ return v;
1322
+ },
1323
+ (e: any) => {
1324
+ ctx.reset(undefined as any);
1325
+ if (poolState.top < maxPool) pool[poolState.top++] = ctx;
1326
+ return zeroArgErrorRes(e);
1327
+ }
1328
+ );
1329
+ }
1330
+ ctx.reset(undefined as any);
1331
+ if (poolState.top < maxPool) pool[poolState.top++] = ctx;
1332
+ return out;
1333
+ } catch (e) {
1334
+ ctx.reset(undefined as any);
1335
+ if (poolState.top < maxPool) pool[poolState.top++] = ctx;
1336
+ return zeroArgErrorRes(e);
1337
+ }
1338
+ };
1339
+ count++;
1340
+ }
1341
+
1342
+ return count > 0 ? routes : undefined;
1343
+ }
1344
+
1191
1345
  public listen(
1192
1346
  port?: number,
1193
1347
  hostname: string = '0.0.0.0',
@@ -1220,12 +1374,14 @@ export class BareJS<
1220
1374
  const wsRoutes = this.wsRoutes;
1221
1375
  const self = this;
1222
1376
  const hasWs = wsRoutes.size > 0;
1377
+ const bunRoutes = runtime.name === 'bun' ? this.buildBunRoutes() : undefined;
1223
1378
 
1224
1379
  const server = runtime.serve({
1225
1380
  port: finalPort,
1226
1381
  hostname,
1227
1382
  reusePort,
1228
1383
  maxRequestBodySize,
1384
+ routes: bunRoutes,
1229
1385
  fetch(req: Request, peerIp?: string) {
1230
1386
  return self.fetch(req, peerIp);
1231
1387
  },
@@ -10,12 +10,14 @@ export const bunDriver: RuntimeDriver = {
10
10
 
11
11
  serve(opts: ServeOptions): ServerHandle {
12
12
  const wsCfg = opts.ws;
13
+ const routes = opts.routes;
13
14
  const server = wsCfg
14
15
  ? Bun.serve<WebSocketRouteHandler>({
15
16
  port: opts.port,
16
17
  hostname: opts.hostname,
17
18
  reusePort: opts.reusePort,
18
19
  maxRequestBodySize: opts.maxRequestBodySize,
20
+ ...(routes ? { routes } : {}),
19
21
  fetch(req: Request, srv: any) {
20
22
  if (req.headers.get('upgrade')?.toLowerCase() === 'websocket') {
21
23
  const matched = matchWsRoute(wsCfg.routes, req.url);
@@ -37,6 +39,7 @@ export const bunDriver: RuntimeDriver = {
37
39
  hostname: opts.hostname,
38
40
  reusePort: opts.reusePort,
39
41
  maxRequestBodySize: opts.maxRequestBodySize,
42
+ ...(routes ? { routes } : {}),
40
43
  fetch(req: Request, srv: any) {
41
44
  return opts.fetch(req, srv?.requestIP?.(req)?.address);
42
45
  }
@@ -3,7 +3,7 @@ import { createServer, type IncomingMessage, type ServerResponse } from 'node:ht
3
3
  import { createReadStream } from 'node:fs';
4
4
  import { extname } from 'node:path';
5
5
  import { Readable } from 'node:stream';
6
- import { gzipSync } from 'node:zlib';
6
+ import * as zlib from 'node:zlib';
7
7
  import type { RuntimeDriver, RuntimeFileHandle, RuntimePasswordConfig, ServeOptions, ServerHandle } from './types';
8
8
  import { matchWsRoute } from '../core/ws-match';
9
9
 
@@ -452,27 +452,47 @@ export const nodeDriver: RuntimeDriver = {
452
452
  }
453
453
  server.listen(listenOpts);
454
454
 
455
- const addr = server.address();
456
- const boundPort = typeof addr === 'object' && addr ? addr.port : opts.port;
455
+ const ready = new Promise<void>((resolve) => {
456
+ if (server.listening) resolve();
457
+ else server.once('listening', () => resolve());
458
+ });
459
+
460
+ const stopFn = (closeActiveConnections = false) =>
461
+ new Promise<void>((resolve) => {
462
+ if (closeActiveConnections && typeof (server as any).closeAllConnections === 'function') {
463
+ (server as any).closeAllConnections();
464
+ }
465
+ server.close(() => resolve());
466
+ });
467
+
468
+ Object.defineProperty(server, 'port', {
469
+ get() {
470
+ const a = server.address();
471
+ return typeof a === 'object' && a ? a.port : opts.port;
472
+ },
473
+ configurable: true
474
+ });
475
+ (server as any).stop = stopFn;
476
+ (server as any).ready = ready;
457
477
 
458
478
  return {
459
- stop(closeActiveConnections = false) {
460
- return new Promise<void>((resolve) => {
461
- if (closeActiveConnections && typeof (server as any).closeAllConnections === 'function') {
462
- (server as any).closeAllConnections();
463
- }
464
- server.close(() => resolve());
465
- });
479
+ stop: stopFn,
480
+ get port() {
481
+ const a = server.address();
482
+ return typeof a === 'object' && a ? a.port : opts.port;
466
483
  },
467
- port: boundPort,
468
484
  raw: server
469
485
  };
470
486
  },
471
487
 
472
488
  gzip(data: Uint8Array, level: number): Uint8Array {
473
- return new Uint8Array(gzipSync(data, { level }));
489
+ return new Uint8Array(zlib.gzipSync(data, { level }));
474
490
  },
475
491
 
492
+ zstd: typeof (zlib as any).zstdCompressSync === 'function'
493
+ ? (data: Uint8Array): Uint8Array => new Uint8Array((zlib as any).zstdCompressSync(data))
494
+ : undefined,
495
+
476
496
  openFile(path: string): RuntimeFileHandle {
477
497
  const ext = extname(path).toLowerCase();
478
498
  const mime = MIME_MAP[ext] || 'application/octet-stream';
@@ -6,6 +6,7 @@ export interface ServeOptions {
6
6
  reusePort: boolean;
7
7
  maxRequestBodySize: number;
8
8
  fetch: (req: Request, peerIp?: string) => Response | Promise<Response>;
9
+ routes?: Record<string, any>;
9
10
  ws?: {
10
11
  routes: Map<string, WebSocketRouteHandler>;
11
12
  adapter: {
@@ -4,6 +4,7 @@ import { runtime } from '../runtime';
4
4
 
5
5
  export const Hash = {
6
6
  make: (data: string): Promise<string> => {
7
+ if (!data) return Promise.reject(new Error('Password cannot be empty'));
7
8
  return runtime.password.hash(data, BARE_CONFIG.hash);
8
9
  },
9
10
 
@@ -25,6 +26,9 @@ export const Hash = {
25
26
  const expectedCost = Math.max(4, Math.min(31, timeCost));
26
27
  return !costMatch || Number(costMatch[1]) !== expectedCost;
27
28
  }
29
+ if (hash.startsWith('$scrypt$')) {
30
+ return !hash.startsWith('$scrypt$N=16384,r=8,p=1$');
31
+ }
28
32
  if (!hash.startsWith(`$${algorithm}$`)) return true;
29
33
  const mMatch = hash.match(/(?:^|[,$])m=(\d+)(?:[,$]|$)/);
30
34
  const tMatch = hash.match(/(?:^|[,$])t=(\d+)(?:[,$]|$)/);