barejs 0.1.49 → 0.1.51

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.
Files changed (43) hide show
  1. package/README.md +257 -98
  2. package/dist/index.js +157 -94
  3. package/dist/types/client/index.d.ts +24 -22
  4. package/dist/types/core/bare.d.ts +83 -3
  5. package/dist/types/core/context.d.ts +47 -1
  6. package/dist/types/core/radix.d.ts +1 -0
  7. package/dist/types/core/router.d.ts +21 -10
  8. package/dist/types/index.d.ts +16 -8
  9. package/dist/types/security/auth.d.ts +10 -1
  10. package/dist/types/security/cors.d.ts +7 -3
  11. package/dist/types/security/csrf.d.ts +12 -0
  12. package/dist/types/security/idempotency.d.ts +22 -0
  13. package/dist/types/security/resilience.d.ts +17 -0
  14. package/dist/types/security/timeout.d.ts +6 -0
  15. package/dist/types/security/validators.d.ts +18 -0
  16. package/dist/types/utils/compress.d.ts +12 -0
  17. package/dist/types/utils/health.d.ts +17 -0
  18. package/dist/types/utils/logger.d.ts +22 -0
  19. package/dist/types/utils/openapi.d.ts +23 -1
  20. package/dist/types/utils/static.d.ts +5 -1
  21. package/llms.txt +138 -0
  22. package/package.json +3 -1
  23. package/src/client/index.ts +61 -18
  24. package/src/core/bare.ts +409 -49
  25. package/src/core/context.ts +266 -32
  26. package/src/core/radix.ts +37 -3
  27. package/src/core/router.ts +43 -16
  28. package/src/index.ts +25 -9
  29. package/src/security/auth.ts +68 -11
  30. package/src/security/cors.ts +85 -31
  31. package/src/security/csrf.ts +84 -0
  32. package/src/security/hash.ts +8 -2
  33. package/src/security/headers.ts +12 -3
  34. package/src/security/idempotency.ts +118 -0
  35. package/src/security/rateLimit.ts +1 -6
  36. package/src/security/resilience.ts +91 -0
  37. package/src/security/timeout.ts +32 -0
  38. package/src/security/validators.ts +201 -5
  39. package/src/utils/compress.ts +49 -0
  40. package/src/utils/health.ts +65 -0
  41. package/src/utils/logger.ts +66 -0
  42. package/src/utils/openapi.ts +59 -14
  43. package/src/utils/static.ts +71 -5
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, 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 (214 tests / 2,906 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.51",
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
  }
@@ -17,49 +17,82 @@ type ExtractParams<Path extends string> =
17
17
  ? { [K in Param]: string | number }
18
18
  : Record<string, never>;
19
19
 
20
- export type RouteSchema = Record<string, {
20
+ export interface RouteEndpoint {
21
21
  method: string;
22
+ path?: string;
22
23
  params?: Record<string, any>;
24
+ query?: Record<string, any>;
25
+ headers?: Record<string, any>;
23
26
  body?: any;
24
27
  response?: any;
25
- }>;
28
+ }
29
+
30
+ export type RouteSchema = Record<string, RouteEndpoint>;
31
+
32
+ type RouteKey<M extends string, P extends string> = `${M} ${P}`;
26
33
 
27
34
  type PathsForMethod<Routes extends RouteSchema, M extends string> = {
28
- [K in keyof Routes]: Routes[K]['method'] extends M ? K : never;
35
+ [K in keyof Routes]: Routes[K]['method'] extends M
36
+ ? (Routes[K]['path'] extends string ? Routes[K]['path'] : K & string)
37
+ : never;
29
38
  }[keyof Routes] & string;
30
39
 
40
+ type LookupRoute<Routes extends RouteSchema, M extends string, P extends string> =
41
+ RouteKey<M, P> extends keyof Routes
42
+ ? Routes[RouteKey<M, P>]
43
+ : P extends keyof Routes
44
+ ? Routes[P]
45
+ : never;
46
+
47
+ type EndpointOptions<R extends RouteEndpoint, P extends string, WithBody extends boolean> =
48
+ Omit<ClientRequestOptions, 'params' | 'query' | 'headers' | (WithBody extends true ? 'body' : never)> & {
49
+ params?: R['params'] extends Record<string, any> ? R['params'] : ExtractParams<P>;
50
+ query?: R['query'] extends Record<string, any> ? R['query'] : ClientRequestOptions['query'];
51
+ headers?: R['headers'] extends Record<string, any> ? R['headers'] & Record<string, string> : ClientRequestOptions['headers'];
52
+ } & (WithBody extends true ? { body?: R['body'] } : {});
53
+
31
54
  export interface BareClient<Routes extends RouteSchema = RouteSchema> {
32
55
  get<P extends PathsForMethod<Routes, 'GET'> | (string & {})>(
33
56
  path: P,
34
- options?: ClientRequestOptions & (P extends keyof Routes ? { params?: ExtractParams<P & string> } : {})
35
- ): Promise<P extends keyof Routes ? Routes[P]['response'] : any>;
57
+ options?: LookupRoute<Routes, 'GET', P & string> extends infer R extends RouteEndpoint
58
+ ? EndpointOptions<R, P & string, false>
59
+ : ClientRequestOptions
60
+ ): Promise<LookupRoute<Routes, 'GET', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>;
36
61
 
