barejs 0.2.5 → 0.2.6

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;
@@ -44,10 +59,10 @@ type TypedRouteHandler<Derived, S extends RouteSchemas, Res> = (ctx: Context & D
44
59
  params: infer Pa;
45
60
  } ? InferSchema<Pa> : Record<string, any>;
46
61
  }) => 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 {
62
+ type AddRoute<Derived extends Record<string, any>, Routes extends RouteSchema, M extends string, Macros extends Record<string, MacroDefinition<any, any, any>> = {}> = {
63
+ <P extends string, S extends RouteSchemas & MacroOptions<Macros>, Res = S extends {
49
64
  response: infer R;
50
- } ? InferSchema<R> : any>(path: P, schemas: S, handler: TypedRouteHandler<Derived, S, Res>): BareJS<Derived, Routes & Record<`${M} ${P}`, {
65
+ } ? (InferResponseSuccess<R> | InferResponseError<R>) : any>(path: P, schemas: S, handler: TypedRouteHandler<Derived, Macros, S, Res>): BareJS<Derived, Routes & Record<`${M} ${P}`, {
51
66
  method: M;
52
67
  path: P;
53
68
  params: S extends {
@@ -64,15 +79,19 @@ type AddRoute<Derived extends Record<string, any>, Routes extends RouteSchema, M
64
79
  } ? InferSchema<B> : any;
65
80
  response: S extends {
66
81
  response: infer R;
67
- } ? InferSchema<R> : Awaited<Res>;
68
- }>>;
82
+ } ? InferResponseSuccess<R> : Awaited<Res>;
83
+ error: S extends {
84
+ response: infer R;
85
+ } ? InferResponseError<R> : any;
86
+ }>, Macros>;
69
87
  <P extends string, Res = any>(path: P, ...handlers: any[]): BareJS<Derived, Routes & Record<`${M} ${P}`, {
70
88
  method: M;
71
89
  path: P;
72
90
  response: Awaited<Res>;
73
- }>>;
91
+ error: any;
92
+ }>, Macros>;
74
93
  };
75
- export declare class BareJS<Derived extends Record<string, any> = {}, Routes extends RouteSchema = {}> extends BareRouter<Routes> {
94
+ export declare class BareJS<Derived extends Record<string, any> = {}, Routes extends RouteSchema = {}, Macros extends Record<string, MacroDefinition<any, any, any>> = {}> extends BareRouter<Routes> {
76
95
  readonly __routes: Routes;
77
96
  private tree;
78
97
  private pool;
@@ -84,6 +103,7 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
84
103
  private _logFormat;
85
104
  private _logSink?;
86
105
  private _trustProxyBox;
106
+ private macros;
87
107
  protected _onRouteMutate(): void;
88
108
  private errorHandler?;
89
109
  private wsRoutes;
@@ -121,28 +141,48 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
121
141
  private notFoundHandler;
122
142
  setNotFound(handler: () => NotFoundResponse): void;
123
143
  onError(handler: (err: any, ctx: Context) => any): this;
124
- ws(path: string, handler: WebSocketRouteHandler): this;
144
+ 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'> & {
145
+ body?: BodySchema;
146
+ query?: QuerySchema;
147
+ headers?: HeadersSchema;
148
+ response?: ResponseSchema;
149
+ message?: (ws: any, message: BodySchema extends undefined ? (string | Buffer) : InferSchema<BodySchema>) => void | Promise<void>;
150
+ }): BareJS<Derived, Routes & Record<`WS ${P}`, {
151
+ method: 'WS';
152
+ path: P;
153
+ query: QuerySchema extends undefined ? Record<string, string> : InferSchema<QuerySchema>;
154
+ headers: HeadersSchema extends undefined ? Record<string, string> : InferSchema<HeadersSchema>;
155
+ body: BodySchema extends undefined ? any : InferSchema<BodySchema>;
156
+ response: ResponseSchema extends undefined ? any : InferSchema<ResponseSchema>;
157
+ error: any;
158
+ }>, Macros>;
125
159
  docs(pathOrOptions?: string | OpenAPIOptions, options?: OpenAPIOptions): this;
126
160
  rpc(path: string, procedures: Record<string, (params: any, ctx: Context) => any>, options?: {
127
161
  maxBatchSize?: number;
128
162
  }): 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>>;
163
+ get: AddRoute<Derived, Routes, 'GET', Macros>;
164
+ post: AddRoute<Derived, Routes, 'POST', Macros>;
165
+ put: AddRoute<Derived, Routes, 'PUT', Macros>;
166
+ patch: AddRoute<Derived, Routes, 'PATCH', Macros>;
167
+ delete: AddRoute<Derived, Routes, 'DELETE', Macros>;
168
+ options: AddRoute<Derived, Routes, 'OPTIONS', Macros>;
169
+ head: AddRoute<Derived, Routes, 'HEAD', Macros>;
170
+ all: AddRoute<Derived, Routes, 'ALL', Macros>;
171
+ route: <P extends string, R2 extends RouteSchema = {}>(prefix: P, router: BareRouter<R2>) => BareJS<Derived, Routes & PrefixRoutes<P, R2>, Macros>;
138
172
  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>;
