barejs 0.2.5 → 0.2.7

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.
@@ -42,6 +42,7 @@ export interface RouteEndpoint {
42
42
  headers?: Record<string, any>;
43
43
  body?: any;
44
44
  response?: any;
45
+ error?: any;
45
46
  }
46
47
  export type RouteSchema = Record<string, RouteEndpoint>;
47
48
  type RouteKey<M extends string, P extends string> = `${M} ${P}`;
@@ -56,26 +57,64 @@ type EndpointOptions<R extends RouteEndpoint, P extends string, WithBody extends
56
57
  } & (WithBody extends true ? {
57
58
  body?: R['body'];
58
59
  } : {});
60
+ type TreatyMethodOptions<R extends RouteEndpoint, WithBody extends boolean> = Omit<ClientRequestOptions, 'params' | 'query' | 'headers' | (WithBody extends true ? 'body' : never)> & {
61
+ query?: R['query'] extends Record<string, any> ? R['query'] : ClientRequestOptions['query'];
62
+ headers?: R['headers'] extends Record<string, any> ? R['headers'] & Record<string, string> : ClientRequestOptions['headers'];
63
+ } & (WithBody extends true ? {
64
+ body?: R['body'];
65
+ } : {});
66
+ type EndpointError<R extends RouteEndpoint> = 'error' extends keyof R ? R['error'] : any;
59
67
  export interface BareSafeClient<Routes extends RouteSchema = RouteSchema> {
60
- get<P extends PathsForMethod<Routes, 'GET'> | (string & {})>(path: P, options?: LookupRoute<Routes, 'GET', P & string> extends infer R extends RouteEndpoint ? EndpointOptions<R, P & string, false> : ClientRequestOptions): Promise<BareClientResult<LookupRoute<Routes, 'GET', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>>;
61
- post<P extends PathsForMethod<Routes, 'POST'> | (string & {})>(path: P, options?: LookupRoute<Routes, 'POST', P & string> extends infer R extends RouteEndpoint ? EndpointOptions<R, P & string, true> : ClientRequestOptions): Promise<BareClientResult<LookupRoute<Routes, 'POST', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>>;
62
- put<P extends PathsForMethod<Routes, 'PUT'> | (string & {})>(path: P, options?: LookupRoute<Routes, 'PUT', P & string> extends infer R extends RouteEndpoint ? EndpointOptions<R, P & string, true> : ClientRequestOptions): Promise<BareClientResult<LookupRoute<Routes, 'PUT', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>>;
63
- patch<P extends PathsForMethod<Routes, 'PATCH'> | (string & {})>(path: P, options?: LookupRoute<Routes, 'PATCH', P & string> extends infer R extends RouteEndpoint ? EndpointOptions<R, P & string, true> : ClientRequestOptions): Promise<BareClientResult<LookupRoute<Routes, 'PATCH', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>>;
64
- delete<P extends PathsForMethod<Routes, 'DELETE'> | (string & {})>(path: P, options?: LookupRoute<Routes, 'DELETE', P & string> extends infer R extends RouteEndpoint ? EndpointOptions<R, P & string, false> : ClientRequestOptions): Promise<BareClientResult<LookupRoute<Routes, 'DELETE', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>>;
68
+ get<P extends PathsForMethod<Routes, 'GET'> | (string & {})>(path: P, options?: LookupRoute<Routes, 'GET', P & string> extends infer R extends RouteEndpoint ? EndpointOptions<R, P & string, false> : ClientRequestOptions): Promise<BareClientResult<LookupRoute<Routes, 'GET', P & string> extends infer R extends RouteEndpoint ? R['response'] : any, LookupRoute<Routes, 'GET', P & string> extends infer R extends RouteEndpoint ? EndpointError<R> : any>>;
69
+ post<P extends PathsForMethod<Routes, 'POST'> | (string & {})>(path: P, options?: LookupRoute<Routes, 'POST', P & string> extends infer R extends RouteEndpoint ? EndpointOptions<R, P & string, true> : ClientRequestOptions): Promise<BareClientResult<LookupRoute<Routes, 'POST', P & string> extends infer R extends RouteEndpoint ? R['response'] : any, LookupRoute<Routes, 'POST', P & string> extends infer R extends RouteEndpoint ? EndpointError<R> : any>>;
70
+ put<P extends PathsForMethod<Routes, 'PUT'> | (string & {})>(path: P, options?: LookupRoute<Routes, 'PUT', P & string> extends infer R extends RouteEndpoint ? EndpointOptions<R, P & string, true> : ClientRequestOptions): Promise<BareClientResult<LookupRoute<Routes, 'PUT', P & string> extends infer R extends RouteEndpoint ? R['response'] : any, LookupRoute<Routes, 'PUT', P & string> extends infer R extends RouteEndpoint ? EndpointError<R> : any>>;
71
+ patch<P extends PathsForMethod<Routes, 'PATCH'> | (string & {})>(path: P, options?: LookupRoute<Routes, 'PATCH', P & string> extends infer R extends RouteEndpoint ? EndpointOptions<R, P & string, true> : ClientRequestOptions): Promise<BareClientResult<LookupRoute<Routes, 'PATCH', P & string> extends infer R extends RouteEndpoint ? R['response'] : any, LookupRoute<Routes, 'PATCH', P & string> extends infer R extends RouteEndpoint ? EndpointError<R> : any>>;
72
+ delete<P extends PathsForMethod<Routes, 'DELETE'> | (string & {})>(path: P, options?: LookupRoute<Routes, 'DELETE', P & string> extends infer R extends RouteEndpoint ? EndpointOptions<R, P & string, false> : ClientRequestOptions): Promise<BareClientResult<LookupRoute<Routes, 'DELETE', P & string> extends infer R extends RouteEndpoint ? R['response'] : any, LookupRoute<Routes, 'DELETE', P & string> extends infer R extends RouteEndpoint ? EndpointError<R> : any>>;
65
73
  }
