barejs 0.1.54 → 0.1.56
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 +13 -13
- package/dist/index.js +245 -142
- package/dist/types/core/bare.d.ts +5 -3
- package/dist/types/core/context.d.ts +7 -1
- package/dist/types/core/radix.d.ts +3 -5
- package/dist/types/core/router.d.ts +1 -1
- package/dist/types/index.d.ts +2 -2
- package/dist/types/security/csrf.d.ts +2 -0
- package/dist/types/security/idempotency.d.ts +6 -1
- package/dist/types/security/store.d.ts +4 -1
- package/dist/types/utils/openapi.d.ts +1 -0
- package/llms.txt +4 -4
- package/package.json +2 -2
- package/src/client/index.ts +41 -13
- package/src/core/bare.ts +372 -114
- package/src/core/config.ts +3 -2
- package/src/core/context.ts +261 -76
- package/src/core/loader.ts +13 -3
- package/src/core/radix.ts +197 -110
- package/src/core/router.ts +39 -12
- package/src/index.ts +2 -2
- package/src/security/auth.ts +100 -11
- package/src/security/cors.ts +59 -9
- package/src/security/csrf.ts +33 -8
- package/src/security/hash.ts +10 -3
- package/src/security/idempotency.ts +170 -52
- package/src/security/rateLimit.ts +15 -5
- package/src/security/resilience.ts +34 -7
- package/src/security/store.ts +52 -8
- package/src/security/timeout.ts +8 -4
- package/src/security/validators.ts +618 -70
- package/src/utils/compress.ts +35 -18
- package/src/utils/logger.ts +2 -2
- package/src/utils/openapi.ts +46 -8
- package/src/utils/static.ts +36 -10
|
@@ -66,9 +66,8 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
|
|
|
66
66
|
private pool;
|
|
67
67
|
private hotFetch?;
|
|
68
68
|
private compiled;
|
|
69
|
-
private poolMask;
|
|
70
69
|
private _useLog;
|
|
71
|
-
private
|
|
70
|
+
private _trustProxyBox;
|
|
72
71
|
private errorHandler?;
|
|
73
72
|
private wsRoutes;
|
|
74
73
|
private startHooks;
|
|
@@ -92,7 +91,9 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
|
|
|
92
91
|
onError(handler: (err: any, ctx: Context) => any): this;
|
|
93
92
|
ws(path: string, handler: WebSocketRouteHandler): this;
|
|
94
93
|
docs(path?: string, options?: OpenAPIOptions): this;
|
|
95
|
-
rpc(path: string, procedures: Record<string, (params: any, ctx: Context) => any
|
|
94
|
+
rpc(path: string, procedures: Record<string, (params: any, ctx: Context) => any>, options?: {
|
|
95
|
+
maxBatchSize?: number;
|
|
96
|
+
}): this;
|
|
96
97
|
get: AddRoute<Derived, Routes, 'GET'>;
|
|
97
98
|
post: AddRoute<Derived, Routes, 'POST'>;
|
|
98
99
|
put: AddRoute<Derived, Routes, 'PUT'>;
|
|
@@ -108,6 +109,7 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
|
|
|
108
109
|
(mw: any): BareJS<Derived, Routes>;
|
|
109
110
|
};
|
|
110
111
|
private _hasDerive;
|
|
112
|
+
private static readonly DERIVE_RESERVED;
|
|
111
113
|
derive<T extends Record<string, any>>(fn: (ctx: Context & Derived) => Promise<T> | T): BareJS<Derived & T, Routes>;
|
|
112
114
|
private compileHandler;
|
|
113
115
|
compile(): void;
|
|
@@ -47,13 +47,19 @@ export declare class Context {
|
|
|
47
47
|
_requestId: string | undefined;
|
|
48
48
|
_peerIp: string | undefined;
|
|
49
49
|
_trustProxy: boolean;
|
|
50
|
+
_detached: boolean;
|
|
50
51
|
constructor(trustProxy?: boolean);
|
|
51
52
|
get query(): Record<string, string>;
|
|
53
|
+
/** All values for a (possibly repeated) query key, in order. */
|
|
54
|
+
queryAll(key: string): string[];
|
|
52
55
|
getQuery(key: string): string | undefined;
|
|
53
56
|
get cookies(): Record<string, string>;
|
|
54
57
|
setCookie(name: string, value: string, options?: CookieOptions): this;
|
|
55
58
|
getSignedCookie(name: string, secret: string): string | null;
|
|
56
|
-
deleteCookie(name: string, options?: Pick<CookieOptions, 'path' | 'domain'>): this;
|
|
59
|
+
deleteCookie(name: string, options?: Pick<CookieOptions, 'path' | 'domain' | 'secure' | 'sameSite'>): this;
|
|
60
|
+
private readBodyWithLimit;
|
|
61
|
+
private _parseAndSanitizeJson;
|
|
62
|
+
jsonBodySyncOrAsync(maxBytes?: number): any;
|
|
57
63
|
jsonBody(maxBytes?: number): Promise<any>;
|
|
58
64
|
reset(req: Request): this;
|
|
59
65
|
status(code: number): this;
|
|
@@ -6,11 +6,9 @@ export declare class RadixNode {
|
|
|
6
6
|
paramName: string | null;
|
|
7
7
|
wildcardNode: RadixNode | null;
|
|
8
8
|
handlers: Record<string, Function>;
|
|
9
|
+
handlerParams: Record<string, string[]>;
|
|
9
10
|
insert(path: string, method: string, handler: Function): void;
|
|
10
11
|
lookup(method: string, url: string, start: number, ctx: Context): Function | null;
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
varName: string;
|
|
14
|
-
}[]): string;
|
|
15
|
-
id: string;
|
|
12
|
+
private emitParamsAssign;
|
|
13
|
+
jitCompile(register: (h: Function) => string, level?: number, pathPrefix?: string, idxPrefix?: string, paramVars?: string[], emitCall?: (hName: string) => string): string;
|
|
16
14
|
}
|
|
@@ -75,6 +75,6 @@ export declare class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
75
75
|
route<P extends string, R2 extends RouteSchema = {}>(prefix: P, router: BareRouter<R2>): BareRouter<Routes & PrefixRoutes<P, R2>>;
|
|
76
76
|
use<R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareRouter<Routes & R2>;
|
|
77
77
|
use<P extends string, R2 extends RouteSchema = {}>(prefix: P, mw: BareRouter<R2>): BareRouter<Routes & PrefixRoutes<P, R2>>;
|
|
78
|
-
use(
|
|
78
|
+
use(...mws: any[]): BareRouter<Routes>;
|
|
79
79
|
}
|
|
80
80
|
export {};
|
package/dist/types/index.d.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* Built for Bun with Mechanical Sympathy
|
|
5
5
|
* Optimized to outperform competitors by 55% [2026-01-05]
|
|
6
6
|
*/
|
|
7
|
-
export { BareJS, type WebSocketRouteHandler, type CronOptions } from './core/bare';
|
|
7
|
+
export { BareJS, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
|
|
8
8
|
export { BareRouter, type InferSchema, type PrefixRoutes } from './core/router';
|
|
9
9
|
/**
|
|
10
10
|
* Plugin Interface for BareJS
|
|
@@ -20,7 +20,7 @@ import { typebox, zod, native, validate, schemaValidator, createResponseFilter,
|
|
|
20
20
|
export { typebox, typebox as t, zod, zod as z, Z, Z as Zod, native, native as n, validate, validate as v, schemaValidator, createResponseFilter, type RouteSchemas, type RouteDetail };
|
|
21
21
|
export { logger, type LoggerOptions, type LogEntry } from './utils/logger';
|
|
22
22
|
export { healthcheck, type HealthcheckOptions, type HealthCheckFn } from './utils/health';
|
|
23
|
-
export { cors } from './security/cors';
|
|
23
|
+
export { cors, type CorsOptions } from './security/cors';
|
|
24
24
|
export { csrf, type CsrfOptions } from './security/csrf';
|
|
25
25
|
export { timeout, type TimeoutOptions } from './security/timeout';
|
|
26
26
|
export { rateLimit, type RateLimitOptions } from './security/rateLimit';
|
|
@@ -8,5 +8,7 @@ export interface CsrfOptions {
|
|
|
8
8
|
cookieName?: string;
|
|
9
9
|
headerName?: string;
|
|
10
10
|
requireToken?: boolean;
|
|
11
|
+
/** Allow requests that omit both Origin and Referer headers (default: false) */
|
|
12
|
+
allowMissingOrigin?: boolean;
|
|
11
13
|
}
|
|
12
14
|
export declare const csrf: (options?: CsrfOptions) => Middleware;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Middleware } from '../core/context';
|
|
1
|
+
import type { Context, Middleware } from '../core/context';
|
|
2
2
|
import type { IdempotencyStore } from './store';
|
|
3
3
|
export interface IdempotencyOptions {
|
|
4
4
|
/** Header name (default: 'idempotency-key') */
|
|
@@ -9,6 +9,11 @@ export interface IdempotencyOptions {
|
|
|
9
9
|
maxKeys?: number;
|
|
10
10
|
/** Optional external store (e.g. redisStore(client)). Uses in-memory Map fast path when omitted. */
|
|
11
11
|
store?: IdempotencyStore;
|
|
12
|
+
/**
|
|
13
|
+
* Scope string mixed into the cache key so one caller can never replay another caller's response.
|
|
14
|
+
* Default: SHA-256 of the Authorization and Cookie headers.
|
|
15
|
+
*/
|
|
16
|
+
keyScope?: (ctx: Context) => string | undefined;
|
|
12
17
|
}
|
|
13
18
|
/**
|
|
14
19
|
* Payment & Order Double-Charge Protection Middleware (Idempotency-Key).
|
|
@@ -12,13 +12,16 @@ export interface CachedIdempotentEntry {
|
|
|
12
12
|
body?: any;
|
|
13
13
|
rawBody?: ArrayBuffer;
|
|
14
14
|
contentType?: string;
|
|
15
|
+
/** Replayed safe headers (Location, Content-Location, ETag) */
|
|
16
|
+
headers?: Record<string, string>;
|
|
15
17
|
expiresAt: number;
|
|
16
18
|
}
|
|
17
19
|
export interface IdempotencyStore {
|
|
18
20
|
get(key: string): Promise<CachedIdempotentEntry | undefined> | CachedIdempotentEntry | undefined;
|
|
19
21
|
set(key: string, entry: CachedIdempotentEntry, ttlMs: number): Promise<void> | void;
|
|
20
22
|
acquire(key: string, ttlMs?: number): Promise<boolean> | boolean;
|
|
21
|
-
|
|
23
|
+
acquireToken?(key: string, ttlMs?: number): Promise<string | null> | string | null;
|
|
24
|
+
release(key: string, tokenOverride?: string): Promise<void> | void;
|
|
22
25
|
}
|
|
23
26
|
export interface RevocationStore {
|
|
24
27
|
revoke(tokenOrJti: string, ttlMs: number): Promise<void> | void;
|
|
@@ -12,6 +12,7 @@ export interface OpenAPIOptions {
|
|
|
12
12
|
}>;
|
|
13
13
|
securitySchemes?: Record<string, Record<string, any>>;
|
|
14
14
|
security?: Array<Record<string, string[]>>;
|
|
15
|
+
excludePaths?: string[];
|
|
15
16
|
}
|
|
16
17
|
export declare const generateOpenAPISpec: (routes: any[], options?: OpenAPIOptions) => {
|
|
17
18
|
paths: Record<string, Record<string, any>>;
|
package/llms.txt
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# BareJS (`barejs`) — AI Quick Reference (`llms.txt`)
|
|
2
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 (
|
|
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 (401 tests / 6,129 assertions)**.
|
|
4
4
|
|
|
5
5
|
## 1. Installation & Minimal App
|
|
6
6
|
```ts
|
|
@@ -53,7 +53,7 @@ const typedApp = app.route('/api/v1', api); // or app.use('/api/v1', api)
|
|
|
53
53
|
- `await app.request('/items', { method: 'POST', body: JSON.stringify({ name: 'a' }) })`: Ergonomic in-memory helper (normalizes relative paths to `http://localhost` and delegates to `app.fetch`).
|
|
54
54
|
- `ctx.req`: Raw incoming Bun `Request`.
|
|
55
55
|
- `ctx.params`: Route params (`Record<string, any>`, including `ctx.params['*']` for wildcards).
|
|
56
|
-
- `ctx.query` / `ctx.getQuery(key)`: Lazy, prototype-pollution-safe query parser (fast-path when no `%` or `+`).
|
|
56
|
+
- `ctx.query` / `ctx.getQuery(key)` / `ctx.queryAll(key)`: Lazy, prototype-pollution-safe query parser (fast-path when no `%` or `+`) with repeated query key support.
|
|
57
57
|
- `await ctx.jsonBody(maxBytes = 1048576)`: Cached JSON body parser with native fast-path and `413` DoS limit.
|
|
58
58
|
- `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).
|
|
59
59
|
- `ctx.cookies`: Lazy parsed request cookies (`Record<string, string>`).
|
|
@@ -61,7 +61,7 @@ const typedApp = app.route('/api/v1', api); // or app.use('/api/v1', api)
|
|
|
61
61
|
- `await ctx.getSignedCookie(name, secret)`: Verifies HMAC signature with `timingSafeEqual`; returns `null` if tampered or missing.
|
|
62
62
|
- `ctx.deleteCookie(name, opts?)`: Expires cookie immediately (`Max-Age=0`).
|
|
63
63
|
- `ctx.requestId`: Lazy `x-request-id` header or generated `crypto.randomUUID()`.
|
|
64
|
-
- `ctx.ip`: Client IP
|
|
64
|
+
- `ctx.ip`: Client IP from `x-forwarded-for` (first non-empty), `x-real-ip`, `cf-connecting-ip` (only when `trustProxy` is enabled), else peer IP or `'127.0.0.1'`.
|
|
65
65
|
- `ctx.user`: Authenticated user payload populated by `bareAuth` or `basicAuth`.
|
|
66
66
|
- `ctx.store` / `ctx.set(k, v)` / `ctx.get(k)`: Per-request `Map<string, any>` (automatically cleared on pool release).
|
|
67
67
|
- **Response Helpers (Hono / Express style):**
|
|
@@ -103,7 +103,7 @@ app.use(rateLimit({ windowMs: 60_000, max: 100, store })); // Omit store for zer
|
|
|
103
103
|
app.use(staticFile('public', { maxAge: 3600, etag: true, cacheMetadata: { maxEntries: 1024, ttlMs: 30_000 } }));
|
|
104
104
|
|
|
105
105
|
// Idempotency-Key double-charge & race condition guard (409 IDEMPOTENT_IN_FLIGHT + X-Idempotent-Replayed: true)
|
|
106
|
-
app.post('/pay', idempotency({ ttlMs: 86_400_000, maxKeys: 10_000, store }), (ctx) => ({ paid: true }));
|
|
106
|
+
app.post('/pay', idempotency({ ttlMs: 86_400_000, maxKeys: 10_000, store, keyScope: (ctx) => ctx.user?.id }), (ctx) => ({ paid: true }));
|
|
107
107
|
|
|
108
108
|
// Thundering-herd / Cache-stampede request coalescer
|
|
109
109
|
const sf = createSingleflight();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "barejs",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.56",
|
|
4
4
|
"author": "xarhang",
|
|
5
5
|
"description": "High-performance JIT-specialized web framework for Bun",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
"test": "bun test",
|
|
23
23
|
"benchs": "bun run benchmarks/index.ts",
|
|
24
24
|
"bench": "bun run benchmarks/head-to-head.ts",
|
|
25
|
-
"dev": "bun --watch
|
|
25
|
+
"dev": "bun --watch Example/index.ts",
|
|
26
26
|
"build": "bun ./scripts/build.ts",
|
|
27
27
|
"prepublishOnly": "bun run build",
|
|
28
28
|
"release": "bun run build && npm version patch && npm publish --access public"
|
package/src/client/index.ts
CHANGED
|
@@ -92,8 +92,8 @@ const buildUrl = (baseUrl: string, path: string, options?: ClientRequestOptions)
|
|
|
92
92
|
let finalPath = path;
|
|
93
93
|
if (options?.params) {
|
|
94
94
|
const params = options.params;
|
|
95
|
-
finalPath = finalPath.replace(/:([a-zA-Z0-9_]+)(
|
|
96
|
-
Object.hasOwn(params, key) ? encodeURIComponent(String(params[key])) : match
|
|
95
|
+
finalPath = finalPath.replace(/:([a-zA-Z0-9_]+)(?=\/|\?|$)/g, (match, key) =>
|
|
96
|
+
Object.hasOwn(params, key) && params[key] !== undefined ? encodeURIComponent(String(params[key])) : match
|
|
97
97
|
);
|
|
98
98
|
}
|
|
99
99
|
const base = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
|
|
@@ -106,7 +106,7 @@ const buildUrl = (baseUrl: string, path: string, options?: ClientRequestOptions)
|
|
|
106
106
|
if (v !== undefined) qs.set(k, String(v));
|
|
107
107
|
}
|
|
108
108
|
const str = qs.toString();
|
|
109
|
-
if (str) url +=
|
|
109
|
+
if (str) url += (url.includes('?') ? '&' : '?') + str;
|
|
110
110
|
}
|
|
111
111
|
return url;
|
|
112
112
|
};
|
|
@@ -122,26 +122,54 @@ export const bareClient = <AppOrRoutes = any>(
|
|
|
122
122
|
|
|
123
123
|
const request = async (method: string, path: string, options?: ClientRequestOptions) => {
|
|
124
124
|
const url = buildUrl(baseUrl, path, options);
|
|
125
|
-
const headers
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
}
|
|
125
|
+
const headers = new Headers();
|
|
126
|
+
for (const [k, v] of Object.entries(defaultHeaders)) {
|
|
127
|
+
headers.set(k, v);
|
|
128
|
+
}
|
|
129
|
+
if (options?.headers) {
|
|
130
|
+
for (const [k, v] of Object.entries(options.headers)) {
|
|
131
|
+
headers.set(k, v);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
129
134
|
|
|
130
135
|
const init: RequestInit = { method, headers };
|
|
131
136
|
if (options?.body !== undefined && method !== 'GET' && method !== 'HEAD') {
|
|
132
|
-
|
|
133
|
-
|
|
137
|
+
const b = options.body;
|
|
138
|
+
const isRawBody =
|
|
139
|
+
typeof b === 'string' ||
|
|
140
|
+
b instanceof FormData ||
|
|
141
|
+
b instanceof URLSearchParams ||
|
|
142
|
+
b instanceof Blob ||
|
|
143
|
+
b instanceof ArrayBuffer ||
|
|
144
|
+
ArrayBuffer.isView(b) ||
|
|
145
|
+
(typeof ReadableStream !== 'undefined' && b instanceof ReadableStream);
|
|
146
|
+
|
|
147
|
+
if (isRawBody) {
|
|
148
|
+
if (b instanceof FormData) headers.delete('content-type');
|
|
149
|
+
init.body = b as RequestInit['body'];
|
|
150
|
+
} else {
|
|
151
|
+
if (!headers.has('content-type')) {
|
|
152
|
+
headers.set('Content-Type', 'application/json');
|
|
153
|
+
}
|
|
154
|
+
init.body = JSON.stringify(b);
|
|
134
155
|
}
|
|
135
|
-
init.body = typeof options.body === 'string' ? options.body : JSON.stringify(options.body);
|
|
136
156
|
}
|
|
137
157
|
|
|
138
158
|
const res = await fetchImpl(url, init);
|
|
139
159
|
let data: any = null;
|
|
140
160
|
if (res.status !== 204 && res.status !== 205 && res.status !== 304) {
|
|
141
|
-
const ct = res.headers.get('content-type') || '';
|
|
142
|
-
if (ct.includes('application/json')) {
|
|
161
|
+
const ct = (res.headers.get('content-type') || '').toLowerCase();
|
|
162
|
+
if (ct.includes('application/json') || ct.includes('+json')) {
|
|
143
163
|
const text = await res.text();
|
|
144
|
-
|
|
164
|
+
if (text) {
|
|
165
|
+
try {
|
|
166
|
+
data = JSON.parse(text);
|
|
167
|
+
} catch {
|
|
168
|
+
data = text;
|
|
169
|
+
}
|
|
170
|
+
} else {
|
|
171
|
+
data = null;
|
|
172
|
+
}
|
|
145
173
|
} else {
|
|
146
174
|
data = await res.text();
|
|
147
175
|
}
|