barejs 0.1.49 → 0.1.50

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.
@@ -42,7 +42,9 @@ export interface BareClient<Routes extends RouteSchema = RouteSchema> {
42
42
  params?: ExtractParams<P & string>;
43
43
  } : {})): Promise<P extends keyof Routes ? Routes[P]['response'] : any>;
44
44
  }
45
- export declare const bareClient: <AppOrRoutes = any>(baseUrl: string, clientOptions?: BareClientOptions) => BareClient<AppOrRoutes extends {
45
+ export declare const bareClient: <AppOrRoutes = any>(baseUrlOrApp: string | {
46
+ fetch: (req: Request) => any;
47
+ }, clientOptions?: BareClientOptions) => BareClient<AppOrRoutes extends {
46
48
  __routes?: infer R extends RouteSchema;
47
49
  } ? R : RouteSchema>;
48
50
  export {};
@@ -22,7 +22,15 @@ export declare class BareJS extends BareRouter {
22
22
  private _useLog;
23
23
  private errorHandler?;
24
24
  private wsRoutes;
25
+ private startHooks;
26
+ private stopHooks;
27
+ private server?;
28
+ private shutdownHandler?;
29
+ private wsAdapter;
25
30
  useLog(enabled?: boolean): this;
31
+ onStart(fn: () => void | Promise<void>): this;
32
+ onStop(fn: () => void | Promise<void>): this;
33
+ stop(closeActiveConnections?: boolean): Promise<void>;
26
34
  constructor(poolSize?: number);
27
35
  private notFoundHandler;
28
36
  setNotFound(handler: () => NotFoundResponse): void;
@@ -30,6 +38,8 @@ export declare class BareJS extends BareRouter {
30
38
  ws(path: string, handler: WebSocketRouteHandler): this;
31
39
  docs(path?: string, options?: OpenAPIOptions): this;
32
40
  rpc(path: string, procedures: Record<string, (params: any, ctx: Context) => any>): this;
41
+ private _hasDerive;
42
+ derive<T extends Record<string, any>>(fn: (ctx: Context) => Promise<T> | T): this;
33
43
  private compileHandler;
34
44
  compile(): void;
35
45
  fetch: (req: Request) => any;
@@ -4,6 +4,36 @@ export type Middleware = (ctx: Context, next: Next) => Promise<any> | any;
4
4
  export type Handler = (ctx: Context) => Promise<any> | any;
5
5
  export type GroupCallback = (router: any) => void;
6
6
  export type AuthUser = Record<string, any>;
7
+ export interface CookieOptions {
8
+ httpOnly?: boolean;
9
+ secure?: boolean;
10
+ sameSite?: 'Strict' | 'Lax' | 'None';
11
+ path?: string;
12
+ domain?: string;
13
+ maxAge?: number;
14
+ expires?: Date;
15
+ secret?: string;
16
+ }
17
+ export interface UploadOptions {
18
+ /** Max size per file in bytes (default: 5MB) */
19
+ maxFileSize?: number;
20
+ /** Max number of uploaded files (default: 10) */
21
+ maxFiles?: number;
22
+ /** Allowed MIME types (e.g. ['image/png', 'image/jpeg', 'application/pdf']) */
23
+ allowedTypes?: string[];
24
+ }
25
+ export interface UploadedFile {
26
+ fieldName: string;
27
+ filename: string;
28
+ safeName: string;
29
+ type: string;
30
+ size: number;
31
+ file: File;
32
+ }
33
+ export interface UploadResult {
34
+ fields: Record<string, string>;
35
+ files: UploadedFile[];
36
+ }
7
37
  export declare class Context {
8
38
  req: Request;
9
39
  params: Params;
@@ -12,21 +42,35 @@ export declare class Context {
12
42
  store: Map<string, any>;
13
43
  body: any;
14
44
  _query: Record<string, string> | undefined;
45
+ _cookies: Record<string, string> | undefined;
46
+ _setCookies: string[] | undefined;
47
+ _requestId: string | undefined;
15
48
  constructor();
16
49
  get query(): Record<string, string>;
17
50
  getQuery(key: string): string | undefined;
18
- jsonBody(): Promise<any>;
51
+ get cookies(): Record<string, string>;
52
+ setCookie(name: string, value: string, options?: CookieOptions): this;
53
+ getSignedCookie(name: string, secret: string): string | null;
54
+ deleteCookie(name: string, options?: Pick<CookieOptions, 'path' | 'domain'>): this;
55
+ jsonBody(maxBytes?: number): Promise<any>;
19
56
  reset(req: Request): this;
20
57
  status(code: number): this;
21
58
  json(data: any): Response;
22
59
  set(key: string, value: any): this;
23
60
  get(key: string): any;
24
61
  setHeader(name: string, value: string): this;
62
+ get user(): AuthUser | undefined;
25
63
  send(message: string, extra?: Record<string, any>): Response;
64
+ html(content: string, status?: number): Response;
65
+ text(content: string, status?: number): Response;
66
+ redirect(url: string, status?: number): Response;
26
67
  sse(source: AsyncIterable<string | {
27
68
  event?: string;
28
69
  data: any;
29
70
  id?: string;
30
71
  retry?: number;
31
72
  }> | ((send: (data: any, event?: string, id?: string) => void, close: () => void) => Promise<void> | void)): Response;
73
+ get requestId(): string;
74
+ get ip(): string;
75
+ upload(options?: UploadOptions): Promise<UploadResult>;
32
76
  }
@@ -4,6 +4,7 @@ export declare class RadixNode {
4
4
  staticKeys: string[];
5
5
  paramNode: RadixNode | null;
6
6
  paramName: string | null;
7
+ wildcardNode: RadixNode | null;
7
8
  handlers: Record<string, Function>;
8
9
  insert(path: string, method: string, handler: Function): void;
9
10
  lookup(method: string, url: string, start: number, ctx: Context): Function | null;
@@ -1,5 +1,6 @@
1
1
  import { type Middleware, type Handler } from '../core/context';
2
- type HandlersChain = (Middleware | Handler)[];
2
+ import { type RouteSchemas } from '../security/validators';
3
+ type HandlersChain = (Middleware | Handler | RouteSchemas)[];
3
4
  export declare class BareRouter {
4
5
  prefix: string;
5
6
  groupMiddleware: any[];
@@ -11,15 +11,19 @@ export { BareJS, type WebSocketRouteHandler } from './core/bare';
11
11
  export interface BarePlugin {
12
12
  install: (app: any) => void;
13
13
  }
14
- export type { Middleware, Handler, Next, Context, Params, AuthUser } from './core/context';
14
+ export { Context } from './core/context';
15
+ export type { Middleware, Handler, Next, Params, AuthUser, CookieOptions, UploadOptions, UploadedFile, UploadResult } from './core/context';
15
16
  import { Type } from "@sinclair/typebox";
16
17
  export { Type, Type as T, Type as TypeBox };
17
- import { typebox, zod, native, validate, Z } from './security/validators';
18
- export { typebox, typebox as t, zod, zod as z, Z, Z as Zod, native, native as n, validate, validate as v };
18
+ import { typebox, zod, native, validate, schemaValidator, createResponseFilter, Z, type RouteSchemas, type RouteDetail } from './security/validators';
19
+ export { typebox, typebox as t, zod, zod as z, Z, Z as Zod, native, native as n, validate, validate as v, schemaValidator, createResponseFilter, type RouteSchemas, type RouteDetail };
19
20
  export { cors } from './security/cors';
21
+ export { csrf, type CsrfOptions } from './security/csrf';
22
+ export { timeout, type TimeoutOptions } from './security/timeout';
20
23
  export { rateLimit, type RateLimitOptions } from './security/rateLimit';
24
+ export { idempotency, createSingleflight, type IdempotencyOptions } from './security/idempotency';
21
25
  export { securityHeaders, type SecurityHeadersOptions } from './security/headers';
22
- export { staticFile } from './utils/static';
26
+ export { staticFile, type StaticOptions } from './utils/static';
23
27
  export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
24
28
  export { BareRouter } from './core/router';
25
29
  export { bareAuth, createToken, basicAuth, hasRole } from './security/auth';
@@ -7,7 +7,9 @@ export declare const createToken: (payload: object, secret: string) => Promise<s
7
7
  * 1. BARE TOKEN AUTH (Standard JWT Middleware)
8
8
  * High-performance, constant-time JWT middleware for BareJS
9
9
  */
10
- export declare const bareAuth: (secret: string) => (ctx: any, next: any) => any;
10
+ export declare const bareAuth: (secretOrOpts: string | {
11
+ secret: string;
12
+ }) => (ctx: any, next: any) => any;
11
13
  /**
12
14
  * 2. BASIC AUTH
13
15
  * Useful for internal tools and simple admin panels
@@ -1,5 +1,9 @@
1
1
  import type { Middleware } from '../core/context';
2
- export declare const cors: (options?: {
3
- origin?: string;
2
+ export interface CorsOptions {
3
+ origin?: string | string[] | ((origin: string) => boolean);
4
4
  methods?: string;
5
- }) => Middleware;
5
+ credentials?: boolean;
6
+ allowedHeaders?: string | string[];
7
+ exposedHeaders?: string | string[];
8
+ }
9
+ export declare const cors: (options?: CorsOptions) => Middleware;
@@ -0,0 +1,12 @@
1
+ import type { Middleware } from '../core/context';
2
+ export interface CsrfOptions {
3
+ /** Allowed origins for state-changing requests (defaults to same-origin matching request Host) */
4
+ allowedOrigins?: string[];
5
+ /** HTTP methods exempt from CSRF checks (default: ['GET', 'HEAD', 'OPTIONS']) */
6
+ ignoreMethods?: string[];
7
+ /** Optional cookie + header double-submit check */
8
+ cookieName?: string;
9
+ headerName?: string;
10
+ requireToken?: boolean;
11
+ }
12
+ export declare const csrf: (options?: CsrfOptions) => Middleware;
@@ -0,0 +1,22 @@
1
+ import type { Middleware } from '../core/context';
2
+ export interface IdempotencyOptions {
3
+ /** Header name (default: 'idempotency-key') */
4
+ headerName?: string;
5
+ /** Cache TTL in milliseconds (default: 300_000 = 5 minutes) */
6
+ ttlMs?: number;
7
+ /** Maximum cached keys before LRU eviction (default: 10_000) */
8
+ maxKeys?: number;
9
+ }
10
+ /**
11
+ * Payment & Order Double-Charge Protection Middleware (Idempotency-Key).
12
+ * Prevents duplicate state-changing executions and concurrent race conditions.
13
+ */
14
+ export declare const idempotency: (options?: IdempotencyOptions) => Middleware;
15
+ /**
16
+ * Singleflight Helper for Thundering-Herd / Cache-Stampede Protection.
17
+ * Coalesces N concurrent identical async calls into 1 underlying execution.
18
+ */
19
+ export declare const createSingleflight: () => <T>(key: string, fn: () => Promise<T>) => Promise<{
20
+ data: T;
21
+ shared: boolean;
22
+ }>;
@@ -0,0 +1,6 @@
1
+ import type { Middleware } from '../core/context';
2
+ export interface TimeoutOptions {
3
+ status?: number;
4
+ message?: string;
5
+ }
6
+ export declare const timeout: (ms?: number, options?: TimeoutOptions) => Middleware;
@@ -24,3 +24,19 @@ export declare const zod: (schema: z.ZodSchema) => Middleware;
24
24
  */
25
25
  export declare const validate: (schema: any) => Middleware;
26
26
  export { typebox as t, zod as z, native as n, validate as v };
27
+ export interface RouteDetail {
28
+ summary?: string;
29
+ description?: string;
30
+ tags?: string[];
31
+ }
32
+ export interface RouteSchemas {
33
+ body?: any;
34
+ query?: any;
35
+ params?: any;
36
+ headers?: any;
37
+ response?: any;
38
+ detail?: RouteDetail;
39
+ maxBodySize?: number;
40
+ }
41
+ export declare const createResponseFilter: (schema: any) => ((val: any) => any);
42
+ export declare const schemaValidator: (schemas: RouteSchemas) => Middleware;
@@ -1 +1,5 @@
1
- export declare const staticFile: (root?: string) => (ctx: any, next: any) => Promise<any>;
1
+ export interface StaticOptions {
2
+ maxAge?: number;
3
+ etag?: boolean;
4
+ }
5
+ export declare const staticFile: (root?: string, options?: StaticOptions) => (ctx: any, next: any) => Promise<any>;
package/llms.txt ADDED
@@ -0,0 +1,138 @@
1
+ # BareJS (`barejs`) — AI Quick Reference (`llms.txt`)
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, Idempotency-Key double-charge protection, Singleflight request coalescing, Security Headers, DoS body/upload limits, Prototype Pollution guards) and **100% Function & Line Test Coverage (209 tests / 2,878 assertions)**.
4
+
5
+ ## 1. Installation & Minimal App
6
+ ```ts
7
+ import { BareJS, Context, Type } from 'barejs';
8
+
9
+ const app = new BareJS();
10
+
11
+ // Direct return (Elysia style — auto-detects JSON, text, or Response)
12
+ app.get('/hello/:name', (ctx: Context) => ({ hello: ctx.params.name }));
13
+ app.get('/ping', () => 'pong');
14
+
15
+ // Wildcard catch-all route (`ctx.params['*']`)
16
+ app.get('/files/*', (ctx: Context) => ({ filePath: ctx.params['*'] }));
17
+
18
+ app.listen(3000);
19
+ ```
20
+
21
+ ## 2. Routing, Plugins & Unified Schema Validation
22
+ Methods: `app.get`, `app.post`, `app.put`, `app.patch`, `app.delete`, `app.options`, `app.useAll`, `app.group(prefix, fn)`, `app.use(mwOrRouterOrPlugin)`.
23
+ Pass a `RouteSchemas` object directly before the handler for AOT-compiled validation + auto-coercion (`number`/`integer`/`boolean` on `query` & `params`):
24
+ ```ts
25
+ app.post('/users/:id', {
26
+ detail: { summary: 'Update user', description: 'Updates user profile', tags: ['Users'] },
27
+ params: Type.Object({ id: Type.Integer() }),
28
+ query: Type.Object({ active: Type.Optional(Type.Boolean()) }),
29
+ headers: Type.Object({ 'x-client': Type.Optional(Type.String()) }),
30
+ body: Type.Object({ name: Type.String({ minLength: 1 }) }),
31
+ response: Type.Object({ id: Type.Number(), name: Type.String() }), // Recursive JIT projector auto-strips undeclared fields (e.g. password_hash)!
32
+ maxBodySize: 1024 * 1024 // default 1MB (returns 413 on overflow)
33
+ }, (ctx: Context) => ({
34
+ id: ctx.params.id, // auto-coerced to number
35
+ active: ctx.query.active, // auto-coerced to boolean
36
+ name: ctx.body.name,
37
+ password_hash: 'secret' // automatically stripped before sending to client!
38
+ }));
39
+ ```
40
+ Supports **TypeBox** (`Type`, `t`), **Zod** (`Z`, `z`), or **Native** (`native({ properties: { a: { type: 'string' }, b: { type: 'number' } }, required: ['a'] })`).
41
+
42
+ ### Modular Routers & Plugins
43
+ ```ts
44
+ // Sub-router
45
+ const api = new BareRouter();
46
+ api.get('/items', () => []);
47
+ app.use('/api/v1', api);
48
+
49
+ // Reusable Plugin
50
+ app.use({
51
+ name: 'metrics-plugin',
52
+ install(app) {
53
+ app.get('/metrics', () => ({ uptime: process.uptime() }));
54
+ }
55
+ });
56
+ ```
57
+
58
+ ## 3. Context (`ctx`) Complete API
59
+ - `ctx.req`: Raw incoming Bun `Request`.
60
+ - `ctx.params`: Route params (`Record<string, any>`, including `ctx.params['*']` for wildcards).
61
+ - `ctx.query` / `ctx.getQuery(key)`: Lazy, prototype-pollution-safe query parser (fast-path when no `%` or `+`).
62
+ - `await ctx.jsonBody(maxBytes = 1048576)`: Cached JSON body parser with native fast-path and `413` DoS limit.
63
+ - `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).
64
+ - `ctx.cookies`: Lazy parsed request cookies (`Record<string, string>`).
65
+ - `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.
66
+ - `await ctx.getSignedCookie(name, secret)`: Verifies HMAC signature with `timingSafeEqual`; returns `null` if tampered or missing.
67
+ - `ctx.deleteCookie(name, opts?)`: Expires cookie immediately (`Max-Age=0`).
68
+ - `ctx.requestId`: Lazy `x-request-id` header or generated `crypto.randomUUID()`.
69
+ - `ctx.ip`: Client IP extracted from `x-forwarded-for`, `x-real-ip`, `cf-connecting-ip`, or `'127.0.0.1'`.
70
+ - `ctx.user`: Authenticated user payload populated by `bareAuth` or `basicAuth`.
71
+ - `ctx.store` / `ctx.set(k, v)` / `ctx.get(k)`: Per-request `Map<string, any>` (automatically cleared on pool release).
72
+ - **Response Helpers (Hono / Express style):**
73
+ - `ctx.status(code)` (chainable)
74
+ - `ctx.setHeader(name, val)` (chainable, copy-on-write safe)
75
+ - `ctx.json(data)` -> `application/json`
76
+ - `ctx.send(message, extra?)` -> `{ status: 'success' | 'error', msg: message, ...extra }`
77
+ - `ctx.html(html, status?)` -> `text/html; charset=utf-8`
78
+ - `ctx.text(text, status?)` -> `text/plain; charset=utf-8`
79
+ - `ctx.redirect(url, status = 302)` -> `Location: url`
80
+ - `ctx.sse(async (send, close) => { send(data, event?, id?); })` or `ctx.sse(asyncIterable)` -> `text/event-stream`
81
+
82
+ ## 4. Context Enrichment (`app.derive`)
83
+ ```ts
84
+ const derivedApp = app.derive((ctx) => ({
85
+ requestTime: Date.now(),
86
+ tenant: ctx.req.headers.get('x-tenant') || 'public'
87
+ }));
88
+ ```
89
+ Derived properties are attached directly onto `ctx` with TypeScript inference (`Bare<Derived>`) and automatically cleaned up when `Context` returns to the pool.
90
+
91
+ ## 5. Built-in Security Middlewares, Idempotency & Singleflight
92
+ ```ts
93
+ import {
94
+ cors, csrf, timeout, rateLimit, securityHeaders,
95
+ idempotency, createSingleflight,
96
+ bareAuth, createToken, basicAuth, hasRole, Hash, staticFile
97
+ } from 'barejs';
98
+
99
+ app.use(securityHeaders());
100
+ app.use(cors({ origin: ['https://app.example.com'], credentials: true }));
101
+ app.use(csrf({ allowedOrigins: ['https://app.example.com'], requireToken: true }));
102
+ app.use(timeout(10_000, { status: 408, message: 'Timed out' }));
103
+ app.use(rateLimit({ windowMs: 60_000, max: 100 }));
104
+ app.use(staticFile('public', { maxAge: 3600, etag: true })); // ETag, 304, Range 206/416, HEAD
105
+
106
+ // Idempotency-Key double-charge & race condition guard (409 IDEMPOTENT_IN_FLIGHT + X-Idempotent-Replayed: true)
107
+ app.post('/pay', idempotency({ ttlMs: 86_400_000, maxKeys: 10_000 }), (ctx) => ({ paid: true }));
108
+
109
+ // Thundering-herd / Cache-stampede request coalescer
110
+ const sf = createSingleflight();
111
+ app.get('/report', () => sf.do('report-key', async () => ({ total: 100 })));
112
+
113
+ // Auth & Hashing
114
+ const hash = await Hash.make('password'); // Argon2id (64MB default)
115
+ const ok = await Hash.verify('password', hash);
116
+ const token = await createToken({ id: 1, role: 'admin', exp: Math.floor(Date.now() / 1000) + 3600 }, process.env.JWT_SECRET!);
117
+
118
+ // bareAuth accepts either secret string or { secret } object
119
+ app.get('/admin', bareAuth(process.env.JWT_SECRET!), hasRole('admin'), (ctx) => ctx.user);
120
+ ```
121
+
122
+ ## 6. Real-Time, RPC, OpenAPI & Client
123
+ - **WebSocket**: `app.ws('/ws/chat', { open(ws){}, message(ws, msg){}, close(ws){}, drain(ws){} })`
124
+ - **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)
125
+ - **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`)
126
+ - **Type-Safe Client (URL or Zero-Network In-Memory `app`)**:
127
+ - Network: `const api = bareClient('http://localhost:3000');`
128
+ - In-Memory (SSR / Unit Tests): `const api = bareClient(app); await api.get('/users/:id', { params: { id: 1 } });`
129
+
130
+ ## 7. Lifecycle & Error Handling
131
+ ```ts
132
+ app.onStart(() => console.log('Server started'));
133
+ app.onStop(async () => await db.close());
134
+ app.onError((err, ctx) => ctx.status(err.status || 500).json({ error: err.message, requestId: ctx.requestId }));
135
+ app.setNotFound(() => ({ status: 404, message: 'Custom Not Found' }));
136
+ await app.stop(); // Graceful shutdown & removes SIGINT/SIGTERM listeners
137
+ ```
138
+ > **Note**: In `NODE_ENV=production`, unhandled 500 errors automatically mask internal `err.message` and `stack` unless overridden by `app.onError()`, while preserving client 4xx errors (`400`, `413`, `415`).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barejs",
3
- "version": "0.1.49",
3
+ "version": "0.1.50",
4
4
  "author": "xarhang",
5
5
  "description": "High-performance JIT-specialized web framework for Bun",
6
6
  "main": "./dist/index.js",
@@ -56,6 +56,7 @@
56
56
  "elysia": "latest",
57
57
  "hono": "latest",
58
58
  "mitata": "^1.0.34",
59
+ "playwright-core": "^1.65.1",
59
60
  "typescript": "latest",
60
61
  "zod": "^3.25.76"
61
62
  },
@@ -63,6 +64,7 @@
63
64
  "dist",
64
65
  "src",
65
66
  "README.md",
67
+ "llms.txt",
66
68
  "LICENSE"
67
69
  ]
68
70
  }
@@ -78,10 +78,12 @@ const buildUrl = (baseUrl: string, path: string, options?: ClientRequestOptions)
78
78
  };
79
79
 
80
80
  export const bareClient = <AppOrRoutes = any>(
81
- baseUrl: string,
81
+ baseUrlOrApp: string | { fetch: (req: Request) => any },
82
82
  clientOptions: BareClientOptions = {}
83
83
  ): BareClient<AppOrRoutes extends { __routes?: infer R extends RouteSchema } ? R : RouteSchema> => {
84
- const fetchImpl = clientOptions.fetch ?? fetch;
84
+ const isApp = typeof baseUrlOrApp === 'object' && baseUrlOrApp !== null && typeof baseUrlOrApp.fetch === 'function';
85
+ const baseUrl = isApp ? 'http://localhost' : (baseUrlOrApp as string);
86
+ const fetchImpl = clientOptions.fetch ?? (isApp ? ((input: any, init?: RequestInit) => baseUrlOrApp.fetch(new Request(String(input), init))) as any : fetch);
85
87
  const defaultHeaders = clientOptions.headers ?? {};
86
88
 
87
89
  const request = async (method: string, path: string, options?: ClientRequestOptions) => {