barejs 0.2.7 → 0.2.9
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 +139 -126
- package/dist/aws-lambda.js +1 -0
- package/dist/cache.js +1 -0
- package/dist/cloudflare-pages.js +1 -0
- package/dist/edge.js +28 -28
- package/dist/etag.js +1 -0
- package/dist/html.js +1 -0
- package/dist/index.js +146 -144
- package/dist/jsx.js +1 -0
- package/dist/netlify.js +1 -0
- package/dist/node.js +146 -144
- 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 +15 -3
- package/dist/types/core/radix.d.ts +5 -0
- package/dist/types/core/router.d.ts +2 -0
- package/dist/types/edge.d.ts +13 -0
- package/dist/types/index.d.ts +3 -1
- package/dist/types/utils/cache.d.ts +26 -0
- package/dist/types/utils/etag.d.ts +12 -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 +24 -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 +78 -22
- package/src/core/context.ts +1 -1
- package/src/core/radix.ts +46 -10
- package/src/core/router.ts +41 -7
- package/src/edge.ts +28 -1
- package/src/index.ts +3 -1
- package/src/utils/cache.ts +128 -0
- package/src/utils/etag.ts +115 -0
- package/src/utils/html.ts +72 -0
- package/src/utils/jsx.ts +217 -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 TypeScript 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> · Modular subpaths: <code>barejs/edge</code> (53 KB), <code>barejs/html</code>, <code>barejs/etag</code>, <code>barejs/cache</code>, <code>barejs/jsx</code>, <code>barejs/ssg</code>, <code>barejs/aws-lambda</code>, <code>barejs/cloudflare-pages</code> & <code>barejs/netlify</code>.</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,163 @@
|
|
|
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
|
+
# Optional: Install the official BareJS AI Agent Skill (Claude Code, Cursor, Codex, OpenCode)
|
|
49
|
+
bunx skills add xarhang/bareJS
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
<details>
|
|
53
|
+
<summary><strong>Manual Install (Bun · Node.js >= 20 · Deno 2 · Edge · AWS Lambda)</strong></summary>
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
bun add barejs # Bun (>= 1.1)
|
|
57
|
+
npm install barejs # Node.js (>= 20) — optional: npm install uWebSockets.js ws @node-rs/argon2
|
|
58
|
+
deno add npm:barejs # Deno (>= 2.0)
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
- **Bun:** `import { BareJS } from 'barejs'; app.listen(3000);`
|
|
62
|
+
- **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`)*
|
|
63
|
+
- **Deno:** `Deno.serve({ port: 3000 }, (req, info) => app.fetch(req, info.remoteAddr.hostname));`
|
|
64
|
+
- **Edge Workers:** `import { BareJS } from 'barejs/edge'; export default app;` *(Cloudflare Workers, Vercel Edge, Deno Deploy — zero `node:*` imports)*
|
|
65
|
+
- **AWS Lambda:** `import { awsLambda } from 'barejs/aws-lambda'; export const handler = awsLambda(app);` *(API Gateway v1/v2 & ALB)*
|
|
66
|
+
- **Meta Frameworks:** `const app = new BareJS({ prefix: '/api' }); export const GET = app.fetch;` *(Next.js App Router, Astro, SvelteKit, Nuxt/Nitro, Remix, SolidStart, TanStack Start — [recipes](./docs/integrations.md))*
|
|
41
67
|
|
|
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**.
|
|
68
|
+
</details>
|
|
48
69
|
|
|
49
70
|
---
|
|
50
71
|
|
|
51
|
-
##
|
|
72
|
+
## Package Exports & Bundle Sizes
|
|
52
73
|
|
|
53
|
-
|
|
74
|
+
Import only what you need — optional modules ship as standalone tree-shakeable subpaths so core stays lean:
|
|
54
75
|
|
|
55
|
-
|
|
76
|
+
| Import Path | Size | Target / Purpose |
|
|
77
|
+
| :--- | :---: | :--- |
|
|
78
|
+
| `barejs` | Full | Bun & Deno core + all built-in security, resilience, OpenAPI, WebSockets, SSE, RPC, Cron |
|
|
79
|
+
| `barejs/node` | Full | Node.js `>= 20` driver (`node:http`, native RFC 6455 WS, `scrypt`, optional `uWebSockets.js` + `uWS.SSLApp`) |
|
|
80
|
+
| `barejs/edge` | `53 KB` | Zero-`node:*` Edge runtime (Cloudflare Workers, Vercel Edge, Deno Deploy) |
|
|
81
|
+
| `barejs/html` | `649 B` | XSS-safe `html` tagged template literal + `raw()` + `escapeHtml()` + `.toResponse()` |
|
|
82
|
+
| `barejs/etag` | `1.8 KB` | Edge-safe dynamic `etag()` middleware (`304 Not Modified`, weak FNV-1a default / strong SHA-256) |
|
|
83
|
+
| `barejs/cache` | `2.2 KB` | Edge-safe `cache()` middleware (`Cache-Control`, `Vary`, Web Cache API `caches.default`) |
|
|
84
|
+
| `barejs/jsx` | `4.5 KB` | Zero-dep JSX/TSX SSR (`jsx-runtime`, async components, streaming `<Suspense>`, `renderToReadableStream`) |
|
|
85
|
+
| `barejs/ssg` | `2.1 KB` | Build-time Static Site Generator (`toSSG(app, { dir, routes })`) |
|
|
86
|
+
| `barejs/aws-lambda` | `3.0 KB` | AWS Lambda adapter (`awsLambda` / `handle`) for API Gateway v1, v2 & ALB |
|
|
87
|
+
| `barejs/cloudflare-pages` | `768 B` | Cloudflare Pages Functions adapter (`export const onRequest = handle(app)`) |
|
|
88
|
+
| `barejs/netlify` | `752 B` | Netlify Functions v2 adapter (`export default handle(app)`) |
|
|
56
89
|
|
|
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
|
-
```
|
|
90
|
+
---
|
|
67
91
|
|
|
68
|
-
|
|
92
|
+
## Batteries Included (At a Glance)
|
|
69
93
|
|
|
70
|
-
|
|
71
|
-
<summary><strong>Bun (>= 1.1.0)</strong></summary>
|
|
94
|
+
Everything below ships in `barejs` with full TypeScript types — no extra packages required:
|
|
72
95
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
96
|
+
| Area | Built-In APIs & Exports |
|
|
97
|
+
| :--- | :--- |
|
|
98
|
+
| **Routing & Core** | `BareJS`, `BareRouter`, `new BareJS({ prefix })` / `app.basePath()`, 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 |
|
|
99
|
+
| **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 |
|
|
100
|
+
| **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**) |
|
|
101
|
+
| **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 |
|
|
102
|
+
| **Resilience & State** | `idempotency()` (`409` in-flight + `X-Idempotent-Replayed`), `createSingleflight()`, `circuitBreaker()`, `timeout()`, `redisStore()` (`Bun.redis` / `ioredis`), `app.cron()`, `app.onDrain()` |
|
|
103
|
+
| **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`) |
|
|
104
|
+
| **Observability** | Zero-dep W3C `tracing()` (`traceparent` + `Server-Timing`), `serverTiming()`, `logger()`, `app.useLog({ format: 'json' })`, `healthcheck()` |
|
|
105
|
+
| **External Interop** | Standard `Request`/`Response` works directly with **Next.js**, **Astro**, **SvelteKit**, **Nuxt**, **Remix**, **SolidStart**, **TanStack Start**, **Better-Auth**, **GraphQL Yoga**, **Auth0**, **Clerk**, **Sentry**, **OpenTelemetry** ([recipes](./docs/integrations.md)) |
|
|
76
106
|
|
|
77
|
-
|
|
78
|
-
import { BareJS } from 'barejs';
|
|
107
|
+
---
|
|
79
108
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
109
|
+
## Feature Snippets
|
|
110
|
+
|
|
111
|
+
<details>
|
|
112
|
+
<summary><strong>1. End-to-End Type-Safe RPC (<code>bareTreaty</code>) & Composable Macros (<code>app.macro</code>)</strong></summary>
|
|
113
|
+
|
|
114
|
+
```typescript
|
|
115
|
+
import { BareJS, bareTreaty, bareAuth } from 'barejs';
|
|
116
|
+
|
|
117
|
+
const authPlugin = new BareJS()
|
|
118
|
+
.macro({
|
|
119
|
+
auth: {
|
|
120
|
+
beforeHandle: (ctx, role: string) => (ctx.user?.role === role ? undefined : ctx.status(403).json({ error: 'Forbidden' }))
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
const app = new BareJS()
|
|
125
|
+
.use(bareAuth({ secret: process.env.JWT_SECRET! }))
|
|
126
|
+
.use(authPlugin)
|
|
127
|
+
.get('/users/:id', { auth: 'admin' }, (ctx) => ({ id: ctx.params.id, viewer: ctx.user }));
|
|
128
|
+
|
|
129
|
+
// Zero-network in-memory OR remote HTTP client with full compile-time inference:
|
|
130
|
+
const api = bareTreaty(app); // or bareTreaty('https://api.example.com')
|
|
131
|
+
const { data, error } = await api.users({ id: 42 }).get();
|
|
83
132
|
```
|
|
84
133
|
|
|
85
134
|
</details>
|
|
86
135
|
|
|
87
136
|
<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
|
-
```
|
|
137
|
+
<summary><strong>2. Security, ETag & Idempotency (<code>basicAuth</code> · <code>bareAuth</code> · <code>etag</code> · <code>idempotency</code>)</strong></summary>
|
|
96
138
|
|
|
97
139
|
```typescript
|
|
98
|
-
import { BareJS } from 'barejs
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
app
|
|
102
|
-
app.
|
|
140
|
+
import { BareJS, basicAuth, idempotency, securityHeaders, cors } from 'barejs';
|
|
141
|
+
import { etag } from 'barejs/etag';
|
|
142
|
+
|
|
143
|
+
const app = new BareJS()
|
|
144
|
+
.use(securityHeaders(), cors({ origin: 'https://app.example.com' }), etag())
|
|
145
|
+
.get('/catalog', () => ({ items: ['a', 'b'] })) // Automatic W/"..." ETag & 304 Not Modified
|
|
146
|
+
.post('/charge', idempotency({ ttlMs: 86_400_000 }), () => ({ paid: true }))
|
|
147
|
+
.get('/metrics', basicAuth({ user: 'ops', pass: process.env.OPS_PASSWORD! }), () => 'ok');
|
|
103
148
|
```
|
|
104
149
|
|
|
105
150
|
</details>
|
|
106
151
|
|
|
107
152
|
<details>
|
|
108
|
-
<summary><strong>
|
|
109
|
-
|
|
110
|
-
```bash
|
|
111
|
-
deno add npm:barejs
|
|
112
|
-
```
|
|
153
|
+
<summary><strong>3. XSS-Safe HTML (<code>barejs/html</code>), Streaming Generators & <code>file()</code></strong></summary>
|
|
113
154
|
|
|
114
155
|
```typescript
|
|
115
|
-
import { BareJS } from 'barejs';
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
app
|
|
119
|
-
|
|
156
|
+
import { BareJS, file } from 'barejs';
|
|
157
|
+
import { html, raw } from 'barejs/html';
|
|
158
|
+
|
|
159
|
+
const app = new BareJS()
|
|
160
|
+
.get('/hello', (ctx) => html`<h1>Hello ${ctx.query.name ?? 'World'}</h1>${raw('<span>✓</span>')}`.toResponse())
|
|
161
|
+
.get('/download/:name', (ctx) => file(ctx.params.name, { root: './uploads', download: true }))
|
|
162
|
+
.get('/stream', async function* () {
|
|
163
|
+
yield 'chunk-1\n';
|
|
164
|
+
yield 'chunk-2\n';
|
|
165
|
+
});
|
|
120
166
|
```
|
|
121
167
|
|
|
122
168
|
</details>
|
|
123
169
|
|
|
124
170
|
<details>
|
|
125
|
-
<summary><strong>Edge Workers (
|
|
171
|
+
<summary><strong>4. Edge Workers (<code>barejs/edge</code>) & AWS Lambda (<code>barejs/aws-lambda</code>)</strong></summary>
|
|
126
172
|
|
|
127
173
|
```typescript
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
export default app;
|
|
174
|
+
// Cloudflare Workers / Vercel Edge / Deno Deploy (53 KB, zero node:* imports)
|
|
175
|
+
import { BareJS, cors } from 'barejs/edge';
|
|
176
|
+
export default new BareJS<{ API_KEY: string }>().use(cors()).get('/ping', () => 'pong');
|
|
177
|
+
|
|
178
|
+
// AWS Lambda (API Gateway v1, v2 & ALB — 2.4 KB adapter)
|
|
179
|
+
import { BareJS } from 'barejs/edge';
|
|
180
|
+
import { awsLambda } from 'barejs/aws-lambda';
|
|
181
|
+
export const handler = awsLambda(new BareJS().get('/hello/:name', (ctx) => ({ hi: ctx.params.name })));
|
|
138
182
|
```
|
|
139
183
|
|
|
140
184
|
</details>
|
|
@@ -143,15 +187,14 @@ export default app;
|
|
|
143
187
|
|
|
144
188
|
## Runtime Support
|
|
145
189
|
|
|
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` | — |
|
|
190
|
+
| Feature | Bun (`barejs`) | Node.js >= 20 (`barejs/node`) | Deno (`app.fetch`) | Edge (`barejs/edge`) | AWS Lambda (`barejs/aws-lambda`) |
|
|
191
|
+
| :--- | :---: | :---: | :---: | :---: | :---: |
|
|
192
|
+
| **Router, Validation, `bareTreaty`/`bareClient`, `barejs/html`, `barejs/etag`** | ✅ | ✅ | ✅ | ✅ | ✅ |
|
|
193
|
+
| **Security (`bareAuth`, `basicAuth`, `cors`, `csrf`, `rateLimit`, `idempotency`, `tracing`)** | ✅ | ✅ | ✅ | ✅ (Web Crypto) | ✅ |
|
|
194
|
+
| **Streaming (`ctx.sse`, generator streams, `ctx.uploadStream`)** | ✅ | ✅ | ✅ | ✅ | ✅ (buffered) |
|
|
195
|
+
| **Files (`file`, `staticFile`), Compression (`zstd`/`br`/`gzip`) & Native `tls`** | ✅ | ✅ (`uWS` / `https`) | ✅ | — (Edge CDN) | — (S3 / CloudFront) |
|
|
196
|
+
| **WebSockets (`app.ws`)** | ✅ Native | ✅ RFC 6455 · `uWS` · `ws` | ✅ Native | — | — |
|
|
197
|
+
| **Password Hashing (`Hash`)** | ✅ Argon2id / bcrypt | ✅ `scrypt` · Argon2id | ✅ `scrypt` | — | ✅ (Node) |
|
|
155
198
|
|
|
156
199
|
---
|
|
157
200
|
|
|
@@ -165,58 +208,28 @@ export default app;
|
|
|
165
208
|
<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
209
|
</p>
|
|
167
210
|
|
|
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%
|
|
211
|
+
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
212
|
|
|
170
213
|
<!-- MARKER: MULTI_BENCH_SUMMARY_START -->
|
|
171
214
|
|
|
172
215
|
| Scenario | **BareJS** | **ElysiaJS** | **Hono** |
|
|
173
216
|
| :--- | :---: | :---: | :---: |
|
|
174
|
-
| **1. 100 Routes + Dynamic Params** | **`
|
|
175
|
-
| **2. 10 Middlewares + Deep Path** | **`
|
|
176
|
-
| **3. POST JSON + Schema Validation** | **`
|
|
177
|
-
| **4. Async Handler + Query Parsing** | **`
|
|
217
|
+
| **1. 100 Routes + Dynamic Params** | **`803 ns`**<br><sub>`p99: 4.36 µs`</sub> | `1.23 µs`<br><sub>`p99: 5.38 µs`</sub> | `2.88 µs`<br><sub>`p99: 11.42 µs`</sub> |
|
|
218
|
+
| **2. 10 Middlewares + Deep Path** | **`741 ns`**<br><sub>`p99: 4.14 µs`</sub> | `1.24 µs`<br><sub>`p99: 6.04 µs`</sub> | `3.20 µs`<br><sub>`p99: 10.69 µs`</sub> |
|
|
219
|
+
| **3. POST JSON + Schema Validation** | **`2.36 µs`**<br><sub>`p99: 9.36 µs`</sub> | `3.11 µs`<br><sub>`p99: 12.47 µs`</sub> | `3.21 µs`<br><sub>`p99: 13.48 µs`</sub> |
|
|
220
|
+
| **4. Async Handler + Query Parsing** | **`1.27 µs`**<br><sub>`p99: 5.15 µs`</sub> | `1.55 µs`<br><sub>`p99: 6.71 µs`</sub> | `2.17 µs`<br><sub>`p99: 9.51 µs`</sub> |
|
|
178
221
|
|
|
179
|
-
> Last Updated: 2026-
|
|
222
|
+
> 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
223
|
|
|
181
224
|
<!-- MARKER: MULTI_BENCH_SUMMARY_END -->
|
|
182
225
|
|
|
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` + radix jump-table + $O(1)$ grouped sibling dispatch (`: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 (`50 KB` bundle for Cloudflare Workers, Vercel Edge, Deno Deploy), `app.listenCluster()`, composable `app.use(plugin)` carrying routes + **`app.macro()`**, 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`, **`cookies`**, single or **per-status `response: { 200, 404 }`**, `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()`), strict compile-time **`bareTreaty(app \| url)`** (`api.users({ id: 42 }).get()` & `.subscribe()` WebSocket in-memory or network with typed `data`/`error` unions), automatic **OpenAPI 3.1** spec (`/docs/json`, per-status responses & cookie params) + 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, CRLF header/cookie/redirect guards, `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 fail-closed `body`/`query`/`headers` schemas & pub/sub on Bun / `uWebSockets.js`), **Generator Streaming** (`function*` / `async function*`), Server-Sent Events (`ctx.sse()`), **`file()` 1-liner** (root jail + download), `ctx.upload()` & $O(\text{chunk})$ streaming `ctx.uploadStream()`, `staticFile()` (ETag, `304`, Range `206`, SPA fallback, LRU cache), `compress()` (`zstd`/`br`/`gzip`), zero-dep W3C **`tracing()` / `serverTiming()`**, `useLog({ format: 'json' })`, `healthcheck()`, `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 with `Ctrl+K` instant search, sticky TOC, 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, `file()`, generator streaming, security suite, `app.derive()`, `app.macro()`, WebSockets, SSE, JSON-RPC 2.0, OpenAPI 3.1, `tracing()`/`serverTiming()`, `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).
|
|
226
|
+
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
227
|
|
|
215
228
|
---
|
|
216
229
|
|
|
217
|
-
##
|
|
230
|
+
## Documentation & Status
|
|
218
231
|
|
|
219
|
-
- **
|
|
220
|
-
- **
|
|
221
|
-
- **
|
|
232
|
+
- **[Documentation Site](https://xarhang.github.io/bareJS/)** — Interactive docs with `Ctrl+K` instant search, sticky TOC, and live benchmark dashboard.
|
|
233
|
+
- **[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)
|
|
234
|
+
- **Status:** Active `0.2.x` (**511 tests across 38 files**), verified in [CI](./.github/workflows/ci.yml) across **Bun**, **Node.js 20 & 22**, and **Deno 2**.
|
|
222
235
|
- **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};
|