66
74
  export type BareTreatyNode = {
67
- get<T = any>(options?: ClientRequestOptions): Promise<BareClientResult<T>>;
68
- post<T = any>(options?: ClientRequestOptions): Promise<BareClientResult<T>>;
69
- put<T = any>(options?: ClientRequestOptions): Promise<BareClientResult<T>>;
70
- patch<T = any>(options?: ClientRequestOptions): Promise<BareClientResult<T>>;
71
- delete<T = any>(options?: ClientRequestOptions): Promise<BareClientResult<T>>;
75
+ get<T = any, E = any>(options?: ClientRequestOptions): Promise<BareClientResult<T, E>>;
76
+ post<T = any, E = any>(options?: ClientRequestOptions): Promise<BareClientResult<T, E>>;
77
+ put<T = any, E = any>(options?: ClientRequestOptions): Promise<BareClientResult<T, E>>;
78
+ patch<T = any, E = any>(options?: ClientRequestOptions): Promise<BareClientResult<T, E>>;
79
+ delete<T = any, E = any>(options?: ClientRequestOptions): Promise<BareClientResult<T, E>>;
72
80
  subscribe<In = any, Out = In>(options?: {
73
81
  query?: Record<string, string | number | boolean | undefined>;
82
+ headers?: Record<string, string>;
74
83
  }): BareWsClient<In, Out>;
75
84
  (params: Record<string, string | number> | string | number): BareTreatyNode;
76
85
  } & {
77
86
  [segment: string]: BareTreatyNode;
78
87
  };
