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/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 {};
|
|
@@ -94,6 +94,12 @@ type AddRoute<Derived extends Record<string, any>, Routes extends RouteSchema, M
|
|
|
94
94
|
error: any;
|
|
95
95
|
}>, Macros>;
|
|
96
96
|
};
|
|
97
|
+
export interface BareJSOptions {
|
|
98
|
+
/** Context object pool size (default: 1024, max: 65536). */
|
|
99
|
+
poolSize?: number;
|
|
100
|
+
/** Base path prefix applied to all registered routes (e.g. '/api' for Next.js, Astro, SvelteKit). */
|
|
101
|
+
prefix?: string;
|
|
102
|
+
}
|
|
97
103
|
export declare class BareJS<Derived extends Record<string, any> = {}, Routes extends RouteSchema = {}, Macros extends Record<string, MacroDefinition<any, any, any>> = {}> extends BareRouter<Routes> {
|
|
98
104
|
readonly __routes: Routes;
|
|
99
105
|
private tree;
|
|
@@ -140,9 +146,14 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
|
|
|
140
146
|
stop(closeActiveConnections?: boolean): Promise<void>;
|
|
141
147
|
private static readonly DEFAULT_POOL_SIZE;
|
|
142
148
|
private static readonly MAX_POOL_SIZE;
|
|
143
|
-
constructor(
|
|
149
|
+
constructor(poolSizeOrOptions?: number | BareJSOptions);
|
|
150
|
+
/**
|
|
151
|
+
* Set or append a base path prefix for all subsequently registered routes
|
|
152
|
+
* (e.g. `new BareJS().basePath('/api')` for Next.js / Astro / SvelteKit).
|
|
153
|
+
*/
|
|
154
|
+
basePath(path: string): this;
|
|
144
155
|
private notFoundHandler;
|
|
145
|
-
setNotFound(handler: () => NotFoundResponse):
|
|
156
|
+
setNotFound(handler: () => NotFoundResponse): this;
|
|
146
157
|
onError(handler: (err: any, ctx: Context) => any): this;
|
|
147
158
|
ws<P extends string, BodySchema = undefined, QuerySchema = undefined, HeadersSchema = undefined, ResponseSchema = undefined>(path: P, handler: Omit<WebSocketRouteHandler<any, any, any, any>, 'body' | 'query' | 'headers' | 'response' | 'message'> & {
|
|
148
159
|
body?: BodySchema;
|
|
@@ -182,6 +193,7 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
|
|
|
182
193
|
* Zero overhead on routes that do not opt into a macro.
|
|
183
194
|
*/
|
|
184
195
|
macro<M extends Record<string, MacroDefinition<any, Derived, any>>>(defs: M): BareJS<Derived, Routes, Macros & M>;
|
|
196
|
+
protected _createGroupRouter(prefix: string, middleware: any[]): BareRouter<any>;
|
|
185
197
|
protected _add(method: string, path: string, handlers: any[]): this;
|
|
186
198
|
private _hasDerive;
|
|
187
199
|
private static readonly DERIVE_RESERVED;
|
|
@@ -189,7 +201,7 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
|
|
|
189
201
|
private compileHandler;
|
|
190
202
|
compile(): void;
|
|
191
203
|
private readonly _lazyFetch;
|
|
192
|
-
fetch: (req: Request, peerIp?:
|
|
204
|
+
fetch: (req: Request, peerIp?: any) => any;
|
|
193
205
|
/**
|
|
194
206
|
* Ergonomic in-memory request helper for testing or internal invocations.
|
|
195
207
|
* Normalizes relative paths to http://localhost and delegates to this.fetch(req).
|
|
@@ -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'>;
|
|
@@ -99,6 +100,7 @@ export declare class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
99
100
|
options: AddRouterRoute<Routes, 'OPTIONS'>;
|
|
100
101
|
head: AddRouterRoute<Routes, 'HEAD'>;
|
|
101
102
|
all: AddRouterRoute<Routes, 'ALL'>;
|
|
103
|
+
protected _createGroupRouter(prefix: string, middleware: any[]): BareRouter<any>;
|
|
102
104
|
group: (path: string, ...args: any[]) => this;
|
|
103
105
|
private _mountRouter;
|
|
104
106
|
route<P extends string, R2 extends RouteSchema = {}>(prefix: P, router: BareRouter<R2>): BareRouter<Routes & PrefixRoutes<P, R2>>;
|
package/dist/types/edge.d.ts
CHANGED
|
@@ -63,17 +63,28 @@ export declare class EdgeContext<Env = Record<string, any>> {
|
|
|
63
63
|
send(msg: string, extra?: Record<string, any>): Response;
|
|
64
64
|
redirect(url: string, status?: number): Response;
|
|
65
65
|
}
|
|
66
|
+
export interface BareEdgeOptions {
|
|
67
|
+
/** Base path prefix applied to all registered routes (e.g. '/api'). */
|
|
68
|
+
prefix?: string;
|
|
69
|
+
}
|
|
66
70
|
/**
|
|
67
71
|
* Zero-Node Edge Web Framework (`barejs/edge`).
|
|
68
72
|
* Drop-in `export default app` for Cloudflare Workers, Vercel Edge, Deno Deploy, and Bun.
|
|
69
73
|
*/
|
|
70
74
|
export declare class BareEdge<Env = Record<string, any>> {
|
|
75
|
+
private prefix;
|
|
71
76
|
private staticRoutes;
|
|
72
77
|
private dynamicTrees;
|
|
73
78
|
private middlewares;
|
|
74
79
|
private requestHooks;
|
|
75
80
|
private responseHooks;
|
|
76
81
|
private errorHandler;
|
|
82
|
+
constructor(options?: BareEdgeOptions);
|
|
83
|
+
/**
|
|
84
|
+
* Set or append a base path prefix for all subsequently registered routes
|
|
85
|
+
* (e.g. `new BareEdge().basePath('/api')` for Next.js Edge / Astro / SvelteKit).
|
|
86
|
+
*/
|
|
87
|
+
basePath(path: string): this;
|
|
77
88
|
use(mw: EdgeMiddleware<Env>): this;
|
|
78
89
|
onRequest(fn: (ctx: EdgeContext<Env>) => Promise<void> | void): this;
|
|
79
90
|
onResponse(fn: (ctx: EdgeContext<Env>, res: Response) => Promise<void> | void): this;
|
|
@@ -96,4 +107,6 @@ export declare function createSingleflight(): {
|
|
|
96
107
|
size(): number;
|
|
97
108
|
};
|
|
98
109
|
export { tracing, serverTiming, type TracingOptions, type TracingSpan } from './utils/tracing';
|
|
110
|
+
export { html, raw, escapeHtml, type HtmlString } from './utils/html';
|
|
111
|
+
export { etag, type EtagOptions } from './utils/etag';
|
|
99
112
|
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
|
@@ -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, normalizePoolSize, type MacroDefinition, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
|
|
7
|
+
export { BareJS, normalizePoolSize, type BareJSOptions, type MacroDefinition, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
|
|
8
8
|
export { BareRouter, type InferSchema, type InferResponseSuccess, type InferResponseError, type PrefixRoutes } from './core/router';
|
|
9
9
|
/**
|
|
10
10
|
* Plugin Interface for BareJS
|
|
@@ -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
|
|
3
|
+
> BareJS is a batteries-included, JIT-compiled TypeScript 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**, **Netlify**, and **Meta Frameworks** (Next.js App Router, Astro, SvelteKit, Nuxt/Nitro, Remix, SolidStart, TanStack Start via `new BareJS({ prefix: '/api' })` + `export const GET = app.fetch`) with official scaffolding CLI **[`create-barejs`](https://github.com/xarhang/create-barejs)** and **508 tests across 38 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
|
|
@@ -10,7 +23,7 @@ bun create barejs my-app --bun # --bun | --node | --node-uws | --deno
|
|
|
10
23
|
```ts
|
|
11
24
|
import { BareJS, Context, Type, file } from 'barejs'; // Use 'barejs/node' on Node.js (>= 20) or 'barejs/edge' on Cloudflare/Vercel/Deno Deploy
|
|
12
25
|
|
|
13
|
-
// Optional poolSize (0..65536, default 1024): lazy bounded LIFO Context pool
|
|
26
|
+
// Optional { poolSize, prefix } (or numeric poolSize 0..65536, default 1024): lazy bounded LIFO Context pool + optional base path prefix (e.g. `new BareJS({ prefix: '/api' })` or `app.basePath('/api')`)
|
|
14
27
|
const app = new BareJS();
|
|
15
28
|
|
|
16
29
|
// Direct return (auto-detects JSON, text, Response, file(), or sync/async generator streams)
|
|
@@ -27,7 +40,7 @@ app.listen(3000); // or app.listen(8443, '0.0.0.0', false, { tls: { keyFileName,
|
|
|
27
40
|
```
|
|
28
41
|
|
|
29
42
|
## 2. Routing, Plugins & Unified Schema Validation
|
|
30
|
-
Methods: `app.get`, `app.post`, `app.put`, `app.patch`, `app.delete`, `app.options`, `app.
|
|
43
|
+
Methods: `app.get`, `app.post`, `app.put`, `app.patch`, `app.delete`, `app.options`, `app.all`, `app.basePath(prefix)`, `app.group(prefix, fn)`, `app.route(prefix, router)`, `app.use(mwOrRouterOrPlugin)`.
|
|
31
44
|
Pass a `RouteSchemas` object directly before the handler for AOT-compiled validation + auto-coercion (`number`/`integer`/`boolean` on `query` & `params`):
|
|
32
45
|
```ts
|
|
33
46
|
app.post('/users/:id', {
|
|
@@ -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.9",
|
|
4
4
|
"author": "xarhang",
|
|
5
|
-
"description": "Batteries-included web framework for Bun, Node.js,
|
|
5
|
+
"description": "Batteries-included 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 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;
|