37
62
  post<P extends PathsForMethod<Routes, 'POST'> | (string & {})>(
38
63
  path: P,
39
- options?: ClientRequestOptions & (P extends keyof Routes ? { params?: ExtractParams<P & string>; body?: Routes[P]['body'] } : {})
40
- ): Promise<P extends keyof Routes ? Routes[P]['response'] : any>;
64
+ options?: LookupRoute<Routes, 'POST', P & string> extends infer R extends RouteEndpoint
65
+ ? EndpointOptions<R, P & string, true>
66
+ : ClientRequestOptions
67
+ ): Promise<LookupRoute<Routes, 'POST', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>;
41
68
 
42
69
  put<P extends PathsForMethod<Routes, 'PUT'> | (string & {})>(
43
70
  path: P,
44
- options?: ClientRequestOptions & (P extends keyof Routes ? { params?: ExtractParams<P & string>; body?: Routes[P]['body'] } : {})
45
- ): Promise<P extends keyof Routes ? Routes[P]['response'] : any>;
71
+ options?: LookupRoute<Routes, 'PUT', P & string> extends infer R extends RouteEndpoint
72
+ ? EndpointOptions<R, P & string, true>
73
+ : ClientRequestOptions
74
+ ): Promise<LookupRoute<Routes, 'PUT', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>;
46
75
 
47
76
  patch<P extends PathsForMethod<Routes, 'PATCH'> | (string & {})>(
48
77
  path: P,
49
- options?: ClientRequestOptions & (P extends keyof Routes ? { params?: ExtractParams<P & string>; body?: Routes[P]['body'] } : {})
50
- ): Promise<P extends keyof Routes ? Routes[P]['response'] : any>;
78
+ options?: LookupRoute<Routes, 'PATCH', P & string> extends infer R extends RouteEndpoint
79
+ ? EndpointOptions<R, P & string, true>
80
+ : ClientRequestOptions
81
+ ): Promise<LookupRoute<Routes, 'PATCH', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>;
51
82
 
52
83
  delete<P extends PathsForMethod<Routes, 'DELETE'> | (string & {})>(
53
84
  path: P,
54
- options?: ClientRequestOptions & (P extends keyof Routes ? { params?: ExtractParams<P & string> } : {})
55
- ): Promise<P extends keyof Routes ? Routes[P]['response'] : any>;
85
+ options?: LookupRoute<Routes, 'DELETE', P & string> extends infer R extends RouteEndpoint
86
+ ? EndpointOptions<R, P & string, false>
87
+ : ClientRequestOptions
88
+ ): Promise<LookupRoute<Routes, 'DELETE', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>;
56
89
  }
57
90
 
58
91
  const buildUrl = (baseUrl: string, path: string, options?: ClientRequestOptions): string => {
59
92
  let finalPath = path;
60
93
  if (options?.params) {
61
94
  for (const [k, v] of Object.entries(options.params)) {
62
- finalPath = finalPath.replace(`:${k}`, encodeURIComponent(String(v)));
95
+ finalPath = finalPath.replaceAll(`:${k}`, encodeURIComponent(String(v)));
63
96
  }
64
97
  }
65
98
  const base = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
@@ -78,10 +111,12 @@ const buildUrl = (baseUrl: string, path: string, options?: ClientRequestOptions)
78
111
  };
79
112
 
80
113
  export const bareClient = <AppOrRoutes = any>(
81
- baseUrl: string,
114
+ baseUrlOrApp: string | ({ fetch: (req: Request) => any } & AppOrRoutes),
82
115
  clientOptions: BareClientOptions = {}
83
116
  ): BareClient<AppOrRoutes extends { __routes?: infer R extends RouteSchema } ? R : RouteSchema> => {
84
- const fetchImpl = clientOptions.fetch ?? fetch;
117
+ const isApp = typeof baseUrlOrApp === 'object' && baseUrlOrApp !== null && typeof baseUrlOrApp.fetch === 'function';
118
+ const baseUrl = isApp ? 'http://localhost' : (baseUrlOrApp as string);
119
+ const fetchImpl = clientOptions.fetch ?? (isApp ? ((input: any, init?: RequestInit) => baseUrlOrApp.fetch(new Request(String(input), init))) as any : fetch);
85
120
  const defaultHeaders = clientOptions.headers ?? {};
86
121
 
87
122
  const request = async (method: string, path: string, options?: ClientRequestOptions) => {
@@ -100,8 +135,16 @@ export const bareClient = <AppOrRoutes = any>(
100
135
  }
101
136
 
102
137
  const res = await fetchImpl(url, init);
103
- const ct = res.headers.get('content-type') || '';
104
- const data = ct.includes('application/json') ? await res.json() : await res.text();
138
+ let data: any = null;
139
+ if (res.status !== 204 && res.status !== 205 && res.status !== 304) {
140
+ const ct = res.headers.get('content-type') || '';
141
+ if (ct.includes('application/json')) {
142
+ const text = await res.text();
143
+ data = text ? JSON.parse(text) : null;
144
+ } else {
145
+ data = await res.text();
146
+ }
147
+ }
105
148
  if (!res.ok) {
106
149
  const err: any = new Error(`HTTP ${res.status}`);
107
150
  err.status = res.status;