barejs 0.1.50 → 0.1.52
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.
- package/README.md +90 -32
- package/dist/index.js +123 -115
- package/dist/types/client/index.d.ts +23 -23
- package/dist/types/core/bare.d.ts +83 -5
- package/dist/types/core/context.d.ts +3 -1
- package/dist/types/core/router.d.ts +71 -10
- package/dist/types/index.d.ts +10 -5
- package/dist/types/security/auth.d.ts +22 -4
- package/dist/types/security/idempotency.d.ts +3 -0
- package/dist/types/security/rateLimit.d.ts +3 -0
- package/dist/types/security/resilience.d.ts +17 -0
- package/dist/types/security/store.d.ts +36 -0
- package/dist/types/security/validators.d.ts +2 -0
- package/dist/types/utils/compress.d.ts +15 -0
- package/dist/types/utils/health.d.ts +17 -0
- package/dist/types/utils/logger.d.ts +22 -0
- package/dist/types/utils/openapi.d.ts +23 -1
- package/dist/types/utils/static.d.ts +8 -0
- package/llms.txt +19 -20
- package/package.json +1 -1
- package/src/client/index.ts +58 -17
- package/src/core/bare.ts +313 -58
- package/src/core/context.ts +38 -18
- package/src/core/router.ts +110 -16
- package/src/index.ts +18 -5
- package/src/security/auth.ts +286 -38
- package/src/security/hash.ts +8 -2
- package/src/security/idempotency.ts +133 -20
- package/src/security/rateLimit.ts +41 -28
- package/src/security/resilience.ts +91 -0
- package/src/security/store.ts +151 -0
- package/src/security/validators.ts +13 -5
- package/src/utils/compress.ts +80 -0
- package/src/utils/health.ts +65 -0
- package/src/utils/logger.ts +66 -0
- package/src/utils/openapi.ts +10 -0
- package/src/utils/static.ts +68 -9
package/README.md
CHANGED
|
@@ -24,33 +24,43 @@
|
|
|
24
24
|
|
|
25
25
|
## 📊 Benchmarks: Multi-Scenario & Real-World Performance
|
|
26
26
|
|
|
27
|
-
|
|
27
|
+
All benchmark numbers below are **automatically generated on every push to `main`** by GitHub Actions running `benchmarks/fair-suite.ts`, `benchmarks/production-bench.ts`, and `benchmarks/head-to-head.ts` on real `mitata` runs.
|
|
28
28
|
|
|
29
|
-
|
|
30
|
-
| :--- | :---: | :---: | :---: | :---: |
|
|
31
|
-
| **1. 100 Routes + Dynamic Params** | **`1.85 µs`** (`792 ns` min) | `2.86 µs` | `2.31 µs` | `4.77 µs` |
|
|
32
|
-
| **2. 10 Middlewares + Deep Path** | **`1.82 µs`** (`970 B` RAM) | `2.54 µs` | `2.71 µs` (`1.14 KB`) | `5.34 µs` (`1.81 KB`) |
|
|
33
|
-
| **3. POST JSON + Schema Validation** | **`5.00 µs`** (`2.26 KB`) | `5.04 µs` | `5.45 µs` (`2.24 KB`) | `5.51 µs` (`3.53 KB`) |
|
|
34
|
-
| **4. Async Handler + Query Parsing** | **`2.83 µs`** (`1.22 KB` RAM) | `2.99 µs` | `2.92 µs` (`1.58 KB`) | `4.19 µs` (`1.80 KB`) |
|
|
35
|
-
| **5. Live HTTP Server (`Bun.serve` + `fetch`)** | **`45.33 µs`** (`p99: 94 µs`) | `46.63 µs` (`p99: 126 µs`) | `49.31 µs` (`p99: 145 µs`) | `68.54 µs` (`p99: 162 µs`) |
|
|
36
|
-
| **6. Response Schema Secret Stripping** | **`2.01 µs`** (`653 B` RAM) | — | `2.40 µs` (`893 B` RAM) | — |
|
|
37
|
-
| **7. Live SQLite Report (`SUM`/`AVG`/`GROUP BY`)** | **`91.53 µs`** (`p99: 218 µs`) | — | `94.51 µs` (`p99: 277 µs`) | `103.66 µs` (`p99: 543 µs`) |
|
|
38
|
-
| **8. Live SQLite Write (`POST` + Validate + `INSERT`)** | **`88.37 µs`** (`2.84 KB`) | — | `88.51 µs` (`2.95 KB`) | `103.73 µs` (`3.33 KB`) |
|
|
29
|
+
<!-- MARKER: MULTI_BENCH_START -->
|
|
39
30
|
|
|
40
|
-
|
|
31
|
+
| Scenario | **BareJS** 🏆 | **ElysiaJS** | **Hono** |
|
|
32
|
+
| :--- | :---: | :---: | :---: |
|
|
33
|
+
| **1. 100 Routes + Dynamic Params** | **`1.18 µs`**<br><sub>`p99: 7.14 µs`</sub> | `1.81 µs`<br><sub>`p99: 8.63 µs`</sub> | `3.83 µs`<br><sub>`p99: 13.93 µs`</sub> |
|
|
34
|
+
| **2. 10 Middlewares + Deep Path** | **`1.49 µs`**<br><sub>`p99: 8.50 µs`</sub> | `1.99 µs`<br><sub>`p99: 9.14 µs`</sub> | `3.89 µs`<br><sub>`p99: 14.05 µs`</sub> |
|
|
35
|
+
| **3. POST JSON + Schema Validation** | **`4.30 µs`**<br><sub>`p99: 14.34 µs`</sub> | `4.94 µs`<br><sub>`p99: 15.67 µs`</sub> | `4.99 µs`<br><sub>`p99: 16.90 µs`</sub> |
|
|
36
|
+
| **4. Async Handler + Query Parsing** | **`1.91 µs`**<br><sub>`p99: 9.06 µs`</sub> | `2.26 µs`<br><sub>`p99: 9.78 µs`</sub> | `3.26 µs`<br><sub>`p99: 12.48 µs`</sub> |
|
|
37
|
+
| **5. Response Schema Secret Stripping** | **`988 ns`**<br><sub>`p99: 6.36 µs`</sub> | `1.57 µs`<br><sub>`p99: 7.48 µs`</sub> | — |
|
|
38
|
+
| **6. SQLite Report (`SUM`/`AVG`/`GROUP BY`)** | **`20.59 µs`**<br><sub>`p99: 40.46 µs`</sub> | `20.69 µs`<br><sub>`p99: 38.76 µs`</sub> | `26.21 µs`<br><sub>`p99: 50.02 µs`</sub> |
|
|
39
|
+
| **7. SQLite Write (`POST` + Validate + `INSERT`)** | `14.11 µs`<br><sub>`p99: 33.57 µs`</sub> | `17.77 µs`<br><sub>`p99: 45.34 µs`</sub> | **`13.15 µs`**<br><sub>`p99: 13.34 µs`</sub> |
|
|
40
|
+
|
|
41
|
+
> Last Updated: 2026-11-19 (github action)
|
|
42
|
+
|
|
43
|
+
<!-- MARKER: MULTI_BENCH_END -->
|
|
44
|
+
|
|
45
|
+
### Head-to-Head Stress Test (10 Middlewares + Deep Path)
|
|
41
46
|
|
|
42
47
|
<!-- MARKER: PERFORMANCE_TABLE_START -->
|
|
43
48
|
|
|
44
49
|
| Framework | Latency | Speed |
|
|
45
50
|
| :--- | :--- | :--- |
|
|
46
|
-
| **BareJS** | **
|
|
47
|
-
| Elysia | 1.
|
|
48
|
-
| Hono |
|
|
51
|
+
| **BareJS** | **1.17 µs** | **Baseline** |
|
|
52
|
+
| Elysia | 1.64 µs | 1.39x slower |
|
|
53
|
+
| Hono | 5.22 µs | 4.44x slower |
|
|
49
54
|
|
|
50
|
-
> Last Updated: 2026-11-
|
|
55
|
+
> Last Updated: 2026-11-19 (github action)
|
|
51
56
|
|
|
52
57
|
<!-- MARKER: PERFORMANCE_TABLE_END -->
|
|
53
58
|
|
|
59
|
+
> Verified with **268 Automated Tests (5,634 assertions)** and **100.00% Function & 100.00% Line Coverage**.
|
|
60
|
+
>
|
|
61
|
+
> [!TIP]
|
|
62
|
+
> **View our [Continuous Benchmark Dashboard](https://xarhang.github.io/bareJS/dev/benchmarks/)** for historical data and detailed performance trends.
|
|
63
|
+
|
|
54
64
|
> [!TIP]
|
|
55
65
|
> **Using AI Coding Assistants (Cursor, Copilot, Claude, Windsurf)?** Point them to [`llms.txt`](./llms.txt) for a complete, token-efficient reference of every BareJS API.
|
|
56
66
|
|
|
@@ -60,13 +70,15 @@ BareJS is engineered to beat both **ElysiaJS** and **Hono** across routing, midd
|
|
|
60
70
|
|
|
61
71
|
* **JIT Pipeline Compilation**: Flattens routes and middleware chains into direct JavaScript functions at startup, using `AsyncFunction` single-handler fast paths and conditional bytecode inlining.
|
|
62
72
|
* **$O(1)$ Radix Jump-Table Router**: Compiles static branches, dynamic `:params`, and catch-all wildcards (`/*`) into inline `switch` jump-tables.
|
|
63
|
-
* **Recursive JIT Response Projector
|
|
64
|
-
* **Built-In
|
|
73
|
+
* **Recursive JIT Response Projector & Mass-Assignment Guard**: Compiles `response` schemas into fixed-shape JS object literals to strip undeclared fields, and supports `stripUnknown: true` on `body` to prevent Mass-Assignment attacks.
|
|
74
|
+
* **Built-In Resilience (`circuitBreaker`, `idempotency`, `createSingleflight`, `app.cron`)**: Prevent cascading failures (`503 Retry-After`), double-charges (`409 IDEMPOTENT_IN_FLIGHT`), cache stampedes (100 concurrent calls -> 1 DB hit), and overlapping background jobs.
|
|
75
|
+
* **Native Zero-Dep Gzip (`compress`)**: Compresses responses via Bun's native C/Zig `Bun.gzipSync` with `minSize` threshold and automatic SSE/204/304 bypass.
|
|
76
|
+
* **End-to-End Type Inference (`bareClient(app)`)**: Automatic compile-time inference of route paths (across all HTTP methods on shared paths), `params`, `query`, `headers`, `body`, and `response` types directly from your `BareJS` app or mounted `BareRouter`—with zero runtime overhead.
|
|
65
77
|
* **Concurrency-Safe Object Pooling**: Recycles `Context` instances via a LIFO free-list stack with automatic cleanup on release—zero cross-request state leakage.
|
|
66
|
-
* **Dual Response Ergonomics**: Return plain objects/strings directly (Elysia style) OR use
|
|
78
|
+
* **Dual Response Ergonomics & Full HTTP Methods**: Return plain objects/strings directly (Elysia style) OR use `ctx.json()`, `ctx.html()`, `ctx.text()`, `ctx.redirect()`, `ctx.send()`, with `get`, `post`, `put`, `patch`, `delete`, `options`, `head`, and `all`.
|
|
67
79
|
* **Unified Schema Validation & Auto-Coercion**: Validate `body`, `query`, `params`, `headers`, `response`, and `maxBodySize` (`413` DoS guard) in one object with **TypeBox**, **Zod**, or **Native JSON Schema**—with automatic `number`/`boolean` coercion on `query` and `params`.
|
|
68
|
-
* **Batteries-Included Security Suite**: Built-in `securityHeaders()
|
|
69
|
-
* **Real-Time, RPC
|
|
80
|
+
* **Batteries-Included Zero-Trust Security Suite**: Built-in `securityHeaders()`, `cors()`, `csrf()`, `timeout()`, `rateLimit()`, `trustProxy(false)` anti-spoofing, `maxRequestBodySize` server cap, `bareAuth()` (constant-time HS256 JWT + `revokeToken()` / `isRevoked`), `Hash` (Argon2id), HMAC-signed cookies, `ctx.upload()`, and symlink-safe `staticFile()`.
|
|
81
|
+
* **Observability, Real-Time, RPC & OpenAPI 3.1**: Built-in `logger()` (`pretty`/`json` + `X-Request-Id`), `healthcheck()` (`/health` + `/ready`), parameterized WebSockets (`app.ws('/ws/:room')`), SSE (`ctx.sse`), JSON-RPC 2.0 (`app.rpc`), and OpenAPI 3.1 (`app.docs`) with `securitySchemes`, `servers`, and `tags`.
|
|
70
82
|
|
|
71
83
|
---
|
|
72
84
|
|
|
@@ -183,25 +195,27 @@ app.post('/upload', async (ctx) => {
|
|
|
183
195
|
|
|
184
196
|
```typescript
|
|
185
197
|
import {
|
|
186
|
-
BareJS, securityHeaders, cors, csrf, timeout, rateLimit,
|
|
187
|
-
idempotency, createSingleflight,
|
|
198
|
+
BareJS, BareRouter, securityHeaders, cors, csrf, timeout, rateLimit,
|
|
199
|
+
idempotency, createSingleflight, redisStore, compress,
|
|
188
200
|
bareAuth, createToken, basicAuth, hasRole, Hash, staticFile
|
|
189
201
|
} from 'barejs';
|
|
190
202
|
|
|
191
203
|
const app = new BareJS();
|
|
192
204
|
const SECRET = process.env.JWT_SECRET || 'super-secret-key';
|
|
205
|
+
const store = redisStore(Bun.redis, { prefix: 'myapp:' }); // Optional: omit for zero-overhead in-memory Map
|
|
193
206
|
|
|
194
207
|
app.use(securityHeaders());
|
|
195
208
|
app.use(cors({ origin: ['https://app.example.com'], credentials: true }));
|
|
196
209
|
app.use(csrf({ allowedOrigins: ['https://app.example.com'] }));
|
|
197
210
|
app.use(timeout(10_000)); // Returns 408 if handler exceeds 10s
|
|
198
|
-
app.use(
|
|
199
|
-
app.use(
|
|
211
|
+
app.use(compress({ minSize: 1024, encodings: ['zstd', 'br', 'gzip'] })); // Negotiates zstd / br / gzip
|
|
212
|
+
app.use(rateLimit({ windowMs: 60_000, max: 100, store }));
|
|
213
|
+
app.use(staticFile('public', { maxAge: 3600, etag: true, cacheMetadata: { maxEntries: 1024, ttlMs: 30_000 } }));
|
|
200
214
|
|
|
201
215
|
// Payment/Order Double-Charge Protection (Idempotency-Key header)
|
|
202
216
|
// - Returns 409 Conflict if duplicate request is currently in-flight
|
|
203
217
|
// - Replays cached response with X-Idempotent-Replayed: true on retry
|
|
204
|
-
app.post('/payments', idempotency({ ttlMs: 86_400_000 }), async (ctx) => {
|
|
218
|
+
app.post('/payments', idempotency({ ttlMs: 86_400_000, store }), async (ctx) => {
|
|
205
219
|
const body = await ctx.jsonBody();
|
|
206
220
|
return { chargeId: 'ch_101', amount: body.amount, status: 'paid' };
|
|
207
221
|
});
|
|
@@ -224,11 +238,12 @@ app.post('/login', async (ctx) => {
|
|
|
224
238
|
return { token };
|
|
225
239
|
});
|
|
226
240
|
|
|
227
|
-
// Protect routes with constant-time JWT
|
|
228
|
-
app.get('/admin', bareAuth({ secret: SECRET }), hasRole('admin'), (ctx) => ({
|
|
241
|
+
// Protect routes with constant-time HS256 JWT or asymmetric RS256/ES256/JWKS (`ctx.user`)
|
|
242
|
+
app.get('/admin', bareAuth({ secret: SECRET, revocationStore: store }), hasRole('admin'), (ctx) => ({
|
|
229
243
|
user: ctx.user,
|
|
230
244
|
requestId: ctx.requestId
|
|
231
245
|
}));
|
|
246
|
+
app.get('/sso', bareAuth({ algorithms: ['RS256', 'ES256'], jwksUri: 'https://auth.example.com/.well-known/jwks.json' }), (ctx) => ctx.user);
|
|
232
247
|
```
|
|
233
248
|
|
|
234
249
|
---
|
|
@@ -270,9 +285,14 @@ app.onError((err, ctx) => ctx.status(err.status || 500).json({
|
|
|
270
285
|
### 5. 📡 Real-Time (WebSocket, SSE), OpenAPI 3.1, JSON-RPC 2.0 & Client
|
|
271
286
|
|
|
272
287
|
```typescript
|
|
273
|
-
import { BareJS, bareClient } from 'barejs';
|
|
288
|
+
import { BareJS, BareRouter, bareClient, Type } from 'barejs';
|
|
274
289
|
|
|
275
|
-
const
|
|
290
|
+
const usersRouter = new BareRouter().get('/users/:id', {
|
|
291
|
+
params: Type.Object({ id: Type.Integer() }),
|
|
292
|
+
query: Type.Object({ full: Type.Optional(Type.Boolean()) }),
|
|
293
|
+
}, (ctx) => ({ id: ctx.params.id, full: ctx.query.full }));
|
|
294
|
+
|
|
295
|
+
const app = new BareJS().route('/api', usersRouter); // Preserves full route type inference!
|
|
276
296
|
|
|
277
297
|
// Native Bun WebSocket
|
|
278
298
|
app.ws('/ws/chat', {
|
|
@@ -293,12 +313,50 @@ app.rpc('/rpc', {
|
|
|
293
313
|
// Auto OpenAPI 3.1 Spec (/docs/json) + Scalar UI (/docs)
|
|
294
314
|
app.docs('/docs', { title: 'My BareJS API', version: '1.0.0' });
|
|
295
315
|
|
|
316
|
+
// Ergonomic in-memory test helper
|
|
317
|
+
const res = await app.request('/api/users/42?full=true');
|
|
318
|
+
|
|
296
319
|
// Type-Safe Client (Zero-Network In-Memory for tests/SSR OR Network URL)
|
|
297
320
|
const inMemoryClient = bareClient(app);
|
|
298
|
-
const localRes = await inMemoryClient.get('/users/:id', { params: { id: 42 }, query: { full: true } });
|
|
321
|
+
const localRes = await inMemoryClient.get('/api/users/:id', { params: { id: 42 }, query: { full: true } });
|
|
299
322
|
|
|
300
323
|
const httpClient = bareClient('http://localhost:3000');
|
|
301
|
-
const remoteRes = await httpClient.get('/users/:id', { params: { id: 42 }, query: { full: true } });
|
|
324
|
+
const remoteRes = await httpClient.get('/api/users/:id', { params: { id: 42 }, query: { full: true } });
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
---
|
|
328
|
+
|
|
329
|
+
### 6. 🛡️ Production Observability & Zero-Trust Hardening
|
|
330
|
+
|
|
331
|
+
```typescript
|
|
332
|
+
import { BareJS, logger, healthcheck, bareAuth, revokeToken } from 'barejs';
|
|
333
|
+
|
|
334
|
+
const app = new BareJS()
|
|
335
|
+
.trustProxy(false) // Ignore spoofed X-Forwarded-For when directly exposed
|
|
336
|
+
.use(logger({ format: 'json' })) // Structured JSON logs + X-Request-Id
|
|
337
|
+
.use(healthcheck({
|
|
338
|
+
path: '/health',
|
|
339
|
+
readyPath: '/ready',
|
|
340
|
+
version: '1.0.0',
|
|
341
|
+
checks: { db: async () => true }
|
|
342
|
+
}))
|
|
343
|
+
.use(bareAuth({
|
|
344
|
+
secret: process.env.JWT_SECRET!,
|
|
345
|
+
isRevoked: async (payload) => isBlockedInRedis(payload.jti)
|
|
346
|
+
}));
|
|
347
|
+
|
|
348
|
+
// Revoke a compromised token or jti immediately
|
|
349
|
+
revokeToken('compromised-jti-123', 3600_000);
|
|
350
|
+
|
|
351
|
+
// OpenAPI 3.1 with Bearer JWT securitySchemes
|
|
352
|
+
app.docs('/docs', {
|
|
353
|
+
title: 'Production API',
|
|
354
|
+
securitySchemes: { bearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' } },
|
|
355
|
+
security: [{ bearerAuth: [] }]
|
|
356
|
+
});
|
|
357
|
+
|
|
358
|
+
// Enforce server-level maxRequestBodySize (default: 10MB)
|
|
359
|
+
app.listen(3000, '0.0.0.0', true, { maxRequestBodySize: 2 * 1024 * 1024 });
|
|
302
360
|
```
|
|
303
361
|
|
|
304
362
|
---
|