barejs 0.2.6 → 0.2.8
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 +132 -125
- package/dist/aws-lambda.js +1 -0
- package/dist/cache.js +1 -0
- package/dist/cloudflare-pages.js +1 -0
- package/dist/edge.js +29 -29
- package/dist/etag.js +1 -0
- package/dist/html.js +1 -0
- package/dist/index.js +194 -189
- package/dist/jsx.js +1 -0
- package/dist/netlify.js +1 -0
- package/dist/node.js +194 -189
- package/dist/ssg.js +1 -0
- package/dist/types/adapters/aws-lambda.d.ts +43 -0
- package/dist/types/adapters/cloudflare-pages.d.ts +18 -0
- package/dist/types/adapters/netlify.d.ts +32 -0
- package/dist/types/core/bare.d.ts +8 -5
- package/dist/types/core/radix.d.ts +5 -0
- package/dist/types/core/router.d.ts +4 -0
- package/dist/types/edge.d.ts +2 -0
- package/dist/types/index.d.ts +3 -0
- package/dist/types/security/validators.d.ts +1 -0
- package/dist/types/utils/cache.d.ts +26 -0
- package/dist/types/utils/etag.d.ts +12 -0
- package/dist/types/utils/file.d.ts +23 -0
- package/dist/types/utils/html.d.ts +22 -0
- package/dist/types/utils/jsx.d.ts +34 -0
- package/dist/types/utils/ssg.d.ts +36 -0
- package/llms.txt +26 -3
- package/package.json +42 -2
- package/src/adapters/aws-lambda.ts +166 -0
- package/src/adapters/cloudflare-pages.ts +27 -0
- package/src/adapters/netlify.ts +28 -0
- package/src/core/bare.ts +86 -8
- package/src/core/radix.ts +46 -10
- package/src/core/router.ts +37 -6
- package/src/edge.ts +2 -0
- package/src/index.ts +3 -0
- package/src/security/validators.ts +24 -4
- package/src/utils/cache.ts +128 -0
- package/src/utils/etag.ts +115 -0
- package/src/utils/file.ts +111 -0
- package/src/utils/html.ts +72 -0
- package/src/utils/jsx.ts +217 -0
- package/src/utils/openapi.ts +7 -0
- package/src/utils/ssg.ts +110 -0
package/README.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
<div align="center">
|
|
2
2
|
<br />
|
|
3
3
|
<h1>Bare<span style="color: #F7DF1E;">JS</span></h1>
|
|
4
|
-
<p><strong>The batteries-included web framework for Bun, Node.js, Deno,
|
|
5
|
-
<p><i>
|
|
4
|
+
<p><strong>The batteries-included, zero-bloat web framework for Bun, Node.js, Deno, Edge & AWS Lambda.</strong></p>
|
|
5
|
+
<p><i>JIT-compiled O(1) radix router, LIFO context pooling & optional <code>uWebSockets.js</code> · Unified validation (Standard Schema v1: Valibot, ArkType, Zod 4 · TypeBox · JSON Schema) with response secret-stripping · End-to-end <code>bareTreaty</code> RPC, typed WebSockets, SSE, generator streaming, OpenAPI 3.1 & JSON-RPC 2.0 · Built-in <code>bareAuth</code> (JWT/JWKS), <code>basicAuth</code>, <code>Hash</code> (Argon2id/scrypt), <code>cors</code>, <code>csrf</code>, <code>rateLimit</code>, <code>idempotency</code>, <code>circuitBreaker</code>, <code>compress</code> (zstd/br/gzip), <code>file()</code>/<code>staticFile</code>, <code>app.macro()</code>, <code>app.cron()</code> & W3C <code>tracing()</code> · Standalone zero-bloat subpaths: <code>barejs/edge</code> (53 KB), <code>barejs/html</code> (649 B), <code>barejs/etag</code> (1.8 KB), <code>barejs/cache</code> (1.6 KB) & <code>barejs/aws-lambda</code> (2.4 KB).</i></p>
|
|
6
6
|
|
|
7
7
|
<p>
|
|
8
8
|
<a href="https://www.npmjs.com/package/barejs"><img src="https://img.shields.io/npm/v/barejs?style=for-the-badge&logo=npm&color=CB3837" alt="NPM Version"></a>
|
|
@@ -22,119 +22,157 @@
|
|
|
22
22
|
```typescript
|
|
23
23
|
import { BareJS, Type, type Context } from 'barejs';
|
|
24
24
|
|
|
25
|
-
const app = new BareJS()
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
}
|
|
25
|
+
const app = new BareJS()
|
|
26
|
+
.get('/', () => ({ hello: 'world' }))
|
|
27
|
+
.post('/orders/:id', {
|
|
28
|
+
params: Type.Object({ id: Type.Integer() }),
|
|
29
|
+
body: Type.Object({ item: Type.String({ minLength: 1 }), qty: Type.Integer({ minimum: 1 }) }),
|
|
30
|
+
response: {
|
|
31
|
+
200: Type.Object({ id: Type.Number(), item: Type.String(), qty: Type.Number() }),
|
|
32
|
+
404: Type.Object({ error: Type.String() })
|
|
33
|
+
}
|
|
34
|
+
}, (ctx: Context) => ({ id: ctx.params.id, ...ctx.body, internal_cost: 9999 })) // internal_cost auto-stripped
|
|
35
|
+
.docs('/docs', { title: 'Orders API', version: '1.0.0' });
|
|
34
36
|
|
|
35
37
|
app.listen(3000);
|
|
36
38
|
```
|
|
37
39
|
|
|
38
40
|
---
|
|
39
41
|
|
|
40
|
-
##
|
|
42
|
+
## Quick Start
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
# Official multi-runtime starter CLI (Bun, Node.js, Node.js + uWebSockets.js, Deno)
|
|
46
|
+
bun create barejs my-app # or --bun | --node | --node-uws | --deno
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
<details>
|
|
50
|
+
<summary><strong>Manual Install (Bun · Node.js >= 20 · Deno 2 · Edge · AWS Lambda)</strong></summary>
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
bun add barejs # Bun (>= 1.1)
|
|
54
|
+
npm install barejs # Node.js (>= 20) — optional: npm install uWebSockets.js ws @node-rs/argon2
|
|
55
|
+
deno add npm:barejs # Deno (>= 2.0)
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
- **Bun:** `import { BareJS } from 'barejs'; app.listen(3000);`
|
|
59
|
+
- **Node.js:** `import { BareJS } from 'barejs/node'; app.listen(3000);` *(auto-uses `uWebSockets.js` if installed, or native `node:http` + built-in RFC 6455 WS & `scrypt`)*
|
|
60
|
+
- **Deno:** `Deno.serve({ port: 3000 }, (req, info) => app.fetch(req, info.remoteAddr.hostname));`
|
|
61
|
+
- **Edge Workers:** `import { BareJS } from 'barejs/edge'; export default app;` *(Cloudflare Workers, Vercel Edge, Deno Deploy — zero `node:*` imports)*
|
|
62
|
+
- **AWS Lambda:** `import { awsLambda } from 'barejs/aws-lambda'; export const handler = awsLambda(app);` *(API Gateway v1/v2 & ALB)*
|
|
41
63
|
|
|
42
|
-
|
|
43
|
-
- **Unified Schema Validation:** Declarative `body`, `query`, `params`, `headers`, and `response` schemas with **Standard Schema v1** (Valibot, ArkType, Zod 4, Effect — sync & async fail-closed), **TypeBox**, **Zod**, or **Native JSON Schema** — including auto-coercion, `stripUnknown` Mass-Assignment protection, `413` `maxBodySize` guards, and automatic secret-field stripping.
|
|
44
|
-
- **End-to-End Type Safety:** `bareClient(app)` (with non-throwing `client.safe.*` and typed `client.ws()`) and chained Proxy **`bareTreaty(app | url)`** (`api.users({ id: 42 }).get()` & `.subscribe()`) provide compile-time route, param, query, body, and response inference over HTTP/WS or zero-network in-memory calls.
|
|
45
|
-
- **Batteries Included:** Auto-generated **OpenAPI 3.1** (with automatic `bearerAuth`/`basicAuth` security schemes) + Scalar UI (`app.docs`), **JSON-RPC 2.0** (`app.rpc`), **WebSockets** (`app.ws`), **SSE** (`ctx.sse`), **Streaming Uploads** (`ctx.upload` / `ctx.uploadStream`), **Compression** (`compress` — `zstd`/`br`/`gzip`), **Static Files** (`staticFile` with ETag/`304`/Range `206`/`spa: true`), `app.derive`, `app.cron`, `app.useLog({ format: 'json' })`, `onRequest`/`onResponse` hooks, native `tls`, `app.listenCluster()`, and `healthcheck`.
|
|
46
|
-
- **Zero-Trust Security & Resilience:** Built-in `bareAuth` (HS256/RS256/ES256/JWKS + `revokeToken`), `basicAuth`, `hasRole`, `Hash` (Argon2id/bcrypt/scrypt), HMAC-signed cookies, CRLF header/cookie/redirect injection protection, `trustProxy` CIDR/IP allowlist, `cors`, `csrf`, `rateLimit`, `idempotency`, `circuitBreaker`, `createSingleflight`, `timeout`, `redisStore`, and `app.onDrain`.
|
|
47
|
-
- **Multi-Runtime & Edge Interop:** Zero-dep native drivers for **Bun** (`Bun.serve({ routes })`), **Node.js >= 20** (`barejs/node` with built-in RFC 6455 WebSockets & `scrypt`, plus optional `uWebSockets.js` auto-detection with streaming backpressure, `uWS.SSLApp` TLS & WS pub/sub), **Deno >= 2.0** (`Deno.upgradeWebSocket`), and **Edge Workers** (`barejs/edge` — zero `node:*` imports for Cloudflare Workers, Vercel Edge & Deno Deploy). Standard `Request`/`Response` (`ctx.req`) works directly with **Better-Auth**, **Auth0**, **Clerk**, **GraphQL Yoga**, **Sentry**, and **OpenTelemetry**.
|
|
64
|
+
</details>
|
|
48
65
|
|
|
49
66
|
---
|
|
50
67
|
|
|
51
|
-
##
|
|
68
|
+
## Package Exports & Bundle Sizes
|
|
52
69
|
|
|
53
|
-
|
|
70
|
+
Import only what you need — optional modules ship as standalone tree-shakeable subpaths so core stays lean:
|
|
54
71
|
|
|
55
|
-
|
|
72
|
+
| Import Path | Size | Target / Purpose |
|
|
73
|
+
| :--- | :---: | :--- |
|
|
74
|
+
| `barejs` | Full | Bun & Deno core + all built-in security, resilience, OpenAPI, WebSockets, SSE, RPC, Cron |
|
|
75
|
+
| `barejs/node` | Full | Node.js `>= 20` driver (`node:http`, native RFC 6455 WS, `scrypt`, optional `uWebSockets.js` + `uWS.SSLApp`) |
|
|
76
|
+
| `barejs/edge` | `53 KB` | Zero-`node:*` Edge runtime (Cloudflare Workers, Vercel Edge, Deno Deploy) |
|
|
77
|
+
| `barejs/html` | `649 B` | XSS-safe `html` tagged template literal + `raw()` + `escapeHtml()` + `.toResponse()` |
|
|
78
|
+
| `barejs/etag` | `1.8 KB` | Edge-safe dynamic `etag()` middleware (`304 Not Modified`, weak FNV-1a default / strong SHA-256) |
|
|
79
|
+
| `barejs/cache` | `2.2 KB` | Edge-safe `cache()` middleware (`Cache-Control`, `Vary`, Web Cache API `caches.default`) |
|
|
80
|
+
| `barejs/jsx` | `4.5 KB` | Zero-dep JSX/TSX SSR (`jsx-runtime`, async components, streaming `<Suspense>`, `renderToReadableStream`) |
|
|
81
|
+
| `barejs/ssg` | `2.1 KB` | Build-time Static Site Generator (`toSSG(app, { dir, routes })`) |
|
|
82
|
+
| `barejs/aws-lambda` | `3.0 KB` | AWS Lambda adapter (`awsLambda` / `handle`) for API Gateway v1, v2 & ALB |
|
|
83
|
+
| `barejs/cloudflare-pages` | `768 B` | Cloudflare Pages Functions adapter (`export const onRequest = handle(app)`) |
|
|
84
|
+
| `barejs/netlify` | `752 B` | Netlify Functions v2 adapter (`export default handle(app)`) |
|
|
56
85
|
|
|
57
|
-
|
|
58
|
-
# Interactive (prompts for Bun, Node.js, Node.js + uWebSockets.js, or Deno)
|
|
59
|
-
bun create barejs my-app
|
|
60
|
-
|
|
61
|
-
# Or choose a runtime directly:
|
|
62
|
-
bun create barejs my-bun-app --bun
|
|
63
|
-
bun create barejs my-node-app --node
|
|
64
|
-
bun create barejs my-uws-app --node-uws
|
|
65
|
-
bun create barejs my-deno-app --deno
|
|
66
|
-
```
|
|
86
|
+
---
|
|
67
87
|
|
|
68
|
-
|
|
88
|
+
## Batteries Included (At a Glance)
|
|
69
89
|
|
|
70
|
-
|
|
71
|
-
<summary><strong>Bun (>= 1.1.0)</strong></summary>
|
|
90
|
+
Everything below ships in `barejs` with full TypeScript types — no extra packages required:
|
|
72
91
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
92
|
+
| Area | Built-In APIs & Exports |
|
|
93
|
+
| :--- | :--- |
|
|
94
|
+
| **Routing & Core** | `BareJS`, `BareRouter`, optional params (`:type?`), regex params (`:id{[0-9]+}`), `*` wildcards, `app.group()`, `app.route()`, `app.use(plugin)`, `app.derive()`, `app.macro()`, `app.onRequest()`, `app.onResponse()`, `app.onError()`, `app.setNotFound()`, `app.request()`, `app.listenCluster()`, native `tls`, `uWebSockets.js` (`engine: 'uws'`), lazy LIFO `Context` pool |
|
|
95
|
+
| **Validation & Schemas** | `RouteSchemas` (`body`, `query`, `params`, `headers`, `cookies`, `response` single or per-status `{ 200, 404 }`, `maxBodySize`, `stripUnknown`) — **Standard Schema v1** (Valibot, ArkType, Zod 4, Effect), **TypeBox** (`Type`/`t`), **Zod** (`Z`/`z`), **Native** (`native()`), auto-coercion, recursive response secret-field stripping |
|
|
96
|
+
| **Typed RPC & Docs** | `bareTreaty(app \| url)` (chained Proxy RPC + typed `.subscribe()` WebSockets), `bareClient(app \| url)` (with non-throwing `client.safe.*`), `app.docs()` (**OpenAPI 3.1** + Scalar UI), `app.rpc()` (**JSON-RPC 2.0**) |
|
|
97
|
+
| **Auth & Security** | `bareAuth()` (HS256/RS256/ES256/JWKS + `createToken`, `revokeToken`, `isTokenRevoked`), `basicAuth()`, `hasRole()`, `Hash` (Argon2id/bcrypt/scrypt), HMAC-signed `HttpOnly` cookies (`ctx.setCookie` / `ctx.getSignedCookie`), `cors()`, `csrf()`, `securityHeaders()`, `rateLimit()`, `trustProxy` CIDR allowlist, CRLF injection guards |
|
|
98
|
+
| **Resilience & State** | `idempotency()` (`409` in-flight + `X-Idempotent-Replayed`), `createSingleflight()`, `circuitBreaker()`, `timeout()`, `redisStore()` (`Bun.redis` / `ioredis`), `app.cron()`, `app.onDrain()` |
|
|
99
|
+
| **Real-Time, Files & HTML** | `app.ws('/ws/:room')` (fail-closed schemas + pub/sub), `ctx.sse()`, **Generator Streaming** (`function*` / `async function*`), `file()` 1-liner (root jail + download), `staticFile()` (ETag/`304`/Range `206`/SPA), `ctx.upload()` / `ctx.uploadStream()`, `compress()` (`zstd`/`br`/`gzip`), `html`/`raw` (`barejs/html`), `etag()` (`barejs/etag`) |
|
|
100
|
+
| **Observability** | Zero-dep W3C `tracing()` (`traceparent` + `Server-Timing`), `serverTiming()`, `logger()`, `app.useLog({ format: 'json' })`, `healthcheck()` |
|
|
101
|
+
| **External Interop** | Standard `Request`/`Response` works directly with **Better-Auth**, **GraphQL Yoga**, **Auth0**, **Clerk**, **Sentry**, **OpenTelemetry** ([recipes](./docs/integrations.md)) |
|
|
102
|
+
|
|
103
|
+
---
|
|
104
|
+
|
|
105
|
+
## Feature Snippets
|
|
106
|
+
|
|
107
|
+
<details>
|
|
108
|
+
<summary><strong>1. End-to-End Type-Safe RPC (<code>bareTreaty</code>) & Composable Macros (<code>app.macro</code>)</strong></summary>
|
|
76
109
|
|
|
77
110
|
```typescript
|
|
78
|
-
import { BareJS } from 'barejs';
|
|
111
|
+
import { BareJS, bareTreaty, bareAuth } from 'barejs';
|
|
79
112
|
|
|
80
|
-
const
|
|
81
|
-
|
|
82
|
-
|
|
113
|
+
const authPlugin = new BareJS()
|
|
114
|
+
.macro('auth', {
|
|
115
|
+
beforeHandle: (ctx, role: string) => (ctx.user?.role === role ? undefined : ctx.status(403).json({ error: 'Forbidden' }))
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
const app = new BareJS()
|
|
119
|
+
.use(bareAuth({ secret: process.env.JWT_SECRET! }))
|
|
120
|
+
.use(authPlugin)
|
|
121
|
+
.get('/users/:id', { auth: 'admin' }, (ctx) => ({ id: ctx.params.id, viewer: ctx.user }));
|
|
122
|
+
|
|
123
|
+
// Zero-network in-memory OR remote HTTP client with full compile-time inference:
|
|
124
|
+
const api = bareTreaty(app); // or bareTreaty('https://api.example.com')
|
|
125
|
+
const { data, error } = await api.users({ id: 42 }).get();
|
|
83
126
|
```
|
|
84
127
|
|
|
85
128
|
</details>
|
|
86
129
|
|
|
87
130
|
<details>
|
|
88
|
-
<summary><strong>
|
|
89
|
-
|
|
90
|
-
```bash
|
|
91
|
-
npm install barejs
|
|
92
|
-
# Zero-dep native WebSockets (RFC 6455) & scrypt hashing work out of the box!
|
|
93
|
-
# Optional peer dependencies only if you prefer `ws` or Argon2id:
|
|
94
|
-
npm install ws @node-rs/argon2
|
|
95
|
-
```
|
|
131
|
+
<summary><strong>2. Security, ETag & Idempotency (<code>basicAuth</code> · <code>bareAuth</code> · <code>etag</code> · <code>idempotency</code>)</strong></summary>
|
|
96
132
|
|
|
97
133
|
```typescript
|
|
98
|
-
import { BareJS } from 'barejs
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
app
|
|
102
|
-
app.
|
|
134
|
+
import { BareJS, basicAuth, idempotency, securityHeaders, cors } from 'barejs';
|
|
135
|
+
import { etag } from 'barejs/etag';
|
|
136
|
+
|
|
137
|
+
const app = new BareJS()
|
|
138
|
+
.use(securityHeaders(), cors({ origin: 'https://app.example.com' }), etag())
|
|
139
|
+
.get('/catalog', () => ({ items: ['a', 'b'] })) // Automatic W/"..." ETag & 304 Not Modified
|
|
140
|
+
.post('/charge', idempotency({ ttlMs: 86_400_000 }), () => ({ paid: true }))
|
|
141
|
+
.get('/metrics', basicAuth({ username: 'ops', password: process.env.OPS_PASSWORD! }), () => 'ok');
|
|
103
142
|
```
|
|
104
143
|
|
|
105
144
|
</details>
|
|
106
145
|
|
|
107
146
|
<details>
|
|
108
|
-
<summary><strong>
|
|
109
|
-
|
|
110
|
-
```bash
|
|
111
|
-
deno add npm:barejs
|
|
112
|
-
```
|
|
147
|
+
<summary><strong>3. XSS-Safe HTML (<code>barejs/html</code>), Streaming Generators & <code>file()</code></strong></summary>
|
|
113
148
|
|
|
114
149
|
```typescript
|
|
115
|
-
import { BareJS } from 'barejs';
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
app
|
|
119
|
-
|
|
150
|
+
import { BareJS, file } from 'barejs';
|
|
151
|
+
import { html, raw } from 'barejs/html';
|
|
152
|
+
|
|
153
|
+
const app = new BareJS()
|
|
154
|
+
.get('/hello', (ctx) => html`<h1>Hello ${ctx.query.name ?? 'World'}</h1>${raw('<span>✓</span>')}`.toResponse())
|
|
155
|
+
.get('/download/:name', (ctx) => file(ctx.params.name, { root: './uploads', download: true }))
|
|
156
|
+
.get('/stream', async function* () {
|
|
157
|
+
yield 'chunk-1\n';
|
|
158
|
+
yield 'chunk-2\n';
|
|
159
|
+
});
|
|
120
160
|
```
|
|
121
161
|
|
|
122
162
|
</details>
|
|
123
163
|
|
|
124
164
|
<details>
|
|
125
|
-
<summary><strong>Edge Workers (
|
|
165
|
+
<summary><strong>4. Edge Workers (<code>barejs/edge</code>) & AWS Lambda (<code>barejs/aws-lambda</code>)</strong></summary>
|
|
126
166
|
|
|
127
167
|
```typescript
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
export default app;
|
|
168
|
+
// Cloudflare Workers / Vercel Edge / Deno Deploy (53 KB, zero node:* imports)
|
|
169
|
+
import { BareJS, cors } from 'barejs/edge';
|
|
170
|
+
export default new BareJS<{ API_KEY: string }>().use(cors()).get('/ping', () => 'pong');
|
|
171
|
+
|
|
172
|
+
// AWS Lambda (API Gateway v1, v2 & ALB — 2.4 KB adapter)
|
|
173
|
+
import { BareJS } from 'barejs/edge';
|
|
174
|
+
import { awsLambda } from 'barejs/aws-lambda';
|
|
175
|
+
export const handler = awsLambda(new BareJS().get('/hello/:name', (ctx) => ({ hi: ctx.params.name })));
|
|
138
176
|
```
|
|
139
177
|
|
|
140
178
|
</details>
|
|
@@ -143,15 +181,14 @@ export default app;
|
|
|
143
181
|
|
|
144
182
|
## Runtime Support
|
|
145
183
|
|
|
146
|
-
| Feature | Bun (`barejs`) | Node.js >= 20 (`barejs/node`) | Deno (`app.fetch`) | Edge (`barejs/edge`) |
|
|
147
|
-
| :--- | :---: | :---: | :---: | :---: |
|
|
148
|
-
| **Router, Validation
|
|
149
|
-
| **Security
|
|
150
|
-
| **Streaming (`ctx.sse`,
|
|
151
|
-
| **
|
|
152
|
-
| **
|
|
153
|
-
| **
|
|
154
|
-
| **Password Hashing (`Hash`)** | ✅ Native (`Argon2id` / `bcrypt`) | ✅ Native (`scrypt`) · Optional `Argon2id` | ✅ Native (`scrypt`) · Optional `Argon2id` | — |
|
|
184
|
+
| Feature | Bun (`barejs`) | Node.js >= 20 (`barejs/node`) | Deno (`app.fetch`) | Edge (`barejs/edge`) | AWS Lambda (`barejs/aws-lambda`) |
|
|
185
|
+
| :--- | :---: | :---: | :---: | :---: | :---: |
|
|
186
|
+
| **Router, Validation, `bareTreaty`/`bareClient`, `barejs/html`, `barejs/etag`** | ✅ | ✅ | ✅ | ✅ | ✅ |
|
|
187
|
+
| **Security (`bareAuth`, `basicAuth`, `cors`, `csrf`, `rateLimit`, `idempotency`, `tracing`)** | ✅ | ✅ | ✅ | ✅ (Web Crypto) | ✅ |
|
|
188
|
+
| **Streaming (`ctx.sse`, generator streams, `ctx.uploadStream`)** | ✅ | ✅ | ✅ | ✅ | ✅ (buffered) |
|
|
189
|
+
| **Files (`file`, `staticFile`), Compression (`zstd`/`br`/`gzip`) & Native `tls`** | ✅ | ✅ (`uWS` / `https`) | ✅ | — (Edge CDN) | — (S3 / CloudFront) |
|
|
190
|
+
| **WebSockets (`app.ws`)** | ✅ Native | ✅ RFC 6455 · `uWS` · `ws` | ✅ Native | — | — |
|
|
191
|
+
| **Password Hashing (`Hash`)** | ✅ Argon2id / bcrypt | ✅ `scrypt` · Argon2id | ✅ `scrypt` | — | ✅ (Node) |
|
|
155
192
|
|
|
156
193
|
---
|
|
157
194
|
|
|
@@ -165,58 +202,28 @@ export default app;
|
|
|
165
202
|
<a href="https://github.com/xarhang/bareJS/actions/workflows/bench.yml"><img src="https://img.shields.io/github/actions/workflow/status/xarhang/bareJS/bench.yml?branch=main&label=CI_Benchmarks&style=flat-square&logo=github" alt="CI Benchmarks"></a>
|
|
166
203
|
</p>
|
|
167
204
|
|
|
168
|
-
Measured in-process on **Bun** with [`mitata`](https://github.com/evanwash/mitata) (`benchmarks/fair-suite.ts`). Bold values indicate a **mean** latency more than 10% faster than the runner-up; differences under ~10%
|
|
205
|
+
Measured in-process on **Bun** with [`mitata`](https://github.com/evanwash/mitata) (`benchmarks/fair-suite.ts`, `NODE_ENV=production`). Bold values indicate a **mean** latency more than 10% faster than the runner-up; differences under ~10% are treated as ties.
|
|
169
206
|
|
|
170
207
|
<!-- MARKER: MULTI_BENCH_SUMMARY_START -->
|
|
171
208
|
|
|
172
209
|
| Scenario | **BareJS** | **ElysiaJS** | **Hono** |
|
|
173
210
|
| :--- | :---: | :---: | :---: |
|
|
174
|
-
| **1. 100 Routes + Dynamic Params** | **`
|
|
175
|
-
| **2. 10 Middlewares + Deep Path** | **`
|
|
176
|
-
| **3. POST JSON + Schema Validation** | **`
|
|
177
|
-
| **4. Async Handler + Query Parsing** |
|
|
211
|
+
| **1. 100 Routes + Dynamic Params** | **`824 ns`**<br><sub>`p99: 4.52 µs`</sub> | `1.20 µs`<br><sub>`p99: 5.41 µs`</sub> | `2.79 µs`<br><sub>`p99: 11.61 µs`</sub> |
|
|
212
|
+
| **2. 10 Middlewares + Deep Path** | **`726 ns`**<br><sub>`p99: 4.17 µs`</sub> | `1.22 µs`<br><sub>`p99: 5.80 µs`</sub> | `3.25 µs`<br><sub>`p99: 11.75 µs`</sub> |
|
|
213
|
+
| **3. POST JSON + Schema Validation** | **`2.35 µs`**<br><sub>`p99: 9.91 µs`</sub> | `3.07 µs`<br><sub>`p99: 12.11 µs`</sub> | `3.15 µs`<br><sub>`p99: 14.14 µs`</sub> |
|
|
214
|
+
| **4. Async Handler + Query Parsing** | `1.53 µs`<br><sub>`p99: 6.65 µs`</sub> | `1.62 µs`<br><sub>`p99: 6.88 µs`</sub> | `2.14 µs`<br><sub>`p99: 9.65 µs`</sub> |
|
|
178
215
|
|
|
179
|
-
> Last Updated: 2026-
|
|
216
|
+
> Last Updated: 2026-12-01 (github action — `linux`, INTEL(R) XEON(R) PLATINUM 8573C, Bun `1.4.5`, Elysia `1.4.21`, Hono `4.11.4`)
|
|
180
217
|
|
|
181
218
|
<!-- MARKER: MULTI_BENCH_SUMMARY_END -->
|
|
182
219
|
|
|
183
|
-
See **[BENCHMARKS.md](./BENCHMARKS.md)** for all 7 scenarios
|
|
184
|
-
|
|
185
|
-
---
|
|
186
|
-
|
|
187
|
-
## Full Capabilities & Built-In Modules
|
|
188
|
-
|
|
189
|
-
BareJS is a complete, zero-boilerplate backend platform—every module below ships in the core package with TypeScript types:
|
|
190
|
-
|
|
191
|
-
| Category | Built-In Capabilities |
|
|
192
|
-
| :--- | :--- |
|
|
193
|
-
| **Core & Routing** | $O(1)$ static `switch` fast-path + radix jump-table (`:params`, `*` wildcards), Bun native `routes` fast-path, optional Node.js **`uWebSockets.js`** driver (`engine: 'uws'`), native **`tls`** option (Bun, `uWS.SSLApp`, Node `https`), zero-Node **`barejs/edge`** entrypoint (Cloudflare Workers, Vercel Edge, Deno Deploy), `app.listenCluster()` multi-core clustering, `BareRouter` sub-app mounting, lazy bounded LIFO `Context` pool (`0..65536`), `app.onRequest()`/`app.onResponse()` hooks, `app.request()` test helper |
|
|
194
|
-
| **Validation & Serialization** | Unified `RouteSchemas` (`body`, `query`, `params`, `headers`, `response`, `maxBodySize`) supporting **Standard Schema v1** (Valibot, ArkType, Zod 4, Effect — async fail-closed), **TypeBox** (`Type`/`t`), **Zod** (`Z`/`z`), and **Native JSON Schema** (`native()`), automatic coercion, `413` streaming body limit, `stripUnknown` Mass-Assignment protection, recursive response secret-field stripping |
|
|
195
|
-
| **Type-Safe RPC & Docs** | `bareClient(app \| url)` (with non-throwing `client.safe` Result union & typed `client.ws()`), chained proxy **`bareTreaty(app \| url)`** (`api.users({ id: 42 }).get()` & `.subscribe()` WebSocket in-memory or network), automatic **OpenAPI 3.1** spec (`/docs/json`) + Scalar UI (`/docs`), **JSON-RPC 2.0** (`app.rpc()`) |
|
|
196
|
-
| **Zero-Trust Security** | `bareAuth()` (constant-time HS256 JWT + asymmetric RS256/ES256/JWKS + `revokeToken()`/`isRevoked`), `basicAuth()`, `hasRole()`, `Hash` (Argon2id/bcrypt on Bun; zero-dep `scrypt` fallback on Node/Deno), HMAC-SHA256 signed `HttpOnly` cookies, `cors()`, `csrf()`, `securityHeaders()`, `rateLimit()` (flood-resistant), `trustProxy(boolean \| string[])` CIDR allowlist |
|
|
197
|
-
| **Resilience & State** | `idempotency()` (`409 IDEMPOTENT_IN_FLIGHT` + `X-Idempotent-Replayed`, caller-scoped), `createSingleflight()` cache-stampede coalescing, `circuitBreaker()` (`503 Retry-After`), `timeout()` (`408`), pluggable `redisStore()` (`Bun.redis` / `ioredis`), overlap-safe `app.cron()` |
|
|
198
|
-
| **Real-Time, Files & Ops** | Parameterized WebSockets (`app.ws('/ws/:room')` with pub/sub on Bun & `uWebSockets.js`), Server-Sent Events (`ctx.sse()`), `ctx.upload()` & $O(\text{chunk})$ streaming `ctx.uploadStream()`, `staticFile()` (ETag, `304`, Range `206`, SPA fallback, LRU metadata cache), `compress()` (`zstd`/`br`/`gzip`), `useLog({ format: 'json' })` + `logger()`, `healthcheck()` (`/health` + `/ready`), `app.onDrain()` + IPC `DRAIN_REQUEST` |
|
|
199
|
-
| **External Integrations** | Web Standard `ctx.req`/`Response` works out of the box with **Better-Auth**, **GraphQL Yoga**, **Auth0** (JWKS), **Clerk**, **Sentry**, and **OpenTelemetry** — see [docs/integrations.md](./docs/integrations.md) |
|
|
200
|
-
|
|
201
|
-
---
|
|
202
|
-
|
|
203
|
-
## Documentation
|
|
204
|
-
|
|
205
|
-
- **[Documentation Site](https://xarhang.github.io/bareJS/)** — Interactive docs, code examples, and live CI benchmark dashboard.
|
|
206
|
-
- **[`create-barejs` Starter CLI](https://github.com/xarhang/create-barejs)** — Official multi-runtime project scaffolding (`bun create barejs my-app --bun|--node|--node-uws|--deno`).
|
|
207
|
-
- **[Comprehensive Guide](./docs/guide.md)** — Scaffolding, validation & auto-coercion, cookies & uploads, security suite, `app.derive()`, `app.macro()`, WebSockets, SSE, JSON-RPC 2.0, OpenAPI 3.1, `listenCluster()`, `uWebSockets.js`, native `tls`, `barejs/edge`, and `bareClient`/`bareTreaty`.
|
|
208
|
-
- **[External Integrations](./docs/integrations.md)** — Ready-to-use recipes for Better-Auth, GraphQL Yoga, Auth0, Clerk, Sentry, and OpenTelemetry.
|
|
209
|
-
- **[API & Configuration Reference](./docs/reference.md)** — Complete `Context` (`ctx`) & `BareJS` API tables, `poolSize`, `bare.config.ts`, and `NODE_ENV` settings.
|
|
210
|
-
- **[Benchmarks](./BENCHMARKS.md)** — Full 7-scenario results and reproduction instructions.
|
|
211
|
-
- **[Security Policy](./SECURITY.md)** — Vulnerability reporting and security hardening guidelines.
|
|
212
|
-
- **[Changelog](./CHANGELOG.md)** — Release history and migration notes.
|
|
213
|
-
- **[`llms.txt`](./llms.txt)** — Token-efficient API reference for AI coding assistants (Cursor, Copilot, Claude, Windsurf).
|
|
220
|
+
See **[BENCHMARKS.md](./BENCHMARKS.md)** for all 7 scenarios & reproduction steps, or view the [Continuous Benchmark Dashboard](https://xarhang.github.io/bareJS/dev/benchmarks/).
|
|
214
221
|
|
|
215
222
|
---
|
|
216
223
|
|
|
217
|
-
##
|
|
224
|
+
## Documentation & Status
|
|
218
225
|
|
|
219
|
-
- **
|
|
220
|
-
- **
|
|
221
|
-
- **
|
|
226
|
+
- **[Documentation Site](https://xarhang.github.io/bareJS/)** — Interactive docs with `Ctrl+K` instant search, sticky TOC, and live benchmark dashboard.
|
|
227
|
+
- **[Comprehensive Guide](./docs/guide.md)** · **[API Reference](./docs/reference.md)** · **[Integrations](./docs/integrations.md)** · **[Examples](./examples/)** · **[Benchmarks](./BENCHMARKS.md)** · **[Security](./SECURITY.md)** · **[`llms.txt`](./llms.txt)** / **[`llms-full.txt`](https://xarhang.github.io/bareJS/llms-full.txt)** (AI docs)
|
|
228
|
+
- **Status:** Active `0.2.x` (**502 tests across 37 files**), verified in [CI](./.github/workflows/ci.yml) across **Bun**, **Node.js 20 & 22**, and **Deno 2**.
|
|
222
229
|
- **License:** [MIT](./LICENSE) — Maintained by [xarhang](https://github.com/xarhang).
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var q=Object.create;var{getPrototypeOf:E,defineProperty:f,getOwnPropertyNames:P}=Object;var I=Object.prototype.hasOwnProperty;var w=(D,x,F)=>{F=D!=null?q(E(D)):{};let K=x||!D||!D.__esModule?f(F,"default",{value:D,enumerable:!0}):F;for(let Z of P(D))if(!I.call(K,Z))f(K,Z,{get:()=>D[Z],enumerable:!0});return K};var S=((D)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(D,{get:(x,F)=>(typeof require!=="undefined"?require:x)[F]}):D)(function(D){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+D+'" is not supported')});var L=/^(text\/|application\/(json|xml|javascript|xhtml\+xml|x-www-form-urlencoded)|.*\+(json|xml))/i,T=(D)=>{let x=D.get("content-encoding");if(x&&x!=="identity")return!0;let F=(D.get("content-type")||"").split(";",1)[0].trim();if(!F)return!1;return!L.test(F)},V=(D)=>{if(typeof Buffer!=="undefined")return Buffer.from(D).toString("base64");let x="";for(let F=0;F<D.length;F++)x+=String.fromCharCode(D[F]);return btoa(x)},A=(D)=>{if(typeof Buffer!=="undefined")return new Uint8Array(Buffer.from(D,"base64"));let x=atob(D),F=new Uint8Array(x.length);for(let K=0;K<x.length;K++)F[K]=x.charCodeAt(K);return F},B=(D)=>{return async(x)=>{let F=x.version==="2.0"||Boolean(x.requestContext?.http),K=(x.requestContext?.http?.method||x.httpMethod||"GET").toUpperCase(),Z=x.rawPath||x.requestContext?.http?.path||x.path||"/",G=x.rawQueryString??"";if(!G){let N=new URLSearchParams;if(x.multiValueQueryStringParameters)for(let[Q,U]of Object.entries(x.multiValueQueryStringParameters)){if(!U)continue;for(let g of U)N.append(Q,g)}else if(x.queryStringParameters){for(let[Q,U]of Object.entries(x.queryStringParameters))if(U!==void 0)N.append(Q,U)}G=N.toString()}let $=new Headers;if(x.multiValueHeaders)for(let[N,Q]of Object.entries(x.multiValueHeaders)){if(!Q)continue;for(let U of Q)$.append(N,U)}else if(x.headers){for(let[N,Q]of Object.entries(x.headers))if(Q!==void 0)$.set(N,Q)}if(x.cookies&&x.cookies.length>0&&!$.has("cookie"))$.set("cookie",x.cookies.join("; "));let z=$.get("host")||x.requestContext?.domainName||"localhost",C=`${$.get("x-forwarded-proto")||"https"}://${z}${Z.startsWith("/")?Z:"/"+Z}${G?"?"+G:""}`,M={method:K,headers:$};if(x.body!=null&&K!=="GET"&&K!=="HEAD")M.body=x.isBase64Encoded?A(x.body):x.body;let R=x.requestContext?.http?.sourceIp||x.requestContext?.identity?.sourceIp||void 0,Y=await D.fetch(new Request(C,M),R),J={},j=[],O={},W=typeof Y.headers.getSetCookie==="function"?Y.headers.getSetCookie():[];if(Y.headers.forEach((N,Q)=>{let U=Q.toLowerCase();if(U==="set-cookie"){if(W.length===0)j.push(N);return}if(J[U]=N,!F)O[U]=[N]}),W.length>0)j.push(...W);let X=T(Y.headers),_=X?V(new Uint8Array(await Y.arrayBuffer())):await Y.text();if(F)return{statusCode:Y.status,headers:J,...j.length>0?{cookies:j}:{},body:_,isBase64Encoded:X};if(j.length>0)O["set-cookie"]=j;return{statusCode:Y.status,headers:J,multiValueHeaders:O,body:_,isBase64Encoded:X}}},k=B;export{k as handle,B as awsLambda};
|
package/dist/cache.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var H=Object.create;var{getPrototypeOf:R,defineProperty:q,getOwnPropertyNames:f}=Object;var k=Object.prototype.hasOwnProperty;var T=(z,O,F)=>{F=z!=null?H(R(z)):{};let J=O||!z||!z.__esModule?q(F,"default",{value:z,enumerable:!0}):F;for(let Q of f(z))if(!k.call(J,Q))q(J,Q,{get:()=>z[Q],enumerable:!0});return J};var W=((z)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(z,{get:(O,F)=>(typeof require!=="undefined"?require:O)[F]}):z)(function(z){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+z+'" is not supported')});var D=async(z)=>{let F=globalThis.caches;if(!F)return null;if(z&&typeof F.open==="function")return await F.open(z);if(F.default&&typeof F.default.match==="function")return F.default;if(typeof F.open==="function")return await F.open("barejs-default");return null},E=(z,O)=>{let F=Array.isArray(O)?O:[O],J=z.get("vary"),Q=new Set(J?J.split(",").map((U)=>U.trim().toLowerCase()).filter(Boolean):[]),X=J?J.split(",").map((U)=>U.trim()).filter(Boolean):[];for(let U=0;U<F.length;U++){let _=F[U].trim();if(!_)continue;let $=_.toLowerCase();if(!Q.has($))Q.add($),X.push(_)}if(X.length>0)z.set("vary",X.join(", "))},b=(z={})=>{let{cacheName:O,cache:F,cacheControl:J,vary:Q,keyGenerator:X}=z,U=z.wait??!1,_=new Set(z.cacheableStatuses??[200]),$=async(Y,j)=>{let B=Y.req.method;if(B!=="GET"&&B!=="HEAD")return j();let I=F??await D(O),A=X?X(Y):Y.req.url,Z=new Request(A,{method:"GET"});if(I){let L=await I.match(Z);if(L){if(B==="HEAD")return new Response(null,{status:L.status,headers:L.headers});return L}}let M=await j();if(!(M instanceof Response))return M;if((M.headers.get("content-type")||"").toLowerCase().includes("text/event-stream"))return M;if(!_.has(M.status))return M;let K=M;if(J||Q){let L=new Headers(M.headers);if(J&&!L.has("cache-control"))L.set("cache-control",J);if(Q)E(L,Q);K=new Response(M.body,{status:M.status,statusText:M.statusText,headers:L})}if(I&&B==="GET"){let L=I.put(Z,K.clone()).catch(()=>{}),S=Y.executionCtx;if(U)await L;else if(S&&typeof S.waitUntil==="function")S.waitUntil(L)}return K},V=async(Y,j)=>{return $(Y,()=>Promise.resolve(j?j():void 0))};return V.__wrapHandler=$,V};export{b as cache};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var y=Object.create;var{getPrototypeOf:z,defineProperty:w,getOwnPropertyNames:A}=Object;var B=Object.prototype.hasOwnProperty;var E=(b,j,k)=>{k=b!=null?y(z(b)):{};let m=j||!b||!b.__esModule?w(k,"default",{value:b,enumerable:!0}):k;for(let v of A(b))if(!B.call(m,v))w(m,v,{get:()=>b[v],enumerable:!0});return m};var G=((b)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(b,{get:(j,k)=>(typeof require!=="undefined"?require:j)[k]}):b)(function(b){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+b+'" is not supported')});var D=(b)=>{return(j)=>{return b.fetch(j.request,j.env,{waitUntil:(k)=>j.waitUntil(k),passThroughOnException:()=>{}})}},I=D;export{D as handle,I as cloudflarePages};
|