barejs 0.2.7 → 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 +152 -150
- package/dist/jsx.js +1 -0
- package/dist/netlify.js +1 -0
- package/dist/node.js +152 -150
- 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/radix.d.ts +5 -0
- package/dist/types/core/router.d.ts +1 -0
- package/dist/types/edge.d.ts +2 -0
- package/dist/types/index.d.ts +2 -0
- 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 +22 -1
- 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 +23 -2
- package/src/core/radix.ts +46 -10
- package/src/core/router.ts +36 -6
- package/src/edge.ts +2 -0
- package/src/index.ts +2 -0
- 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/dist/ssg.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var R=Object.create;var{getPrototypeOf:U,defineProperty:O,getOwnPropertyNames:V}=Object;var W=Object.prototype.hasOwnProperty;var X=(j,k,H)=>{H=j!=null?R(U(j)):{};let L=k||!j||!j.__esModule?O(H,"default",{value:j,enumerable:!0}):H;for(let z of V(j))if(!W.call(L,z))O(L,z,{get:()=>j[z],enumerable:!0});return L};var Y=((j)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(j,{get:(k,H)=>(typeof require!=="undefined"?require:k)[H]}):j)(function(j){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+j+'" is not supported')});var Z=(j,k,H,L)=>{let z=j.replace(/\/+$/,""),v=k.startsWith("/")?k:"/"+k;if(v==="/"||v==="")return`${z}/index.html`;if(v.slice(v.lastIndexOf("/")+1).includes("."))return`${z}${v}`;let K=H.toLowerCase();if(K.includes("application/json"))return`${z}${v}.json`;if(K.includes("text/plain"))return`${z}${v}.txt`;if(K.includes("application/xml")||K.includes("text/xml"))return`${z}${v}.xml`;return L?`${z}${v}/index.html`:`${z}${v}.html`},$=async(j,k={})=>{let H=k.dir??"./static",L=k.dirIndex??!1,z=(k.origin??"http://localhost").replace(/\/+$/,""),v=[];try{let J;if(k.fs)J=k.fs;else{let A=await import("node:fs/promises");J={mkdir:(q,C)=>A.mkdir(q,C),writeFile:(q,C)=>A.writeFile(q,C)}}let K=new Set;if(Array.isArray(j.routes))for(let A=0;A<j.routes.length;A++){let q=j.routes[A];if(q.method!=="GET")continue;let C=q.path||"/";if(C.includes(":")||C.includes("*"))continue;K.add(C.startsWith("/")?C:"/"+C)}if(k.routes)for(let A=0;A<k.routes.length;A++){let q=k.routes[A];K.add(q.startsWith("/")?q:"/"+q)}for(let A of K){let q=await j.fetch(new Request(`${z}${A}`,{method:"GET"}));if(q.status<200||q.status>=300)continue;let C=q.headers.get("content-type")??"text/html",M=Z(H,A,C,L),N=M.slice(0,M.lastIndexOf("/"));if(N)await J.mkdir(N,{recursive:!0});let Q=new Uint8Array(await q.arrayBuffer());await J.writeFile(M,Q),v.push(M)}return{success:!0,files:v}}catch(J){return{success:!1,files:v,error:J instanceof Error?J:new Error(String(J))}}};export{$ as toSSG};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
export interface LambdaEvent {
|
|
2
|
+
version?: string;
|
|
3
|
+
rawPath?: string;
|
|
4
|
+
rawQueryString?: string;
|
|
5
|
+
cookies?: string[];
|
|
6
|
+
requestContext?: {
|
|
7
|
+
http?: {
|
|
8
|
+
method?: string;
|
|
9
|
+
path?: string;
|
|
10
|
+
sourceIp?: string;
|
|
11
|
+
};
|
|
12
|
+
identity?: {
|
|
13
|
+
sourceIp?: string;
|
|
14
|
+
};
|
|
15
|
+
domainName?: string;
|
|
16
|
+
};
|
|
17
|
+
httpMethod?: string;
|
|
18
|
+
path?: string;
|
|
19
|
+
queryStringParameters?: Record<string, string | undefined> | null;
|
|
20
|
+
multiValueQueryStringParameters?: Record<string, string[] | undefined> | null;
|
|
21
|
+
headers?: Record<string, string | undefined> | null;
|
|
22
|
+
multiValueHeaders?: Record<string, string[] | undefined> | null;
|
|
23
|
+
body?: string | null;
|
|
24
|
+
isBase64Encoded?: boolean;
|
|
25
|
+
}
|
|
26
|
+
export interface LambdaResult {
|
|
27
|
+
statusCode: number;
|
|
28
|
+
headers: Record<string, string>;
|
|
29
|
+
cookies?: string[];
|
|
30
|
+
multiValueHeaders?: Record<string, string[]>;
|
|
31
|
+
body: string;
|
|
32
|
+
isBase64Encoded: boolean;
|
|
33
|
+
}
|
|
34
|
+
export interface FetchableApp {
|
|
35
|
+
fetch(req: Request, peerIp?: string): Response | Promise<Response>;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Optional AWS Lambda adapter for BareJS (`import { awsLambda, handle } from 'barejs/aws-lambda'`).
|
|
39
|
+
* Supports API Gateway HTTP API (v2), REST API (v1), and Application Load Balancer (ALB) events
|
|
40
|
+
* with zero dependencies and zero impact on core bundle size.
|
|
41
|
+
*/
|
|
42
|
+
export declare const awsLambda: (app: FetchableApp) => (event: LambdaEvent) => Promise<LambdaResult>;
|
|
43
|
+
export declare const handle: (app: FetchableApp) => (event: LambdaEvent) => Promise<LambdaResult>;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export interface CloudflarePagesContext<Env = Record<string, any>> {
|
|
2
|
+
request: Request;
|
|
3
|
+
env: Env;
|
|
4
|
+
params: Record<string, string | string[]>;
|
|
5
|
+
waitUntil(promise: Promise<any>): void;
|
|
6
|
+
next(input?: Request | string, init?: RequestInit): Promise<Response>;
|
|
7
|
+
data: Record<string, unknown>;
|
|
8
|
+
}
|
|
9
|
+
interface FetchableEdgeApp {
|
|
10
|
+
fetch(req: Request, env?: any, executionCtx?: any): Response | Promise<Response>;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Cloudflare Pages Functions adapter (`onRequest`).
|
|
14
|
+
* Usage: `export const onRequest = handle(app);`
|
|
15
|
+
*/
|
|
16
|
+
export declare const handle: <Env = Record<string, any>>(app: FetchableEdgeApp) => (context: CloudflarePagesContext<Env>) => Response | Promise<Response>;
|
|
17
|
+
export declare const cloudflarePages: <Env = Record<string, any>>(app: FetchableEdgeApp) => (context: CloudflarePagesContext<Env>) => Response | Promise<Response>;
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export interface NetlifyContext {
|
|
2
|
+
ip?: string;
|
|
3
|
+
requestId?: string;
|
|
4
|
+
site?: {
|
|
5
|
+
id?: string;
|
|
6
|
+
name?: string;
|
|
7
|
+
url?: string;
|
|
8
|
+
};
|
|
9
|
+
geo?: {
|
|
10
|
+
city?: string;
|
|
11
|
+
country?: {
|
|
12
|
+
code?: string;
|
|
13
|
+
name?: string;
|
|
14
|
+
};
|
|
15
|
+
timezone?: string;
|
|
16
|
+
};
|
|
17
|
+
cookies?: {
|
|
18
|
+
get(name: string): string | undefined;
|
|
19
|
+
};
|
|
20
|
+
waitUntil?(promise: Promise<any>): void;
|
|
21
|
+
[key: string]: any;
|
|
22
|
+
}
|
|
23
|
+
interface FetchableApp {
|
|
24
|
+
fetch(req: Request, peerIpOrEnv?: any, executionCtx?: any): Response | Promise<Response>;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Netlify Functions v2 adapter.
|
|
28
|
+
* Usage: `export default handle(app);`
|
|
29
|
+
*/
|
|
30
|
+
export declare const handle: (app: FetchableApp) => (req: Request, context?: NetlifyContext) => Response | Promise<Response>;
|
|
31
|
+
export declare const netlify: (app: FetchableApp) => (req: Request, context?: NetlifyContext) => Response | Promise<Response>;
|
|
32
|
+
export {};
|
|
@@ -4,6 +4,11 @@ export declare class RadixNode {
|
|
|
4
4
|
staticKeys: string[];
|
|
5
5
|
paramNode: RadixNode | null;
|
|
6
6
|
paramName: string | null;
|
|
7
|
+
regexParamNodes: Array<{
|
|
8
|
+
regex: RegExp;
|
|
9
|
+
pattern: string;
|
|
10
|
+
node: RadixNode;
|
|
11
|
+
}>;
|
|
7
12
|
wildcardNode: RadixNode | null;
|
|
8
13
|
handlers: Record<string, Function>;
|
|
9
14
|
handlerParams: Record<string, string[]>;
|
|
@@ -90,6 +90,7 @@ export declare class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
90
90
|
routes: any[];
|
|
91
91
|
protected _onRouteMutate?(): void;
|
|
92
92
|
constructor(prefix?: string, groupMiddleware?: any[]);
|
|
93
|
+
private static expandOptionalPaths;
|
|
93
94
|
protected _add(method: string, path: string, handlers: HandlersChain): this;
|
|
94
95
|
get: AddRouterRoute<Routes, 'GET'>;
|
|
95
96
|
post: AddRouterRoute<Routes, 'POST'>;
|
package/dist/types/edge.d.ts
CHANGED
|
@@ -96,4 +96,6 @@ export declare function createSingleflight(): {
|
|
|
96
96
|
size(): number;
|
|
97
97
|
};
|
|
98
98
|
export { tracing, serverTiming, type TracingOptions, type TracingSpan } from './utils/tracing';
|
|
99
|
+
export { html, raw, escapeHtml, type HtmlString } from './utils/html';
|
|
100
|
+
export { etag, type EtagOptions } from './utils/etag';
|
|
99
101
|
export { BareEdge as BareJS, BareRouter, Type, t, Z, z, native, standard, bareClient, bareTreaty, cors, securityHeaders, rateLimit, timeout, circuitBreaker, redisStore, healthcheck, logger, generateOpenAPISpec, renderDocsHTML };
|
package/dist/types/index.d.ts
CHANGED
|
@@ -33,6 +33,8 @@ export { file, type FileResponseOptions } from './utils/file';
|
|
|
33
33
|
export { compress, type CompressOptions, type CompressionEncoding } from './utils/compress';
|
|
34
34
|
export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
|
|
35
35
|
export { tracing, serverTiming, type TracingOptions, type TracingSpan } from './utils/tracing';
|
|
36
|
+
export { html, raw, escapeHtml, type HtmlString } from './utils/html';
|
|
37
|
+
export { etag, type EtagOptions } from './utils/etag';
|
|
36
38
|
export { bareAuth, createToken, basicAuth, hasRole, revokeToken, isTokenRevoked, type BareAuthOptions, type JwtAlgorithm } from './security/auth';
|
|
37
39
|
export { Hash as Password, Hash } from './security/hash';
|
|
38
40
|
export { bareClient, bareTreaty, type BareClient, type BareSafeClient, type BareTreatyNode, type TreatyTree, type BareClientResult, type BareWsClient, type BareClientOptions, type ClientRequestOptions, type RouteEndpoint, type RouteSchema } from './client/index';
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { Context, Middleware } from '../core/context';
|
|
2
|
+
export interface CacheLike {
|
|
3
|
+
match(request: Request | string): Promise<Response | undefined>;
|
|
4
|
+
put(request: Request | string, response: Response): Promise<void>;
|
|
5
|
+
}
|
|
6
|
+
export interface CacheOptions {
|
|
7
|
+
/** Cache name for Web Cache API (`caches.open(cacheName)`). Falls back to `caches.default` on Cloudflare Workers. */
|
|
8
|
+
cacheName?: string;
|
|
9
|
+
/** Optional custom `Cache`-compatible store (overrides `globalThis.caches`, useful for testing or custom stores). */
|
|
10
|
+
cache?: CacheLike;
|
|
11
|
+
/** `Cache-Control` header value applied to cacheable 200 OK responses (e.g. `'public, max-age=60, stale-while-revalidate=30'`). */
|
|
12
|
+
cacheControl?: string;
|
|
13
|
+
/** Optional `Vary` header(s) appended to responses (e.g. `'Accept-Encoding'` or `['Accept', 'Accept-Language']`). */
|
|
14
|
+
vary?: string | string[];
|
|
15
|
+
/** Custom cache key generator (defaults to `ctx.req.url`). */
|
|
16
|
+
keyGenerator?: (ctx: Context) => string;
|
|
17
|
+
/** Await `cache.put()` before returning the response (default: `false`; uses `executionCtx.waitUntil` when available). */
|
|
18
|
+
wait?: boolean;
|
|
19
|
+
/** HTTP status codes eligible for caching (default: `[200]`). */
|
|
20
|
+
cacheableStatuses?: number[];
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Zero-dependency HTTP `Cache-Control` + Web Cache API (`caches.default` / `caches.open`) middleware.
|
|
24
|
+
* Edge-safe (Cloudflare Workers, Deno Deploy, Bun, Node.js). Caches GET/HEAD responses only.
|
|
25
|
+
*/
|
|
26
|
+
export declare const cache: (options?: CacheOptions) => Middleware;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Middleware } from '../core/context';
|
|
2
|
+
export interface EtagOptions {
|
|
3
|
+
/** Emit weak ETags `W/"..."` (default: `true`, fast zero-async FNV-1a 64-bit) */
|
|
4
|
+
weak?: boolean;
|
|
5
|
+
/** Retain these headers on 304 Not Modified responses */
|
|
6
|
+
retainedHeaders?: string[];
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Dynamic API ETag middleware (`304 Not Modified` support).
|
|
10
|
+
* Edge-safe, zero dependencies, skips streaming/SSE and non-200 responses.
|
|
11
|
+
*/
|
|
12
|
+
export declare const etag: (options?: EtagOptions) => Middleware;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
declare const RAW_BRAND: unique symbol;
|
|
2
|
+
export interface HtmlString {
|
|
3
|
+
readonly [RAW_BRAND]: true;
|
|
4
|
+
readonly value: string;
|
|
5
|
+
toString(): string;
|
|
6
|
+
toResponse(status?: number, headers?: Record<string, string>): Response;
|
|
7
|
+
}
|
|
8
|
+
export declare const escapeHtml: (input: string) => string;
|
|
9
|
+
/**
|
|
10
|
+
* Marks a trusted HTML string so `html` tagged templates will not double-escape it.
|
|
11
|
+
* Only pass sanitized or static trusted markup.
|
|
12
|
+
*/
|
|
13
|
+
export declare const raw: (trustedHtml: string) => HtmlString;
|
|
14
|
+
/**
|
|
15
|
+
* XSS-safe HTML tagged template literal (Edge-safe, zero dependencies).
|
|
16
|
+
*
|
|
17
|
+
* Example:
|
|
18
|
+
* `app.get('/hi', (ctx) => html\`<h1>Hello ${ctx.query.name}</h1>\`.toResponse())`
|
|
19
|
+
* `app.get('/hi', (ctx) => ctx.html(String(html\`<h1>Hello ${ctx.query.name}</h1>\`)))`
|
|
20
|
+
*/
|
|
21
|
+
export declare const html: (strings: TemplateStringsArray, ...values: unknown[]) => HtmlString;
|
|
22
|
+
export {};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { escapeHtml, raw, type HtmlString } from './html';
|
|
2
|
+
export { escapeHtml, raw, type HtmlString };
|
|
3
|
+
export type JSXChild = JSXNode | HtmlString | string | number | boolean | null | undefined | JSXChild[];
|
|
4
|
+
export type Component<P = any> = (props: P) => JSXChild | Promise<JSXChild>;
|
|
5
|
+
export interface JSXNode {
|
|
6
|
+
readonly $$bareJsx: true;
|
|
7
|
+
type: string | typeof Fragment | typeof Suspense | Component<any>;
|
|
8
|
+
props: Record<string, any>;
|
|
9
|
+
}
|
|
10
|
+
export declare const Fragment: unique symbol;
|
|
11
|
+
export declare const Suspense: unique symbol;
|
|
12
|
+
export declare const jsx: (type: JSXNode["type"], props: Record<string, any> | null) => JSXNode;
|
|
13
|
+
export declare const jsxs: (type: JSXNode["type"], props: Record<string, any> | null) => JSXNode;
|
|
14
|
+
export declare const jsxDEV: (type: JSXNode["type"], props: Record<string, any> | null) => JSXNode;
|
|
15
|
+
/** Renders a JSX tree (including async components) to an HTML string. */
|
|
16
|
+
export declare const renderToString: (node: JSXChild) => Promise<string>;
|
|
17
|
+
/**
|
|
18
|
+
* Streams a JSX tree as a Web `ReadableStream<Uint8Array>`, flushing `<Suspense fallback>`
|
|
19
|
+
* immediately and streaming out-of-order `<template>` replacement chunks as async children resolve.
|
|
20
|
+
*/
|
|
21
|
+
export declare const renderToReadableStream: (node: JSXChild) => ReadableStream<Uint8Array>;
|
|
22
|
+
/** Convenience helper returning a `text/html; charset=utf-8` Response from a JSX tree. */
|
|
23
|
+
export declare const htmlResponse: (node: JSXChild, status?: number, headers?: Record<string, string> | Headers) => Promise<Response>;
|
|
24
|
+
/** Convenience helper returning a streaming `text/html; charset=utf-8` Response with `<Suspense>` support. */
|
|
25
|
+
export declare const streamResponse: (node: JSXChild, status?: number, headers?: Record<string, string> | Headers) => Response;
|
|
26
|
+
export declare namespace JSX {
|
|
27
|
+
type Element = JSXNode;
|
|
28
|
+
interface ElementChildrenAttribute {
|
|
29
|
+
children: {};
|
|
30
|
+
}
|
|
31
|
+
interface IntrinsicElements {
|
|
32
|
+
[elemName: string]: Record<string, any>;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export interface SSGFileWriter {
|
|
2
|
+
mkdir(path: string, opts?: {
|
|
3
|
+
recursive?: boolean;
|
|
4
|
+
}): Promise<any>;
|
|
5
|
+
writeFile(path: string, data: Uint8Array | string): Promise<any>;
|
|
6
|
+
}
|
|
7
|
+
export interface ToSSGOptions {
|
|
8
|
+
/** Output directory on disk (default: `'./static'`). */
|
|
9
|
+
dir?: string;
|
|
10
|
+
/** Additional concrete routes to pre-render (useful for parameterized routes like `['/posts/hello']`). */
|
|
11
|
+
routes?: string[];
|
|
12
|
+
/** Emit `/about` as `/about/index.html` instead of `/about.html` (default: `false`). */
|
|
13
|
+
dirIndex?: boolean;
|
|
14
|
+
/** Optional custom filesystem writer (useful for testing or non-Node runtimes). */
|
|
15
|
+
fs?: SSGFileWriter;
|
|
16
|
+
/** Base origin used when invoking `app.fetch` (default: `'http://localhost'`). */
|
|
17
|
+
origin?: string;
|
|
18
|
+
}
|
|
19
|
+
export interface ToSSGResult {
|
|
20
|
+
success: boolean;
|
|
21
|
+
files: string[];
|
|
22
|
+
error?: Error;
|
|
23
|
+
}
|
|
24
|
+
interface FetchableApp {
|
|
25
|
+
fetch(req: Request): Response | Promise<Response>;
|
|
26
|
+
routes?: Array<{
|
|
27
|
+
method: string;
|
|
28
|
+
path: string;
|
|
29
|
+
}>;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Build-time Static Site Generator (`toSSG`).
|
|
33
|
+
* Pre-renders static `GET` routes (plus any explicit `options.routes`) into static files.
|
|
34
|
+
*/
|
|
35
|
+
export declare const toSSG: (app: FetchableApp, options?: ToSSGOptions) => Promise<ToSSGResult>;
|
|
36
|
+
export {};
|
package/llms.txt
CHANGED
|
@@ -1,6 +1,19 @@
|
|
|
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 `Bun.serve({ routes })`), **Node.js** (`>= 20` via `barejs/node` with optional `uWebSockets.js` auto-detection & `uWS.SSLApp` TLS), **Deno**,
|
|
3
|
+
> BareJS is an ultra-fast, zero-allocation JIT-compiled web framework for **Bun** (`>= 1.1` with `Bun.serve({ routes })`), **Node.js** (`>= 20` via `barejs/node` with optional `uWebSockets.js` auto-detection & `uWS.SSLApp` TLS), **Deno**, **Edge Workers** (`barejs/edge` — `53 KB`, zero `node:*` imports), **AWS Lambda**, **Cloudflare Pages**, and **Netlify** with official scaffolding CLI **[`create-barejs`](https://github.com/xarhang/create-barejs)** and **502 tests across 37 files verified in CI (Bun, Node.js 20/22, Deno 2)**.
|
|
4
|
+
|
|
5
|
+
## 0. Complete Export & Subpath Index (Check Here First!)
|
|
6
|
+
- `barejs` (core): `BareJS`, `BareRouter`, `Context`, `Type`/`T`/`TypeBox`, `Z`/`z`, `native`, `bareClient`, `bareTreaty`, `bareAuth`, `createToken`, `basicAuth`, `hasRole`, `revokeToken`, `isTokenRevoked`, `Hash`/`Password`, `cors`, `csrf`, `securityHeaders`, `rateLimit`, `timeout`, `idempotency`, `createSingleflight`, `circuitBreaker`, `redisStore`, `compress`, `staticFile`, `file`, `etag`, `html`, `raw`, `escapeHtml`, `tracing`, `serverTiming`, `logger`, `healthcheck`, `generateOpenAPISpec`, `renderDocsHTML` (router supports `:param`, optional `:param?`, regex `:id{[0-9]+}`, and `*` wildcards)
|
|
7
|
+
- `barejs/node`: Node.js `>= 20` build (same exports + native RFC 6455 WS, `scrypt`, optional `uWebSockets.js` / `ws` / `@node-rs/argon2`)
|
|
8
|
+
- `barejs/edge` (`53 KB`): Zero-`node:*` Edge build (Cloudflare Workers, Vercel Edge, Deno Deploy)
|
|
9
|
+
- `barejs/html` (`1.3 KB`): `html`, `raw`, `escapeHtml`, `type HtmlString`
|
|
10
|
+
- `barejs/etag` (`2.4 KB`): `etag`, `type EtagOptions`
|
|
11
|
+
- `barejs/cache` (`2.2 KB`): `cache`, `type CacheOptions`
|
|
12
|
+
- `barejs/jsx` / `barejs/jsx-runtime` (`4.5 KB`): `jsx`, `jsxs`, `Fragment`, `Suspense`, `renderToString`, `renderToReadableStream`, `htmlResponse`, `streamResponse`
|
|
13
|
+
- `barejs/ssg` (`2.1 KB`): `toSSG`, `type ToSSGOptions`, `type ToSSGResult`
|
|
14
|
+
- `barejs/aws-lambda` (`3.0 KB`): `awsLambda`, `handle`, `type AwsLambdaEvent`, `type AwsLambdaResult`
|
|
15
|
+
- `barejs/cloudflare-pages` (`768 B`): `handle`, `cloudflarePages` (`export const onRequest = handle(app)`)
|
|
16
|
+
- `barejs/netlify` (`752 B`): `handle`, `netlify` (`export default handle(app)`)
|
|
4
17
|
|
|
5
18
|
## 1. Scaffolding (`create-barejs`) & Minimal App (Bun, Node.js, Deno, Edge)
|
|
6
19
|
```bash
|
|
@@ -148,3 +161,11 @@ app.setNotFound(() => ({ status: 404, message: 'Custom Not Found' }));
|
|
|
148
161
|
await app.stop(); // Graceful shutdown & removes SIGINT/SIGTERM listeners
|
|
149
162
|
```
|
|
150
163
|
> **Note**: In `NODE_ENV=production`, unhandled 500 errors automatically mask internal `err.message` and `stack` unless overridden by `app.onError()`, while preserving client 4xx errors (`400`, `413`, `415`).
|
|
164
|
+
|
|
165
|
+
## 8. Optional Subpaths, Macros & Observability
|
|
166
|
+
- **HTML Templates (`barejs/html`, `649 B`)**: `html\`<h1>Hello ${name}</h1>${raw('<span>✓</span>')}\`.toResponse()` — auto-escapes XSS, supports nested `html`, arrays, and falsy values.
|
|
167
|
+
- **Dynamic ETag (`barejs/etag`, `1.8 KB`)**: `app.use(etag())` (weak FNV-1a 64-bit default) or `etag({ weak: false })` (strong SHA-256) with `304 Not Modified`.
|
|
168
|
+
- **AWS Lambda (`barejs/aws-lambda`, `2.4 KB`)**: `export const handler = awsLambda(app)` (alias `handle`) — supports API Gateway v1, v2, ALB, `Set-Cookie`, and binary base64.
|
|
169
|
+
- **Composable Macros (`app.macro`)**: `const plugin = new BareJS().macro('auth', { beforeHandle, resolve }); app.use(plugin).get('/me', { auth: 'admin' }, handler);`
|
|
170
|
+
- **Cookie & Per-Status Response Schemas**: `RouteSchemas` supports `cookies` validation and `response: { 200: OkSchema, 404: ErrSchema }` (reflected in OpenAPI 3.1 & `bareTreaty`).
|
|
171
|
+
- **Observability (`tracing`, `serverTiming`)**: `app.use(tracing({ serverTiming: 'app', onSpan }))` — zero-dep W3C `traceparent` + `Server-Timing` header.
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "barejs",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.8",
|
|
4
4
|
"author": "xarhang",
|
|
5
|
-
"description": "Batteries-included web framework for Bun, Node.js,
|
|
5
|
+
"description": "Batteries-included, zero-bloat TypeScript web framework for Bun, Node.js (uWebSockets.js), Deno, Edge & AWS Lambda — O(1) JIT routing, Standard Schema/TypeBox/Zod, bareTreaty RPC, OpenAPI 3.1, WebSockets, JSX SSR, and built-in zero-trust security.",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"module": "./dist/index.js",
|
|
8
8
|
"types": "./dist/types/index.d.ts",
|
|
@@ -21,6 +21,46 @@
|
|
|
21
21
|
"./edge": {
|
|
22
22
|
"types": "./dist/types/edge.d.ts",
|
|
23
23
|
"import": "./dist/edge.js"
|
|
24
|
+
},
|
|
25
|
+
"./html": {
|
|
26
|
+
"types": "./dist/types/utils/html.d.ts",
|
|
27
|
+
"import": "./dist/html.js"
|
|
28
|
+
},
|
|
29
|
+
"./etag": {
|
|
30
|
+
"types": "./dist/types/utils/etag.d.ts",
|
|
31
|
+
"import": "./dist/etag.js"
|
|
32
|
+
},
|
|
33
|
+
"./cache": {
|
|
34
|
+
"types": "./dist/types/utils/cache.d.ts",
|
|
35
|
+
"import": "./dist/cache.js"
|
|
36
|
+
},
|
|
37
|
+
"./jsx": {
|
|
38
|
+
"types": "./dist/types/utils/jsx.d.ts",
|
|
39
|
+
"import": "./dist/jsx.js"
|
|
40
|
+
},
|
|
41
|
+
"./jsx-runtime": {
|
|
42
|
+
"types": "./dist/types/utils/jsx.d.ts",
|
|
43
|
+
"import": "./dist/jsx.js"
|
|
44
|
+
},
|
|
45
|
+
"./jsx-dev-runtime": {
|
|
46
|
+
"types": "./dist/types/utils/jsx.d.ts",
|
|
47
|
+
"import": "./dist/jsx.js"
|
|
48
|
+
},
|
|
49
|
+
"./ssg": {
|
|
50
|
+
"types": "./dist/types/utils/ssg.d.ts",
|
|
51
|
+
"import": "./dist/ssg.js"
|
|
52
|
+
},
|
|
53
|
+
"./aws-lambda": {
|
|
54
|
+
"types": "./dist/types/adapters/aws-lambda.d.ts",
|
|
55
|
+
"import": "./dist/aws-lambda.js"
|
|
56
|
+
},
|
|
57
|
+
"./cloudflare-pages": {
|
|
58
|
+
"types": "./dist/types/adapters/cloudflare-pages.d.ts",
|
|
59
|
+
"import": "./dist/cloudflare-pages.js"
|
|
60
|
+
},
|
|
61
|
+
"./netlify": {
|
|
62
|
+
"types": "./dist/types/adapters/netlify.d.ts",
|
|
63
|
+
"import": "./dist/netlify.js"
|
|
24
64
|
}
|
|
25
65
|
},
|
|
26
66
|
"engines": {
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
export interface LambdaEvent {
|
|
2
|
+
// API Gateway HTTP API v2
|
|
3
|
+
version?: string;
|
|
4
|
+
rawPath?: string;
|
|
5
|
+
rawQueryString?: string;
|
|
6
|
+
cookies?: string[];
|
|
7
|
+
requestContext?: {
|
|
8
|
+
http?: { method?: string; path?: string; sourceIp?: string };
|
|
9
|
+
identity?: { sourceIp?: string };
|
|
10
|
+
domainName?: string;
|
|
11
|
+
};
|
|
12
|
+
// API Gateway REST API v1 & ALB
|
|
13
|
+
httpMethod?: string;
|
|
14
|
+
path?: string;
|
|
15
|
+
queryStringParameters?: Record<string, string | undefined> | null;
|
|
16
|
+
multiValueQueryStringParameters?: Record<string, string[] | undefined> | null;
|
|
17
|
+
headers?: Record<string, string | undefined> | null;
|
|
18
|
+
multiValueHeaders?: Record<string, string[] | undefined> | null;
|
|
19
|
+
body?: string | null;
|
|
20
|
+
isBase64Encoded?: boolean;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface LambdaResult {
|
|
24
|
+
statusCode: number;
|
|
25
|
+
headers: Record<string, string>;
|
|
26
|
+
cookies?: string[];
|
|
27
|
+
multiValueHeaders?: Record<string, string[]>;
|
|
28
|
+
body: string;
|
|
29
|
+
isBase64Encoded: boolean;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface FetchableApp {
|
|
33
|
+
fetch(req: Request, peerIp?: string): Response | Promise<Response>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const TEXT_MIME_RE = /^(text\/|application\/(json|xml|javascript|xhtml\+xml|x-www-form-urlencoded)|.*\+(json|xml))/i;
|
|
37
|
+
|
|
38
|
+
const isBinaryResponse = (headers: Headers): boolean => {
|
|
39
|
+
const enc = headers.get('content-encoding');
|
|
40
|
+
if (enc && enc !== 'identity') return true;
|
|
41
|
+
const ct = (headers.get('content-type') || '').split(';', 1)[0]!.trim();
|
|
42
|
+
if (!ct) return false;
|
|
43
|
+
return !TEXT_MIME_RE.test(ct);
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const toBase64 = (bytes: Uint8Array): string => {
|
|
47
|
+
if (typeof Buffer !== 'undefined') return Buffer.from(bytes).toString('base64');
|
|
48
|
+
let bin = '';
|
|
49
|
+
for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]!);
|
|
50
|
+
return btoa(bin);
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const fromBase64 = (b64: string): Uint8Array => {
|
|
54
|
+
if (typeof Buffer !== 'undefined') return new Uint8Array(Buffer.from(b64, 'base64'));
|
|
55
|
+
const bin = atob(b64);
|
|
56
|
+
const out = new Uint8Array(bin.length);
|
|
57
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
58
|
+
return out;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Optional AWS Lambda adapter for BareJS (`import { awsLambda, handle } from 'barejs/aws-lambda'`).
|
|
63
|
+
* Supports API Gateway HTTP API (v2), REST API (v1), and Application Load Balancer (ALB) events
|
|
64
|
+
* with zero dependencies and zero impact on core bundle size.
|
|
65
|
+
*/
|
|
66
|
+
export const awsLambda = (app: FetchableApp) => {
|
|
67
|
+
return async (event: LambdaEvent): Promise<LambdaResult> => {
|
|
68
|
+
const isV2 = event.version === '2.0' || Boolean(event.requestContext?.http);
|
|
69
|
+
const method = (event.requestContext?.http?.method || event.httpMethod || 'GET').toUpperCase();
|
|
70
|
+
const path = event.rawPath || event.requestContext?.http?.path || event.path || '/';
|
|
71
|
+
|
|
72
|
+
let queryString = event.rawQueryString ?? '';
|
|
73
|
+
if (!queryString) {
|
|
74
|
+
const sp = new URLSearchParams();
|
|
75
|
+
if (event.multiValueQueryStringParameters) {
|
|
76
|
+
for (const [k, vals] of Object.entries(event.multiValueQueryStringParameters)) {
|
|
77
|
+
if (!vals) continue;
|
|
78
|
+
for (const v of vals) sp.append(k, v);
|
|
79
|
+
}
|
|
80
|
+
} else if (event.queryStringParameters) {
|
|
81
|
+
for (const [k, v] of Object.entries(event.queryStringParameters)) {
|
|
82
|
+
if (v !== undefined) sp.append(k, v);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
queryString = sp.toString();
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const headers = new Headers();
|
|
89
|
+
if (event.multiValueHeaders) {
|
|
90
|
+
for (const [k, vals] of Object.entries(event.multiValueHeaders)) {
|
|
91
|
+
if (!vals) continue;
|
|
92
|
+
for (const v of vals) headers.append(k, v);
|
|
93
|
+
}
|
|
94
|
+
} else if (event.headers) {
|
|
95
|
+
for (const [k, v] of Object.entries(event.headers)) {
|
|
96
|
+
if (v !== undefined) headers.set(k, v);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
if (event.cookies && event.cookies.length > 0 && !headers.has('cookie')) {
|
|
100
|
+
headers.set('cookie', event.cookies.join('; '));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const host = headers.get('host') || event.requestContext?.domainName || 'localhost';
|
|
104
|
+
const proto = headers.get('x-forwarded-proto') || 'https';
|
|
105
|
+
const url = `${proto}://${host}${path.startsWith('/') ? path : '/' + path}${queryString ? '?' + queryString : ''}`;
|
|
106
|
+
|
|
107
|
+
const init: RequestInit = { method, headers };
|
|
108
|
+
if (event.body != null && method !== 'GET' && method !== 'HEAD') {
|
|
109
|
+
init.body = event.isBase64Encoded ? (fromBase64(event.body) as any) : event.body;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const sourceIp =
|
|
113
|
+
event.requestContext?.http?.sourceIp ||
|
|
114
|
+
event.requestContext?.identity?.sourceIp ||
|
|
115
|
+
undefined;
|
|
116
|
+
|
|
117
|
+
const res = await app.fetch(new Request(url, init), sourceIp);
|
|
118
|
+
|
|
119
|
+
const outHeaders: Record<string, string> = {};
|
|
120
|
+
const cookies: string[] = [];
|
|
121
|
+
const multiValueHeaders: Record<string, string[]> = {};
|
|
122
|
+
|
|
123
|
+
const rawSetCookies = typeof (res.headers as any).getSetCookie === 'function'
|
|
124
|
+
? ((res.headers as any).getSetCookie() as string[])
|
|
125
|
+
: [];
|
|
126
|
+
|
|
127
|
+
res.headers.forEach((v, k) => {
|
|
128
|
+
const lower = k.toLowerCase();
|
|
129
|
+
if (lower === 'set-cookie') {
|
|
130
|
+
if (rawSetCookies.length === 0) cookies.push(v);
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
outHeaders[lower] = v;
|
|
134
|
+
if (!isV2) multiValueHeaders[lower] = [v];
|
|
135
|
+
});
|
|
136
|
+
if (rawSetCookies.length > 0) cookies.push(...rawSetCookies);
|
|
137
|
+
|
|
138
|
+
const binary = isBinaryResponse(res.headers);
|
|
139
|
+
const body = binary
|
|
140
|
+
? toBase64(new Uint8Array(await res.arrayBuffer()))
|
|
141
|
+
: await res.text();
|
|
142
|
+
|
|
143
|
+
if (isV2) {
|
|
144
|
+
return {
|
|
145
|
+
statusCode: res.status,
|
|
146
|
+
headers: outHeaders,
|
|
147
|
+
...(cookies.length > 0 ? { cookies } : {}),
|
|
148
|
+
body,
|
|
149
|
+
isBase64Encoded: binary
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (cookies.length > 0) {
|
|
154
|
+
multiValueHeaders['set-cookie'] = cookies;
|
|
155
|
+
}
|
|
156
|
+
return {
|
|
157
|
+
statusCode: res.status,
|
|
158
|
+
headers: outHeaders,
|
|
159
|
+
multiValueHeaders,
|
|
160
|
+
body,
|
|
161
|
+
isBase64Encoded: binary
|
|
162
|
+
};
|
|
163
|
+
};
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
export const handle = awsLambda;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export interface CloudflarePagesContext<Env = Record<string, any>> {
|
|
2
|
+
request: Request;
|
|
3
|
+
env: Env;
|
|
4
|
+
params: Record<string, string | string[]>;
|
|
5
|
+
waitUntil(promise: Promise<any>): void;
|
|
6
|
+
next(input?: Request | string, init?: RequestInit): Promise<Response>;
|
|
7
|
+
data: Record<string, unknown>;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
interface FetchableEdgeApp {
|
|
11
|
+
fetch(req: Request, env?: any, executionCtx?: any): Response | Promise<Response>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Cloudflare Pages Functions adapter (`onRequest`).
|
|
16
|
+
* Usage: `export const onRequest = handle(app);`
|
|
17
|
+
*/
|
|
18
|
+
export const handle = <Env = Record<string, any>>(app: FetchableEdgeApp) => {
|
|
19
|
+
return (context: CloudflarePagesContext<Env>): Response | Promise<Response> => {
|
|
20
|
+
return app.fetch(context.request, context.env, {
|
|
21
|
+
waitUntil: (p: Promise<any>) => context.waitUntil(p),
|
|
22
|
+
passThroughOnException: () => {}
|
|
23
|
+
});
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export const cloudflarePages = handle;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export interface NetlifyContext {
|
|
2
|
+
ip?: string;
|
|
3
|
+
requestId?: string;
|
|
4
|
+
site?: { id?: string; name?: string; url?: string };
|
|
5
|
+
geo?: { city?: string; country?: { code?: string; name?: string }; timezone?: string };
|
|
6
|
+
cookies?: { get(name: string): string | undefined };
|
|
7
|
+
waitUntil?(promise: Promise<any>): void;
|
|
8
|
+
[key: string]: any;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
interface FetchableApp {
|
|
12
|
+
fetch(req: Request, peerIpOrEnv?: any, executionCtx?: any): Response | Promise<Response>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Netlify Functions v2 adapter.
|
|
17
|
+
* Usage: `export default handle(app);`
|
|
18
|
+
*/
|
|
19
|
+
export const handle = (app: FetchableApp) => {
|
|
20
|
+
return (req: Request, context?: NetlifyContext): Response | Promise<Response> => {
|
|
21
|
+
const execCtx = context?.waitUntil
|
|
22
|
+
? { waitUntil: (p: Promise<any>) => context.waitUntil!(p) }
|
|
23
|
+
: undefined;
|
|
24
|
+
return app.fetch(req, context ?? {}, execCtx);
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export const netlify = handle;
|
package/src/core/bare.ts
CHANGED
|
@@ -807,6 +807,27 @@ export class BareJS<
|
|
|
807
807
|
};
|
|
808
808
|
}
|
|
809
809
|
|
|
810
|
+
const postIdx = pipeline.findIndex((fn) => fn?.__postResponse);
|
|
811
|
+
if (postIdx !== -1) {
|
|
812
|
+
const applyPost = pipeline[postIdx]!.__postResponse;
|
|
813
|
+
const innerPipeline = pipeline.filter((_, i) => i !== postIdx);
|
|
814
|
+
const innerCompiled = this.compileHandler(innerPipeline, isLog);
|
|
815
|
+
return async (ctx: Context, doLog?: any) => {
|
|
816
|
+
const res = await innerCompiled(ctx, doLog);
|
|
817
|
+
return applyPost(ctx, res);
|
|
818
|
+
};
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
const wrapIdx = pipeline.findIndex((fn) => fn?.__wrapHandler);
|
|
822
|
+
if (wrapIdx !== -1) {
|
|
823
|
+
const applyWrap = pipeline[wrapIdx]!.__wrapHandler;
|
|
824
|
+
const innerPipeline = pipeline.filter((_, i) => i !== wrapIdx);
|
|
825
|
+
const innerCompiled = this.compileHandler(innerPipeline, isLog);
|
|
826
|
+
return async (ctx: Context, doLog?: any) => {
|
|
827
|
+
return applyWrap(ctx, () => innerCompiled(ctx, doLog));
|
|
828
|
+
};
|
|
829
|
+
}
|
|
830
|
+
|
|
810
831
|
const cbIdx = pipeline.findIndex((fn) => fn?.__circuitBreaker);
|
|
811
832
|
if (cbIdx !== -1) {
|
|
812
833
|
const cbMw = pipeline[cbIdx]!;
|
|
@@ -1714,7 +1735,7 @@ export class BareJS<
|
|
|
1714
1735
|
let count = 0;
|
|
1715
1736
|
for (const route of this.routes) {
|
|
1716
1737
|
if (route.method === 'ALL') continue;
|
|
1717
|
-
if (route.path.includes('*') || route.path.includes('?') || route.path.includes('(')) continue;
|
|
1738
|
+
if (route.path.includes('*') || route.path.includes('?') || route.path.includes('(') || route.path.includes('{')) continue;
|
|
1718
1739
|
if (route.handlers.length !== 1) continue;
|
|
1719
1740
|
|
|
1720
1741
|
const rawHandler = route.handlers[0] as any;
|
|
@@ -1847,7 +1868,7 @@ export class BareJS<
|
|
|
1847
1868
|
|
|
1848
1869
|
for (const route of this.routes) {
|
|
1849
1870
|
if (route.method !== 'GET' && route.method !== 'HEAD' && route.method !== 'DELETE' && route.method !== 'OPTIONS') continue;
|
|
1850
|
-
if (route.path.includes('*') || route.path.includes('?') || route.path.includes('(')) continue;
|
|
1871
|
+
if (route.path.includes('*') || route.path.includes('?') || route.path.includes('(') || route.path.includes('{')) continue;
|
|
1851
1872
|
if (route.handlers.length !== 1) continue;
|
|
1852
1873
|
|
|
1853
1874
|
const rawHandler = route.handlers[0] as any;
|