88
+ type UnionToIntersection<U> = (U extends any ? (x: U) => void : never) extends (x: infer I) => void ? I : never;
89
+ type TrimLeadingSlash<P extends string> = P extends `/${infer Rest}` ? TrimLeadingSlash<Rest> : P;
90
+ type TreatyLeaf<R extends RouteEndpoint> = R['method'] extends 'GET' ? {
91
+ get(options?: TreatyMethodOptions<R, false>): Promise<BareClientResult<R['response'], EndpointError<R>>>;
92
+ } : R['method'] extends 'POST' ? {
93
+ post(options?: TreatyMethodOptions<R, true>): Promise<BareClientResult<R['response'], EndpointError<R>>>;
94
+ } : R['method'] extends 'PUT' ? {
95
+ put(options?: TreatyMethodOptions<R, true>): Promise<BareClientResult<R['response'], EndpointError<R>>>;
96
+ } : R['method'] extends 'PATCH' ? {
97
+ patch(options?: TreatyMethodOptions<R, true>): Promise<BareClientResult<R['response'], EndpointError<R>>>;
98
+ } : R['method'] extends 'DELETE' ? {
99
+ delete(options?: TreatyMethodOptions<R, false>): Promise<BareClientResult<R['response'], EndpointError<R>>>;
100
+ } : R['method'] extends 'WS' ? {
101
+ subscribe(options?: {
102
+ query?: R['query'] extends Record<string, any> ? R['query'] : Record<string, string | number | boolean | undefined>;
103
+ headers?: R['headers'] extends Record<string, any> ? R['headers'] : Record<string, string>;
104
+ }): BareWsClient<R['response'], R['body']>;
105
+ } : {};
106
+ type PathToTree<Path extends string, Leaf> = Path extends '' ? Leaf : Path extends `:${infer Param}/${infer Rest}` ? {
107
+ (params: Record<Param, string | number> | string | number): PathToTree<Rest, Leaf>;
108
+ } : Path extends `:${infer Param}` ? {
109
+ (params: Record<Param, string | number> | string | number): Leaf;
110
+ } : Path extends `${infer Seg}/${infer Rest}` ? {
111
+ [K in Seg]: PathToTree<Rest, Leaf>;
112
+ } : {
113
+ [K in Path]: Leaf;
114
+ };
115
+ export type TreatyTree<Routes extends RouteSchema> = string extends keyof Routes ? BareTreatyNode : [keyof Routes] extends [never] ? BareTreatyNode : UnionToIntersection<{
116
+ [K in keyof Routes]: Routes[K] extends infer R extends RouteEndpoint ? PathToTree<TrimLeadingSlash<R['path'] extends string ? R['path'] : (K extends `${string} ${infer P}` ? P : '')>, TreatyLeaf<R>> : never;
117
+ }[keyof Routes]>;
79
118
  export interface BareClient<Routes extends RouteSchema = RouteSchema> {
80
119
  get<P extends PathsForMethod<Routes, 'GET'> | (string & {})>(path: P, options?: LookupRoute<Routes, 'GET', P & string> extends infer R extends RouteEndpoint ? EndpointOptions<R, P & string, false> : ClientRequestOptions): Promise<LookupRoute<Routes, 'GET', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>;
81
120
  post<P extends PathsForMethod<Routes, 'POST'> | (string & {})>(path: P, options?: LookupRoute<Routes, 'POST', P & string> extends infer R extends RouteEndpoint ? EndpointOptions<R, P & string, true> : ClientRequestOptions): Promise<LookupRoute<Routes, 'POST', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>;
@@ -84,12 +123,13 @@ export interface BareClient<Routes extends RouteSchema = RouteSchema> {
84
123
  delete<P extends PathsForMethod<Routes, 'DELETE'> | (string & {})>(path: P, options?: LookupRoute<Routes, 'DELETE', P & string> extends infer R extends RouteEndpoint ? EndpointOptions<R, P & string, false> : ClientRequestOptions): Promise<LookupRoute<Routes, 'DELETE', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>;
85
124
  /** Discriminated Result Union client (never throws on 4xx/5xx) */
86
125
  safe: BareSafeClient<Routes>;
87
- /** Chained Proxy RPC client (api.users({ id: 42 }).get()) returning BareClientResult */
88
- treaty: BareTreatyNode;
126
+ /** Chained Proxy RPC client (api.users({ id: 42 }).get()) returning BareClientResult with strict compile-time inference */
127
+ treaty: TreatyTree<Routes>;
89
128
  /** Typed WebSocket client (supports both ws:// network URLs and in-memory BareJS app testing) */
90
129
  ws<In = any, Out = In>(path: string, options?: {
91
130
  params?: Record<string, string | number>;
92
131
  query?: Record<string, string | number | boolean | undefined>;
132
+ headers?: Record<string, string>;
93
133
  }): BareWsClient<In, Out>;
94
134
  }
95
135
  export declare const bareClient: <AppOrRoutes = any>(baseUrlOrApp: string | ({
@@ -98,10 +138,13 @@ export declare const bareClient: <AppOrRoutes = any>(baseUrlOrApp: string | ({
98
138
  __routes?: infer R extends RouteSchema;
99
139
  } ? R : RouteSchema>;
100
140
  /**
101
- * Chained Proxy RPC client (Eden Treaty-style) returning discriminated BareClientResult unions.
102
- * Works both in-memory (`bareTreaty(app)`) and over network (`bareTreaty('https://api.example.com')`).
141
+ * Chained Proxy RPC client (Eden Treaty-style) with strict compile-time route,
142
+ * param, body, response, and per-status error inference (zero runtime overhead).
143
+ * Works both in-memory (`bareTreaty(app)`) and over network (`bareTreaty<typeof app>('https://api.example.com')`).
103
144
  */
104
145
  export declare const bareTreaty: <AppOrRoutes = any>(baseUrlOrApp: string | ({
105
146
  fetch: (req: Request) => any;
106
- } & AppOrRoutes), clientOptions?: BareClientOptions) => BareTreatyNode;
147
+ } & AppOrRoutes), clientOptions?: BareClientOptions) => TreatyTree<AppOrRoutes extends {
148
+ __routes?: infer R extends RouteSchema;
149
+ } ? R : RouteSchema>;
107
150
  export {};
@@ -1,8 +1,8 @@
1
- import { BareRouter, type InferSchema, type PrefixRoutes } from './router';
1
+ import { BareRouter, type InferSchema, type InferResponseSuccess, type InferResponseError, type PrefixRoutes } from './router';
2
2
  import { Context } from './context';
3
3
  import { Type as typebox, Type as t } from '@sinclair/typebox';
4
4
  import { type OpenAPIOptions } from "../utils/openapi";
5
- import type { RouteSchemas } from "../security/validators";
5
+ import { type RouteSchemas } from "../security/validators";
6
6
  import type { RouteSchema } from "../client/index";
7
7
  import type { ServeTlsOptions } from "../runtime/types";
8
8
  import { type WebSocketRouteHandler } from "./ws-match";
@@ -33,7 +33,22 @@ export interface UseLogOptions {
33
33
  format?: 'pretty' | 'json';
34
34
  onLog?: (entry: UseLogEntry) => void;
35
35
  }
36
- type TypedRouteHandler<Derived, S extends RouteSchemas, Res> = (ctx: Context & Derived & {
36
+ export interface MacroDefinition<OptVal = any, Derived extends Record<string, any> = {}, Out extends Record<string, any> = {}> {
37
+ /** Runs before the route handler when enabled on a route; return a Response to short-circuit */
38
+ beforeHandle?: (ctx: Context & Derived, value: OptVal) => Response | void | Promise<Response | void>;
39
+ /** Resolves per-route derived properties attached to ctx (auto-cleaned on pool release) */
40
+ resolve?: (ctx: Context & Derived, value: OptVal) => Out | Promise<Out>;
41
+ }
42
+ type UnionToIntersection<U> = (U extends any ? (x: U) => void : never) extends (x: infer I) => void ? I : never;
43
+ type MacroOptions<Macros extends Record<string, MacroDefinition<any, any, any>>> = {
44
+ [K in keyof Macros]?: Macros[K] extends MacroDefinition<infer V, any, any> ? V | false : any;
45
+ };
46
+ type MacroResolved<Macros extends Record<string, MacroDefinition<any, any, any>>, S> = [keyof Macros & keyof S] extends [never] ? {} : UnionToIntersection<{
47
+ [K in keyof Macros & keyof S]: S[K] extends false | undefined ? {} : Macros[K] extends {
48
+ resolve: (...args: any[]) => infer R;
49
+ } ? Awaited<R> : {};
50
+ }[keyof Macros & keyof S]>;
51
+ type TypedRouteHandler<Derived, Macros extends Record<string, MacroDefinition<any, any, any>>, S, Res> = (ctx: Context & Derived & MacroResolved<Macros, S> & {
37
52
  body: S extends {
38
53
  body: infer B;
39
54
  } ? InferSchema<B> : any;
@@ -43,11 +58,14 @@ type TypedRouteHandler<Derived, S extends RouteSchemas, Res> = (ctx: Context & D
43
58
  params: S extends {
44
59
  params: infer Pa;
45
60
  } ? InferSchema<Pa> : Record<string, any>;
61
+ cookies: S extends {
62
+ cookies: infer C;
63
+ } ? InferSchema<C> : Record<string, string>;
46
64
  }) => Res | Promise<Res>;
47
- type AddRoute<Derived extends Record<string, any>, Routes extends RouteSchema, M extends string> = {
48
- <P extends string, S extends RouteSchemas, Res = S extends {
65
+ type AddRoute<Derived extends Record<string, any>, Routes extends RouteSchema, M extends string, Macros extends Record<string, MacroDefinition<any, any, any>> = {}> = {
66
+ <P extends string, S extends RouteSchemas & MacroOptions<Macros>, Res = S extends {
49
67
  response: infer R;
50
- } ? InferSchema<R> : any>(path: P, schemas: S, handler: TypedRouteHandler<Derived, S, Res>): BareJS<Derived, Routes & Record<`${M} ${P}`, {
68
+ } ? (InferResponseSuccess<R> | InferResponseError<R>) : any>(path: P, schemas: S, handler: TypedRouteHandler<Derived, Macros, S, Res>): BareJS<Derived, Routes & Record<`${M} ${P}`, {
51
69
  method: M;
52
70
  path: P;
53
71
  params: S extends {
@@ -64,15 +82,19 @@ type AddRoute<Derived extends Record<string, any>, Routes extends RouteSchema, M
64
82
  } ? InferSchema<B> : any;
65
83
  response: S extends {
66
84
  response: infer R;
67
- } ? InferSchema<R> : Awaited<Res>;
68
- }>>;
85
+ } ? InferResponseSuccess<R> : Awaited<Res>;
86
+ error: S extends {
87
+ response: infer R;
88
+ } ? InferResponseError<R> : any;
89
+ }>, Macros>;
69
90
  <P extends string, Res = any>(path: P, ...handlers: any[]): BareJS<Derived, Routes & Record<`${M} ${P}`, {
70
91
  method: M;
71
92
  path: P;
72
93
  response: Awaited<Res>;
73
- }>>;
94
+ error: any;
95
+ }>, Macros>;
74
96
  };
75
- export declare class BareJS<Derived extends Record<string, any> = {}, Routes extends RouteSchema = {}> extends BareRouter<Routes> {
97
+ export declare class BareJS<Derived extends Record<string, any> = {}, Routes extends RouteSchema = {}, Macros extends Record<string, MacroDefinition<any, any, any>> = {}> extends BareRouter<Routes> {
76
98
  readonly __routes: Routes;
77
99
  private tree;
78
100
  private pool;
@@ -84,6 +106,7 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
84
106
  private _logFormat;
85
107
  private _logSink?;
86
108
  private _trustProxyBox;
109
+ private macros;
87
110
  protected _onRouteMutate(): void;
88
111
  private errorHandler?;
89
112
  private wsRoutes;
@@ -121,28 +144,48 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
121
144
  private notFoundHandler;
122
145
  setNotFound(handler: () => NotFoundResponse): void;
123
146
  onError(handler: (err: any, ctx: Context) => any): this;
124
- ws(path: string, handler: WebSocketRouteHandler): this;
147
+ 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
+ body?: BodySchema;
149
+ query?: QuerySchema;
150
+ headers?: HeadersSchema;
151
+ response?: ResponseSchema;
152
+ message?: (ws: any, message: BodySchema extends undefined ? (string | Buffer) : InferSchema<BodySchema>) => void | Promise<void>;
153
+ }): BareJS<Derived, Routes & Record<`WS ${P}`, {
154
+ method: 'WS';
155
+ path: P;
156
+ query: QuerySchema extends undefined ? Record<string, string> : InferSchema<QuerySchema>;
157
+ headers: HeadersSchema extends undefined ? Record<string, string> : InferSchema<HeadersSchema>;
158
+ body: BodySchema extends undefined ? any : InferSchema<BodySchema>;
159
+ response: ResponseSchema extends undefined ? any : InferSchema<ResponseSchema>;
160
+ error: any;
161
+ }>, Macros>;
125
162
  docs(pathOrOptions?: string | OpenAPIOptions, options?: OpenAPIOptions): this;
126
163
  rpc(path: string, procedures: Record<string, (params: any, ctx: Context) => any>, options?: {
127
164
  maxBatchSize?: number;
128
165
  }): this;
129
- get: AddRoute<Derived, Routes, 'GET'>;
130
- post: AddRoute<Derived, Routes, 'POST'>;
131
- put: AddRoute<Derived, Routes, 'PUT'>;
132
- patch: AddRoute<Derived, Routes, 'PATCH'>;
133
- delete: AddRoute<Derived, Routes, 'DELETE'>;
134
- options: AddRoute<Derived, Routes, 'OPTIONS'>;
135
- head: AddRoute<Derived, Routes, 'HEAD'>;
136
- all: AddRoute<Derived, Routes, 'ALL'>;
137
- route: <P extends string, R2 extends RouteSchema = {}>(prefix: P, router: BareRouter<R2>) => BareJS<Derived, Routes & PrefixRoutes<P, R2>>;
138
- use: {
139
- <R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareJS<Derived, Routes & R2>;
140
- <P extends string, R2 extends RouteSchema = {}>(prefix: P, mw: BareRouter<R2>): BareJS<Derived, Routes & PrefixRoutes<P, R2>>;
141
- (mw: any): BareJS<Derived, Routes>;
142
- };
166
+ get: AddRoute<Derived, Routes, 'GET', Macros>;
167
+ post: AddRoute<Derived, Routes, 'POST', Macros>;
168
+ put: AddRoute<Derived, Routes, 'PUT', Macros>;
169
+ patch: AddRoute<Derived, Routes, 'PATCH', Macros>;
170
+ delete: AddRoute<Derived, Routes, 'DELETE', Macros>;
171
+ options: AddRoute<Derived, Routes, 'OPTIONS', Macros>;
172
+ head: AddRoute<Derived, Routes, 'HEAD', Macros>;
173
+ all: AddRoute<Derived, Routes, 'ALL', Macros>;
174
+ route: <P extends string, R2 extends RouteSchema = {}>(prefix: P, router: BareRouter<R2>) => BareJS<Derived, Routes & PrefixRoutes<P, R2>, Macros>;
175
+ use<D2 extends Record<string, any> = {}, R2 extends RouteSchema = {}, M2 extends Record<string, MacroDefinition<any, any, any>> = {}>(mw: BareJS<D2, R2, M2>): BareJS<Derived & D2, Routes & R2, Macros & M2>;
176
+ use<P extends string, D2 extends Record<string, any> = {}, R2 extends RouteSchema = {}, M2 extends Record<string, MacroDefinition<any, any, any>> = {}>(prefix: P, mw: BareJS<D2, R2, M2>): BareJS<Derived & D2, Routes & PrefixRoutes<P, R2>, Macros & M2>;
177
+ use<R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareJS<Derived, Routes & R2, Macros>;
178
+ use<P extends string, R2 extends RouteSchema = {}>(prefix: P, mw: BareRouter<R2>): BareJS<Derived, Routes & PrefixRoutes<P, R2>, Macros>;
179
+ use(...mws: any[]): BareJS<Derived, Routes, Macros>;
180
+ /**
181
+ * Registers declarative per-route macros (`beforeHandle` and/or `resolve`).
182
+ * Zero overhead on routes that do not opt into a macro.
183
+ */
184
+ macro<M extends Record<string, MacroDefinition<any, Derived, any>>>(defs: M): BareJS<Derived, Routes, Macros & M>;
185
+ protected _add(method: string, path: string, handlers: any[]): this;
143
186
  private _hasDerive;
144
187
  private static readonly DERIVE_RESERVED;
145
- derive<T extends Record<string, any>>(fn: (ctx: Context & Derived) => Promise<T> | T): BareJS<Derived & T, Routes>;
188
+ derive<T extends Record<string, any>>(fn: (ctx: Context & Derived) => Promise<T> | T): BareJS<Derived & T, Routes, Macros>;
146
189
  private compileHandler;
147
190
  compile(): void;
148
191
  private readonly _lazyFetch;
@@ -13,6 +13,21 @@ export type InferSchema<S> = S extends {
13
13
  } ? T : S extends {
14
14
  _output: infer T;
15
15
  } ? T : any;
16
+ type SuccessStatusKey = 200 | 201 | 202 | 203 | 204 | '200' | '201' | '202' | '203' | '204';
17
+ type ErrorStatusKey = 400 | 401 | 403 | 404 | 409 | 413 | 415 | 422 | 429 | 500 | 502 | 503 | '400' | '401' | '403' | '404' | '409' | '413' | '415' | '422' | '429' | '500' | '502' | '503';
18
+ type IsSingleSchema<S> = S extends {
19
+ '~standard': any;
20
+ } ? true : S extends {
21
+ static: any;
22
+ } ? true : S extends {
23
+ _output: any;
24
+ } ? true : S extends {
25
+ type: string;
26
+ } ? true : S extends {
27
+ properties: Record<string, any>;
28
+ } ? true : false;
29
+ export type InferResponseSuccess<R> = IsSingleSchema<R> extends true ? InferSchema<R> : R extends Record<string | number, any> ? ([Extract<keyof R, SuccessStatusKey>] extends [never] ? InferSchema<R[keyof R]> : InferSchema<R[Extract<keyof R, SuccessStatusKey>]>) : InferSchema<R>;
30
+ export type InferResponseError<R> = IsSingleSchema<R> extends true ? any : R extends Record<string | number, any> ? ([Extract<keyof R, ErrorStatusKey>] extends [never] ? any : InferSchema<R[Extract<keyof R, ErrorStatusKey>]>) : any;
16
31
  type StripLeadingSlash<S extends string> = S extends `/${infer Rest}` ? StripLeadingSlash<Rest> : S;
17
32
  type StripTrailingSlash<S extends string> = S extends `${infer Rest}/` ? StripTrailingSlash<Rest> : S;
18
33
  type NormalizePrefix<P extends string> = StripTrailingSlash<StripLeadingSlash<P>> extends '' ? '' : `/${StripTrailingSlash<StripLeadingSlash<P>>}`;
@@ -32,11 +47,14 @@ type TypedRouterHandler<S extends RouteSchemas, Res> = (ctx: Context & {
32
47
  params: S extends {
33
48
  params: infer Pa;
34
49
  } ? InferSchema<Pa> : Record<string, any>;
50
+ cookies: S extends {
51
+ cookies: infer C;
52
+ } ? InferSchema<C> : Record<string, string>;
35
53
  }) => Res | Promise<Res>;
36
54
  type AddRouterRoute<Routes extends RouteSchema, M extends string> = {
37
55
  <P extends string, S extends RouteSchemas, Res = S extends {
38
56
  response: infer R;
39
- } ? InferSchema<R> : any>(path: P, schemas: S, handler: TypedRouterHandler<S, Res>): BareRouter<Routes & Record<`${M} ${P}`, {
57
+ } ? (InferResponseSuccess<R> | InferResponseError<R>) : any>(path: P, schemas: S, handler: TypedRouterHandler<S, Res>): BareRouter<Routes & Record<`${M} ${P}`, {
40
58
  method: M;
41
59
  path: P;
42
60
  params: S extends {
@@ -53,12 +71,16 @@ type AddRouterRoute<Routes extends RouteSchema, M extends string> = {
53
71
  } ? InferSchema<B> : any;
54
72
  response: S extends {
55
73
  response: infer R;
56
- } ? InferSchema<R> : Awaited<Res>;
74
+ } ? InferResponseSuccess<R> : Awaited<Res>;
75
+ error: S extends {
76
+ response: infer R;
77
+ } ? InferResponseError<R> : any;
57
78
  }>>;
58
79
  <P extends string, Res = any>(path: P, ...handlers: any[]): BareRouter<Routes & Record<`${M} ${P}`, {
59
80
  method: M;
60
81
  path: P;
61
82
  response: Awaited<Res>;
83
+ error: any;
62
84
  }>>;
63
85
  };
64
86
  export declare class BareRouter<Routes extends RouteSchema = {}> {
@@ -1,8 +1,40 @@
1
- export interface WebSocketRouteHandler {
1
+ export interface WebSocketRouteHandler<Body = string | Buffer, Query = any, Headers = any, Res = any> {
2
+ /** Optional schema (Standard Schema v1 / TypeBox / Zod / Native) for incoming JSON messages */
3
+ body?: any;
4
+ /** Optional schema for WebSocket upgrade query parameters */
5
+ query?: any;
6
+ /** Optional schema for WebSocket upgrade request headers */
7
+ headers?: any;
8
+ /** Optional schema describing outgoing server messages (for typed bareTreaty/bareClient) */
9
+ response?: any;
10
+ /** Optional error callback when an incoming WS message fails `body` validation */
11
+ onValidationError?: (ws: any, error: {
12
+ code: string;
13
+ error: any;
14
+ raw: any;
15
+ }) => void;
2
16
  open?: (ws: any) => void;
3
- message?: (ws: any, message: string | Buffer) => void;
17
+ message?: (ws: any, message: Body) => void | Promise<void>;
4
18
  close?: (ws: any, code: number, reason: string) => void;
5
19
  drain?: (ws: any) => void;
20
+ /** @internal Pre-compiled fail-closed upgrade validator (only present when query/headers schema is set) */
21
+ __validateUpgrade?: (urlOrReq: string | Request, headers?: Record<string, string> | Headers) => {
22
+ ok: true;
23
+ query?: Query;
24
+ headers?: Headers;
25
+ } | {
26
+ ok: false;
27
+ code: string;
28
+ error: any;
29
+ } | Promise<{
30
+ ok: true;
31
+ query?: Query;
32
+ headers?: Headers;
33
+ } | {
34
+ ok: false;
35
+ code: string;
36
+ error: any;
37
+ }>;
6
38
  }
7
39
  export interface WsMatchResult {
8
40
  handler: WebSocketRouteHandler;
@@ -95,4 +95,5 @@ export declare function createSingleflight(): {
95
95
  do<T>(key: string, fn: () => Promise<T>): Promise<T>;
96
96
  size(): number;
97
97
  };
98
+ export { tracing, serverTiming, type TracingOptions, type TracingSpan } from './utils/tracing';
98
99
  export { BareEdge as BareJS, BareRouter, Type, t, Z, z, native, standard, bareClient, bareTreaty, cors, securityHeaders, rateLimit, timeout, circuitBreaker, redisStore, healthcheck, logger, generateOpenAPISpec, renderDocsHTML };
@@ -4,8 +4,8 @@
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 WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
8
- export { BareRouter, type InferSchema, type PrefixRoutes } from './core/router';
7
+ export { BareJS, normalizePoolSize, type MacroDefinition, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
8
+ export { BareRouter, type InferSchema, type InferResponseSuccess, type InferResponseError, type PrefixRoutes } from './core/router';
9
9
  /**
10
10
  * Plugin Interface for BareJS
11
11
  */
@@ -16,8 +16,8 @@ export { Context } from './core/context';
16
16
  export type { Middleware, Handler, Next, Params, AuthUser, CookieOptions, UploadOptions, UploadedFile, UploadResult, UploadStreamOptions, UploadStreamPart } from './core/context';
17
17
  import { Type } from "@sinclair/typebox";
18
18
  export { Type, Type as T, Type as TypeBox };
19
- import { typebox, zod, native, standard, validate, schemaValidator, createResponseFilter, Z, type RouteSchemas, type RouteDetail, type StandardSchemaV1 } from './security/validators';
20
- export { typebox, typebox as t, zod, zod as z, Z, Z as Zod, native, native as n, standard, validate, validate as v, schemaValidator, createResponseFilter, type RouteSchemas, type RouteDetail, type StandardSchemaV1 };
19
+ import { typebox, zod, native, standard, validate, schemaValidator, createResponseFilter, isStatusResponseMap, Z, type RouteSchemas, type RouteDetail, type StandardSchemaV1 } from './security/validators';
20
+ export { typebox, typebox as t, zod, zod as z, Z, Z as Zod, native, native as n, standard, validate, validate as v, schemaValidator, createResponseFilter, isStatusResponseMap, type RouteSchemas, type RouteDetail, type StandardSchemaV1 };
21
21
  export { logger, type LoggerOptions, type LogEntry } from './utils/logger';
22
22
  export { healthcheck, type HealthcheckOptions, type HealthCheckFn } from './utils/health';
23
23
  export { cors, type CorsOptions } from './security/cors';
@@ -29,8 +29,10 @@ export { redisStore, type BareStore, type RateLimitStore, type IdempotencyStore,
29
29
  export { circuitBreaker, type CircuitBreakerOptions, type CircuitState } from './security/resilience';
30
30
  export { securityHeaders, type SecurityHeadersOptions } from './security/headers';
31
31
  export { staticFile, type StaticOptions, type StaticMetadataCacheOptions } from './utils/static';
32
+ export { file, type FileResponseOptions } from './utils/file';
32
33
  export { compress, type CompressOptions, type CompressionEncoding } from './utils/compress';
33
34
  export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
35
+ export { tracing, serverTiming, type TracingOptions, type TracingSpan } from './utils/tracing';
34
36
  export { bareAuth, createToken, basicAuth, hasRole, revokeToken, isTokenRevoked, type BareAuthOptions, type JwtAlgorithm } from './security/auth';
35
37
  export { Hash as Password, Hash } from './security/hash';
36
- export { bareClient, bareTreaty, type BareClient, type BareSafeClient, type BareTreatyNode, type BareClientResult, type BareWsClient, type BareClientOptions, type ClientRequestOptions, type RouteEndpoint, type RouteSchema } from './client/index';
38
+ 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';
@@ -67,11 +67,24 @@ export interface RouteSchemas {
67
67
  query?: any;
68
68
  params?: any;
69
69
  headers?: any;
70
+ cookies?: any;
70
71
  response?: any;
71
72
  /** Strip undeclared properties from validated body using JIT projector (prevents Mass Assignment) */
72
73
  stripUnknown?: boolean;
73
74
  detail?: RouteDetail;
74
75
  maxBodySize?: number;
75
76
  }
76
- export declare const createResponseFilter: (schema: any) => ((val: any) => any);
77
+ type CheckResult = {
78
+ ok: boolean;
79
+ data?: any;
80
+ error?: any;
81
+ };
82
+ type SchemaChecker = (val: any) => CheckResult | Promise<CheckResult>;
83
+ export declare const compileSingleSchema: (schema: any) => SchemaChecker;
84
+ /**
85
+ * Detects whether a `response` option is a per-status schema map
86
+ * (e.g. `{ 200: UserSchema, 404: NotFoundSchema }`) rather than a single schema.
87
+ */
88
+ export declare const isStatusResponseMap: (schema: any) => boolean;
89
+ export declare const createResponseFilter: (schema: any) => ((val: any, status?: number) => any);
77
90
  export declare const schemaValidator: (schemas: RouteSchemas) => Middleware;
@@ -0,0 +1,23 @@
1
+ export interface FileResponseOptions {
2
+ /** Optional root directory jail — blocks path traversal and symlinks escaping `root` (403) */
3
+ root?: string;
4
+ /** Override Content-Type header */
5
+ type?: string;
6
+ /** Set Content-Disposition: attachment (pass `true` for basename or a custom filename) */
7
+ download?: boolean | string;
8
+ /** Optional Cache-Control header value */
9
+ cacheControl?: string;
10
+ /** Additional custom response headers */
11
+ headers?: Record<string, string>;
12
+ /** HTTP status code (default: 200) */
13
+ status?: number;
14
+ }
15
+ /**
16
+ * Ergonomic 1-liner file response helper:
17
+ * `app.get('/logo', () => file('public/logo.png'))`
18
+ * `app.get('/dl/:name', (ctx) => file(ctx.params.name, { root: './uploads', download: true }))`
19
+ *
20
+ * Uses zero-copy `Bun.file` on Bun and streaming `fs.createReadStream` on Node.js.
21
+ * Enforces null-byte rejection and optional `root` directory/symlink containment.
22
+ */
23
+ export declare const file: (filePath: string, options?: FileResponseOptions) => Response;
@@ -0,0 +1,25 @@
1
+ import type { Middleware } from '../core/context';
2
+ export interface TracingSpan {
3
+ traceId: string;
4
+ spanId: string;
5
+ parentSpanId?: string;
6
+ traceparent: string;
7
+ method: string;
8
+ path: string;
9
+ status: number;
10
+ durationMs: number;
11
+ }
12
+ export interface TracingOptions {
13
+ /** Metric name emitted in `Server-Timing` header (default: `'app'`). Set `false` to omit. */
14
+ serverTiming?: string | false;
15
+ /** Echo W3C `traceparent` response header (default: `true`) */
16
+ exposeTraceparent?: boolean;
17
+ /** Optional span callback for forwarding to OTLP / APM / structured logger */
18
+ onSpan?: (span: TracingSpan) => void;
19
+ }
20
+ /**
21
+ * Zero-dependency W3C `traceparent` + `Server-Timing` middleware.
22
+ * Tree-shakeable and Edge-safe (uses Web Crypto `crypto.getRandomValues` + `performance.now()`).
23
+ */
24
+ export declare const tracing: (options?: TracingOptions) => Middleware;
25
+ export declare const serverTiming: (metricName?: string) => Middleware;
package/llms.txt CHANGED
@@ -1,17 +1,23 @@
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**, and **Edge Workers** (`barejs/edge` — zero `node:*` imports) with built-in security (Argon2id/scrypt, HS256/RS256/ES256 JWT, HMAC-signed HttpOnly cookies, CRLF injection protection, CSRF, Rate Limiting, Circuit Breaker, Idempotency-Key double-charge protection, Singleflight request coalescing, Mass-Assignment `stripUnknown`, Native Gzip/Brotli/Zstd `compress`, `app.cron`, Security Headers, DoS limits) and **Full Multi-Runtime Test Suite (483 tests / 6,740 assertions verified in CI across Bun, Node.js 20/22, and Deno 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**, and **Edge Workers** (`barejs/edge` — `50 KB`, zero `node:*` imports) with official scaffolding CLI **[`create-barejs`](https://github.com/xarhang/create-barejs)** (`bun create barejs my-app [--bun|--node|--node-uws|--deno]`), built-in security (Argon2id/scrypt, HS256/RS256/ES256 JWT, HMAC-signed HttpOnly cookies, CRLF injection protection, CSRF, Rate Limiting, Circuit Breaker, Idempotency-Key double-charge protection, Singleflight request coalescing, Mass-Assignment `stripUnknown`, Native Gzip/Brotli/Zstd `compress`, `app.cron`, `app.macro()`, `tracing()`/`serverTiming()`, Security Headers, DoS limits), and **Full Multi-Runtime Test Suite (491 tests / 6,801 assertions verified in CI across Bun, Node.js 20/22, and Deno 2)**.
4
4
 
5
- ## 1. Installation & Minimal App (Bun, Node.js, Deno, Edge)
5
+ ## 1. Scaffolding (`create-barejs`) & Minimal App (Bun, Node.js, Deno, Edge)
6
+ ```bash
7
+ bun create barejs my-app # Interactive (Bun, Node.js, Node.js + uWebSockets.js, Deno)
8
+ bun create barejs my-app --bun # --bun | --node | --node-uws | --deno
9
+ ```
6
10
  ```ts
7
- import { BareJS, Context, Type } from 'barejs'; // Use 'barejs/node' on Node.js (>= 20) or 'barejs/edge' on Cloudflare/Vercel/Deno Deploy
11
+ import { BareJS, Context, Type, file } from 'barejs'; // Use 'barejs/node' on Node.js (>= 20) or 'barejs/edge' on Cloudflare/Vercel/Deno Deploy
8
12
 
9
13
  // Optional poolSize (0..65536, default 1024): lazy bounded LIFO Context pool with in-flight slot clearing, shared state across JIT recompiles, & dev-mode UAF guard (0 overhead in prod)
10
14
  const app = new BareJS();
11
15
 
12
- // Direct return (Elysia style — auto-detects JSON, text, or Response)
16
+ // Direct return (auto-detects JSON, text, Response, file(), or sync/async generator streams)
13
17
  app.get('/hello/:name', (ctx: Context) => ({ hello: ctx.params.name }));
14
18
  app.get('/ping', () => 'pong');
19
+ app.get('/logo', () => file('public/logo.png')); // Or file(ctx.params.name, { root: './uploads', download: true })
20
+ app.get('/stream', function* () { yield 'Hello '; yield 'BareJS!'; }); // Pull-based ReadableStream backpressure
15
21
 
16
22
  // Wildcard catch-all route (`ctx.params['*']`)
17
23
  app.get('/files/*', (ctx: Context) => ({ filePath: ctx.params['*'] }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barejs",
3
- "version": "0.2.5",
3
+ "version": "0.2.7",
4
4
  "author": "xarhang",
5
5
  "description": "Batteries-included web framework for Bun, Node.js, and Deno with O(1) JIT routing, TypeBox/Zod validation, OpenAPI 3.1, WebSockets, JSON-RPC 2.0, and built-in security.",
6
6
  "main": "./dist/index.js",
@@ -36,8 +36,8 @@
36
36
  "test": "bun test",
37
37
  "test:node": "NODE_OPTIONS=--expose-gc vitest run && node tests/node-smoke.mjs",
38
38
  "test:deno": "deno test --allow-all --unstable-sloppy-imports --no-check --v8-flags=--expose-gc --config deno.test.json --ignore=tests/playwright.test.ts,tests/production-db.test.ts tests/ && deno run --allow-net --allow-read --allow-write --allow-env tests/deno-smoke.ts",
39
- "benchs": "bun run benchmarks/index.ts",
40
- "bench": "bun run benchmarks/head-to-head.ts",
39
+ "benchs": "NODE_ENV=production bun run benchmarks/index.ts",
40
+ "bench": "NODE_ENV=production bun run benchmarks/head-to-head.ts",
41
41
  "dev": "bun --watch Example/index.ts",
42
42
  "build": "bun ./scripts/build.ts",
43
43
  "prepublishOnly": "bun run build",