173
+ <R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareJS<Derived, Routes & R2, Macros>;
174
+ <P extends string, R2 extends RouteSchema = {}>(prefix: P, mw: BareRouter<R2>): BareJS<Derived, Routes & PrefixRoutes<P, R2>, Macros>;
175
+ (mw: any): BareJS<Derived, Routes, Macros>;
142
176
  };
177
+ /**
178
+ * Registers declarative per-route macros (`beforeHandle` and/or `resolve`).
179
+ * Zero overhead on routes that do not opt into a macro.
180
+ */
181
+ macro<M extends Record<string, MacroDefinition<any, Derived, any>>>(defs: M): BareJS<Derived, Routes, Macros & M>;
182
+ protected _add(method: string, path: string, handlers: any[]): this;
143
183
  private _hasDerive;
144
184
  private static readonly DERIVE_RESERVED;
145
- derive<T extends Record<string, any>>(fn: (ctx: Context & Derived) => Promise<T> | T): BareJS<Derived & T, Routes>;
185
+ derive<T extends Record<string, any>>(fn: (ctx: Context & Derived) => Promise<T> | T): BareJS<Derived & T, Routes, Macros>;
146
186
  private compileHandler;
147
187
  compile(): void;
148
188
  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>>}`;
@@ -36,7 +51,7 @@ type TypedRouterHandler<S extends RouteSchemas, Res> = (ctx: Context & {
36
51
  type AddRouterRoute<Routes extends RouteSchema, M extends string> = {
37
52
  <P extends string, S extends RouteSchemas, Res = S extends {
38
53
  response: infer R;
39
- } ? InferSchema<R> : any>(path: P, schemas: S, handler: TypedRouterHandler<S, Res>): BareRouter<Routes & Record<`${M} ${P}`, {
54
+ } ? (InferResponseSuccess<R> | InferResponseError<R>) : any>(path: P, schemas: S, handler: TypedRouterHandler<S, Res>): BareRouter<Routes & Record<`${M} ${P}`, {
40
55
  method: M;
41
56
  path: P;
42
57
  params: S extends {
@@ -53,12 +68,16 @@ type AddRouterRoute<Routes extends RouteSchema, M extends string> = {
53
68
  } ? InferSchema<B> : any;
54
69
  response: S extends {
55
70
  response: infer R;
56
- } ? InferSchema<R> : Awaited<Res>;
71
+ } ? InferResponseSuccess<R> : Awaited<Res>;
72
+ error: S extends {
73
+ response: infer R;
74
+ } ? InferResponseError<R> : any;
57
75
  }>>;
58
76
  <P extends string, Res = any>(path: P, ...handlers: any[]): BareRouter<Routes & Record<`${M} ${P}`, {
59
77
  method: M;
60
78
  path: P;
61
79
  response: Awaited<Res>;
80
+ error: any;
62
81
  }>>;
63
82
  };
64
83
  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';
@@ -31,6 +31,7 @@ export { securityHeaders, type SecurityHeadersOptions } from './security/headers
31
31
  export { staticFile, type StaticOptions, type StaticMetadataCacheOptions } from './utils/static';
32
32
  export { compress, type CompressOptions, type CompressionEncoding } from './utils/compress';
33
33
  export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
34
+ export { tracing, serverTiming, type TracingOptions, type TracingSpan } from './utils/tracing';
34
35
  export { bareAuth, createToken, basicAuth, hasRole, revokeToken, isTokenRevoked, type BareAuthOptions, type JwtAlgorithm } from './security/auth';
35
36
  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';
37
+ 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';
@@ -73,5 +73,17 @@ export interface RouteSchemas {
73
73
  detail?: RouteDetail;
74
74
  maxBodySize?: number;
75
75
  }
76
- export declare const createResponseFilter: (schema: any) => ((val: any) => any);
76
+ type CheckResult = {
77
+ ok: boolean;
78
+ data?: any;
79
+ error?: any;
80
+ };
81
+ type SchemaChecker = (val: any) => CheckResult | Promise<CheckResult>;
82
+ export declare const compileSingleSchema: (schema: any) => SchemaChecker;
83
+ /**
84
+ * Detects whether a `response` option is a per-status schema map
85
+ * (e.g. `{ 200: UserSchema, 404: NotFoundSchema }`) rather than a single schema.
86
+ */
87
+ export declare const isStatusResponseMap: (schema: any) => boolean;
88
+ export declare const createResponseFilter: (schema: any) => ((val: any, status?: number) => any);
77
89
  export declare const schemaValidator: (schemas: RouteSchemas) => Middleware;
@@ -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,8 +1,12 @@
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` — 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`, Security Headers, DoS limits), and **Full Multi-Runtime Test Suite (487 tests / 6,772 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
11
  import { BareJS, Context, Type } from 'barejs'; // Use 'barejs/node' on Node.js (>= 20) or 'barejs/edge' on Cloudflare/Vercel/Deno Deploy
8
12
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barejs",
3
- "version": "0.2.5",
3
+ "version": "0.2.6",
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",