barejs 0.1.57 → 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,18 +4,15 @@ 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 };
9
+ export declare function normalizePoolSize(poolSize: number, defaultSize?: number, maximumSize?: number): number;
7
10
  export interface CronOptions {
8
11
  /** Execute the cron job immediately upon registration (default: false) */
9
12
  runOnStart?: boolean;
10
13
  /** Optional error handler when the cron callback throws or rejects */
11
14
  onError?: (err: any) => void;
12
15
  }
13
- export interface WebSocketRouteHandler {
14
- open?: (ws: any) => void;
15
- message?: (ws: any, message: string | Buffer) => void;
16
- close?: (ws: any, code: number, reason: string) => void;
17
- drain?: (ws: any) => void;
18
- }
19
16
  export interface NotFoundResponse {
20
17
  status: number;
21
18
  message: string;
@@ -64,27 +61,41 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
64
61
  readonly __routes: Routes;
65
62
  private tree;
66
63
  private pool;
64
+ private readonly _poolState;
65
+ private readonly maxPool;
67
66
  private hotFetch?;
68
67
  private compiled;
69
68
  private _useLog;
70
69
  private _trustProxyBox;
70
+ protected _onRouteMutate(): void;
71
71
  private errorHandler?;
72
72
  private wsRoutes;
73
73
  private startHooks;
74
74
  private stopHooks;
75
+ private drainHooks;
75
76
  private crons;
76
77
  private server?;
77
78
  private shutdownHandler?;
79
+ private ipcDrainHandler?;
80
+ private _draining;
78
81
  private wsAdapter;
79
82
  useLog(enabled?: boolean): this;
80
83
  onStart(fn: () => void | Promise<void>): this;
81
84
  onStop(fn: () => void | Promise<void>): this;
85
+ onDrain(fn: () => void | Promise<void>): this;
86
+ /**
87
+ * Gracefully drains the server by running all onDrain hooks and stopping
88
+ * the server while allowing in-flight requests to complete.
89
+ */
90
+ drain(closeActiveConnections?: boolean): Promise<void>;
82
91
  /**
83
92
  * Built-in overlap-safe background interval scheduler.
84
93
  * Automatically cleared when app.stop() is called.
85
94
  */
86
95
  cron(name: string, intervalMs: number, fn: () => void | Promise<void>, options?: CronOptions): this;
87
96
  stop(closeActiveConnections?: boolean): Promise<void>;
97
+ private static readonly DEFAULT_POOL_SIZE;
98
+ private static readonly MAX_POOL_SIZE;
88
99
  constructor(poolSize?: number);
89
100
  private notFoundHandler;
90
101
  setNotFound(handler: () => NotFoundResponse): void;
@@ -113,6 +124,7 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
113
124
  derive<T extends Record<string, any>>(fn: (ctx: Context & Derived) => Promise<T> | T): BareJS<Derived & T, Routes>;
114
125
  private compileHandler;
115
126
  compile(): void;
127
+ private readonly _lazyFetch;
116
128
  fetch: (req: Request, peerIp?: string) => any;
117
129
  /**
118
130
  * Ergonomic in-memory request helper for testing or internal invocations.
@@ -124,6 +136,6 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
124
136
  listen(port?: number, hostname?: string, reusePort?: boolean, options?: {
125
137
  maxRequestBodySize?: number;
126
138
  trustProxy?: boolean;
127
- }): Bun.Server<WebSocketRouteHandler> | Bun.Server<undefined>;
139
+ }): any;
128
140
  }
129
141
  export { Context, typebox, t };
@@ -34,6 +34,25 @@ export interface UploadResult {
34
34
  fields: Record<string, string>;
35
35
  files: UploadedFile[];
36
36
  }
37
+ export interface UploadStreamOptions {
38
+ /** Max size per file in bytes (default: 100MB) */
39
+ maxFileSize?: number;
40
+ /** Max number of uploaded files (default: 10) */
41
+ maxFiles?: number;
42
+ /** Max size per text field in bytes (default: 1MB) */
43
+ maxFieldSize?: number;
44
+ /** Allowed MIME types (e.g. ['image/png', 'application/octet-stream']) */
45
+ allowedTypes?: string[];
46
+ }
47
+ export interface UploadStreamPart {
48
+ type: 'file' | 'field';
49
+ fieldName: string;
50
+ filename?: string;
51
+ safeName?: string;
52
+ contentType?: string;
53
+ stream?: ReadableStream<Uint8Array>;
54
+ value?: string;
55
+ }
37
56
  export declare class Context {
38
57
  req: Request;
39
58
  params: Params;
@@ -82,4 +101,9 @@ export declare class Context {
82
101
  get requestId(): string;
83
102
  get ip(): string;
84
103
  upload(options?: UploadOptions): Promise<UploadResult>;
104
+ /**
105
+ * True streaming multipart/form-data parser.
106
+ * Streams file parts chunk-by-chunk with backpressure and constant O(chunk) memory usage.
107
+ */
108
+ uploadStream(options?: UploadStreamOptions): AsyncGenerator<UploadStreamPart>;
85
109
  }
@@ -60,6 +60,7 @@ export declare class BareRouter<Routes extends RouteSchema = {}> {
60
60
  groupMiddleware: any[];
61
61
  readonly __routes: Routes;
62
62
  routes: any[];
63
+ protected _onRouteMutate?(): void;
63
64
  constructor(prefix?: string, groupMiddleware?: any[]);
64
65
  protected _add(method: string, path: string, handlers: HandlersChain): this;
65
66
  get: AddRouterRoute<Routes, 'GET'>;
@@ -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;
@@ -4,7 +4,7 @@
4
4
  * Built for Bun with Mechanical Sympathy
5
5
  * Optimized to outperform competitors by 55% [2026-01-05]
6
6
  */
7
- export { BareJS, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
7
+ export { BareJS, normalizePoolSize, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
8
8
  export { BareRouter, type InferSchema, type PrefixRoutes } from './core/router';
9
9
  /**
10
10
  * Plugin Interface for BareJS
@@ -13,7 +13,7 @@ export interface BarePlugin {
13
13
  install: (app: any) => void;
14
14
  }
15
15
  export { Context } from './core/context';
16
- export type { Middleware, Handler, Next, Params, AuthUser, CookieOptions, UploadOptions, UploadedFile, UploadResult } from './core/context';
16
+ export type { Middleware, Handler, Next, Params, AuthUser, CookieOptions, UploadOptions, UploadedFile, UploadResult, UploadStreamOptions, UploadStreamPart } from './core/context';
17
17
  import { Type } from "@sinclair/typebox";
18
18
  export { Type, Type as T, Type as TypeBox };
19
19
  import { typebox, zod, native, validate, schemaValidator, createResponseFilter, Z, type RouteSchemas, type RouteDetail } from './security/validators';
@@ -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,11 +1,12 @@
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 (401 tests / 6,129 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
+ // 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)
9
10
  const app = new BareJS();
10
11
 
11
12
  // Direct return (Elysia style — auto-detects JSON, text, or Response)
@@ -15,7 +16,7 @@ app.get('/ping', () => 'pong');
15
16
  // Wildcard catch-all route (`ctx.params['*']`)
16
17
  app.get('/files/*', (ctx: Context) => ({ filePath: ctx.params['*'] }));
17
18
 
18
- app.listen(3000);
19
+ app.listen(3000); // Or on Deno: Deno.serve({ port: 3000 }, (req, info) => app.fetch(req, info.remoteAddr.hostname));
19
20
  ```
20
21
 
21
22
  ## 2. Routing, Plugins & Unified Schema Validation
@@ -56,6 +57,7 @@ const typedApp = app.route('/api/v1', api); // or app.use('/api/v1', api)
56
57
  - `ctx.query` / `ctx.getQuery(key)` / `ctx.queryAll(key)`: Lazy, prototype-pollution-safe query parser (fast-path when no `%` or `+`) with repeated query key support.
57
58
  - `await ctx.jsonBody(maxBytes = 1048576)`: Cached JSON body parser with native fast-path and `413` DoS limit.
58
59
  - `await ctx.upload({ maxFileSize, maxFiles, allowedTypes })`: Safe `multipart/form-data` parser; returns `{ fields, files }` with `safeName` (sanitized against path traversal) and enforces `413` (size/count) and `415` (MIME type).
60
+ - `ctx.uploadStream({ maxFileSize, maxFiles, maxFieldSize, allowedTypes })`: True streaming `multipart/form-data` async generator yielding `{ type: 'field', fieldName, value }` and `{ type: 'file', fieldName, filename, safeName, contentType, stream }` (`ReadableStream<Uint8Array>`, $O(\text{chunk})$ memory).
59
61
  - `ctx.cookies`: Lazy parsed request cookies (`Record<string, string>`).
60
62
  - `await ctx.setCookie(name, value, { secret?, httpOnly?, sameSite?, secure?, maxAge?, expires?, domain?, path? })`: Defaults to `HttpOnly; SameSite=Lax; Path=/`. Pass `secret` for HMAC-SHA256 signing.
61
63
  - `await ctx.getSignedCookie(name, secret)`: Verifies HMAC signature with `timingSafeEqual`; returns `null` if tampered or missing.
@@ -129,6 +131,7 @@ app.get('/sso', bareAuth({ algorithms: ['RS256', 'ES256'], jwksUri: 'https://aut
129
131
  ## 7. Lifecycle & Error Handling
130
132
  ```ts
131
133
  app.onStart(() => console.log('Server started'));
134
+ app.onDrain(async () => console.log('Draining...')); // Also triggered by IPC DRAIN_REQUEST
132
135
  app.onStop(async () => await db.close());
133
136
  app.onError((err, ctx) => ctx.status(err.status || 500).json({ error: err.message, requestId: ctx.requestId }));
134
137
  app.setNotFound(() => ({ status: 404, message: 'Custom Not Found' }));
package/package.json CHANGED
@@ -1,18 +1,28 @@
1
1
  {
2
2
  "name": "barejs",
3
- "version": "0.1.57",
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": {