barejs 0.2.4 → 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.
@@ -8,6 +8,27 @@ export interface BareClientOptions {
8
8
  headers?: Record<string, string>;
9
9
  fetch?: typeof fetch;
10
10
  }
11
+ export type BareClientResult<T = any, E = any> = {
12
+ ok: true;
13
+ data: T;
14
+ error: null;
15
+ status: number;
16
+ headers: Headers;
17
+ } | {
18
+ ok: false;
19
+ data: null;
20
+ error: E;
21
+ status: number;
22
+ headers: Headers;
23
+ };
24
+ export interface BareWsClient<In = any, Out = In> {
25
+ send(data: Out): void;
26
+ onMessage(cb: (data: In) => void): () => void;
27
+ onOpen(cb: () => void): () => void;
28
+ onClose(cb: (code: number, reason: string) => void): () => void;
29
+ close(code?: number, reason?: string): void;
30
+ readonly readyState: number;
31
+ }
11
32
  type ExtractParams<Path extends string> = Path extends `${string}:${infer Param}/${infer Rest}` ? {
12
33
  [K in Param | keyof ExtractParams<`/${Rest}`>]: string | number;
13
34
  } : Path extends `${string}:${infer Param}` ? {
@@ -21,6 +42,7 @@ export interface RouteEndpoint {
21
42
  headers?: Record<string, any>;
22
43
  body?: any;
23
44
  response?: any;
45
+ error?: any;
24
46
  }
25
47
  export type RouteSchema = Record<string, RouteEndpoint>;
26
48
  type RouteKey<M extends string, P extends string> = `${M} ${P}`;
@@ -35,16 +57,94 @@ type EndpointOptions<R extends RouteEndpoint, P extends string, WithBody extends
35
57
  } & (WithBody extends true ? {
36
58
  body?: R['body'];
37
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;
67
+ export interface BareSafeClient<Routes extends RouteSchema = RouteSchema> {
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>>;
73
+ }
74
+ export type BareTreatyNode = {
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>>;
80
+ subscribe<In = any, Out = In>(options?: {
81
+ query?: Record<string, string | number | boolean | undefined>;
82
+ headers?: Record<string, string>;
83
+ }): BareWsClient<In, Out>;
84
+ (params: Record<string, string | number> | string | number): BareTreatyNode;
85
+ } & {
86
+ [segment: string]: BareTreatyNode;
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]>;
38
118
  export interface BareClient<Routes extends RouteSchema = RouteSchema> {
39
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>;
40
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>;
41
121
  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<LookupRoute<Routes, 'PUT', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>;
42
122
  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<LookupRoute<Routes, 'PATCH', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>;
43
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>;
124
+ /** Discriminated Result Union client (never throws on 4xx/5xx) */
125
+ safe: BareSafeClient<Routes>;
126
+ /** Chained Proxy RPC client (api.users({ id: 42 }).get()) returning BareClientResult with strict compile-time inference */
127
+ treaty: TreatyTree<Routes>;
128
+ /** Typed WebSocket client (supports both ws:// network URLs and in-memory BareJS app testing) */
129
+ ws<In = any, Out = In>(path: string, options?: {
130
+ params?: Record<string, string | number>;
131
+ query?: Record<string, string | number | boolean | undefined>;
132
+ headers?: Record<string, string>;
133
+ }): BareWsClient<In, Out>;
44
134
  }
45
135
  export declare const bareClient: <AppOrRoutes = any>(baseUrlOrApp: string | ({
46
136
  fetch: (req: Request) => any;
47
137
  } & AppOrRoutes), clientOptions?: BareClientOptions) => BareClient<AppOrRoutes extends {
48
138
  __routes?: infer R extends RouteSchema;
49
139
  } ? R : RouteSchema>;
140
+ /**
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')`).
144
+ */
145
+ export declare const bareTreaty: <AppOrRoutes = any>(baseUrlOrApp: string | ({
146
+ fetch: (req: Request) => any;
147
+ } & AppOrRoutes), clientOptions?: BareClientOptions) => TreatyTree<AppOrRoutes extends {
148
+ __routes?: infer R extends RouteSchema;
149
+ } ? R : RouteSchema>;
50
150
  export {};
@@ -1,11 +1,12 @@
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
+ import type { ServeTlsOptions } from "../runtime/types";
7
8
  import { type WebSocketRouteHandler } from "./ws-match";
8
- export type { WebSocketRouteHandler };
9
+ export type { WebSocketRouteHandler, ServeTlsOptions };
9
10
  export declare function normalizePoolSize(poolSize: number, defaultSize?: number, maximumSize?: number): number;
10
11
  export interface CronOptions {
11
12
  /** Execute the cron job immediately upon registration (default: false) */
@@ -32,7 +33,22 @@ export interface UseLogOptions {
32
33
  format?: 'pretty' | 'json';
33
34
  onLog?: (entry: UseLogEntry) => void;
34
35
  }
35
- 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> & {
36
52
  body: S extends {
37
53
  body: infer B;
38
54
  } ? InferSchema<B> : any;
@@ -43,10 +59,10 @@ type TypedRouteHandler<Derived, S extends RouteSchemas, Res> = (ctx: Context & D
43
59
  params: infer Pa;
44
60
  } ? InferSchema<Pa> : Record<string, any>;
45
61
  }) => Res | Promise<Res>;
46
- type AddRoute<Derived extends Record<string, any>, Routes extends RouteSchema, M extends string> = {
47
- <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 {
48
64
  response: infer R;
49
- } ? 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}`, {
50
66
  method: M;
51
67
  path: P;
52
68
  params: S extends {
@@ -63,15 +79,19 @@ type AddRoute<Derived extends Record<string, any>, Routes extends RouteSchema, M
63
79
  } ? InferSchema<B> : any;
64
80
  response: S extends {
65
81
  response: infer R;
66
- } ? InferSchema<R> : Awaited<Res>;
67
- }>>;
82
+ } ? InferResponseSuccess<R> : Awaited<Res>;
83
+ error: S extends {
84
+ response: infer R;
85
+ } ? InferResponseError<R> : any;
86
+ }>, Macros>;
68
87
  <P extends string, Res = any>(path: P, ...handlers: any[]): BareJS<Derived, Routes & Record<`${M} ${P}`, {
69
88
  method: M;
70
89
  path: P;
71
90
  response: Awaited<Res>;
72
- }>>;
91
+ error: any;
92
+ }>, Macros>;
73
93
  };
74
- 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> {
75
95
  readonly __routes: Routes;
76
96
  private tree;
77
97
  private pool;
@@ -83,6 +103,7 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
83
103
  private _logFormat;
84
104
  private _logSink?;
85
105
  private _trustProxyBox;
106
+ private macros;
86
107
  protected _onRouteMutate(): void;
87
108
  private errorHandler?;
88
109
  private wsRoutes;
@@ -120,28 +141,48 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
120
141
  private notFoundHandler;
121
142
  setNotFound(handler: () => NotFoundResponse): void;
122
143
  onError(handler: (err: any, ctx: Context) => any): this;
123
- 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>;
124
159
  docs(pathOrOptions?: string | OpenAPIOptions, options?: OpenAPIOptions): this;
125
160
  rpc(path: string, procedures: Record<string, (params: any, ctx: Context) => any>, options?: {
126
161
  maxBatchSize?: number;
127
162
  }): this;
128
- get: AddRoute<Derived, Routes, 'GET'>;
129
- post: AddRoute<Derived, Routes, 'POST'>;
130
- put: AddRoute<Derived, Routes, 'PUT'>;
131
- patch: AddRoute<Derived, Routes, 'PATCH'>;
132
- delete: AddRoute<Derived, Routes, 'DELETE'>;
133
- options: AddRoute<Derived, Routes, 'OPTIONS'>;
134
- head: AddRoute<Derived, Routes, 'HEAD'>;
135
- all: AddRoute<Derived, Routes, 'ALL'>;
136
- 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>;
137
172
  use: {
138
- <R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareJS<Derived, Routes & R2>;
139
- <P extends string, R2 extends RouteSchema = {}>(prefix: P, mw: BareRouter<R2>): BareJS<Derived, Routes & PrefixRoutes<P, R2>>;
140
- (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>;
141
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;
142
183
  private _hasDerive;
143
184
  private static readonly DERIVE_RESERVED;
144
- 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>;
145
186
  private compileHandler;
146
187
  compile(): void;
147
188
  private readonly _lazyFetch;
@@ -159,11 +200,13 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
159
200
  maxRequestBodySize?: number;
160
201
  trustProxy?: boolean | string[];
161
202
  engine?: 'auto' | 'http' | 'uws';
203
+ tls?: ServeTlsOptions;
162
204
  }): any;
163
205
  listenCluster(port?: number, workers?: number, hostname?: string, options?: {
164
206
  maxRequestBodySize?: number;
165
207
  trustProxy?: boolean | string[];
166
208
  engine?: 'auto' | 'http' | 'uws';
209
+ tls?: ServeTlsOptions;
167
210
  }): Promise<{
168
211
  stop: () => Promise<void> | void;
169
212
  workers: number;
@@ -89,6 +89,7 @@ export declare class Context {
89
89
  get(key: string): any;
90
90
  setHeader(name: string, value: string): this;
91
91
  get user(): AuthUser | undefined;
92
+ set user(value: AuthUser | undefined);
92
93
  send(message: string, extra?: Record<string, any>): Response;
93
94
  html(content: string, status?: number): Response;
94
95
  text(content: string, status?: number): Response;
@@ -3,10 +3,31 @@ import { type RouteSchemas } from '../security/validators';
3
3
  import type { RouteEndpoint, RouteSchema } from '../client/index';
4
4
  type HandlersChain = (Middleware | Handler | RouteSchemas)[];
5
5
  export type InferSchema<S> = S extends {
6
+ '~standard': {
7
+ types?: {
8
+ output: infer T;
9
+ };
10
+ };
11
+ } ? T : S extends {
6
12
  static: infer T;
7
13
  } ? T : S extends {
8
14
  _output: infer T;
9
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;
10
31
  type StripLeadingSlash<S extends string> = S extends `/${infer Rest}` ? StripLeadingSlash<Rest> : S;
11
32
  type StripTrailingSlash<S extends string> = S extends `${infer Rest}/` ? StripTrailingSlash<Rest> : S;
12
33
  type NormalizePrefix<P extends string> = StripTrailingSlash<StripLeadingSlash<P>> extends '' ? '' : `/${StripTrailingSlash<StripLeadingSlash<P>>}`;
@@ -30,7 +51,7 @@ type TypedRouterHandler<S extends RouteSchemas, Res> = (ctx: Context & {
30
51
  type AddRouterRoute<Routes extends RouteSchema, M extends string> = {
31
52
  <P extends string, S extends RouteSchemas, Res = S extends {
32
53
  response: infer R;
33
- } ? 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}`, {
34
55
  method: M;
35
56
  path: P;
36
57
  params: S extends {
@@ -47,12 +68,16 @@ type AddRouterRoute<Routes extends RouteSchema, M extends string> = {
47
68
  } ? InferSchema<B> : any;
48
69
  response: S extends {
49
70
  response: infer R;
50
- } ? InferSchema<R> : Awaited<Res>;
71
+ } ? InferResponseSuccess<R> : Awaited<Res>;
72
+ error: S extends {
73
+ response: infer R;
74
+ } ? InferResponseError<R> : any;
51
75
  }>>;
52
76
  <P extends string, Res = any>(path: P, ...handlers: any[]): BareRouter<Routes & Record<`${M} ${P}`, {
53
77
  method: M;
54
78
  path: P;
55
79
  response: Awaited<Res>;
80
+ error: any;
56
81
  }>>;
57
82
  };
58
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;
@@ -0,0 +1,99 @@
1
+ import { BareRouter } from './core/router';
2
+ import { Type, Type as t } from '@sinclair/typebox';
3
+ import { Z, Z as z, native, standard } from './security/validators';
4
+ import { bareClient, bareTreaty } from './client/index';
5
+ import { cors } from './security/cors';
6
+ import { securityHeaders } from './security/headers';
7
+ import { rateLimit } from './security/rateLimit';
8
+ import { timeout } from './security/timeout';
9
+ import { circuitBreaker } from './security/resilience';
10
+ import { redisStore } from './security/store';
11
+ import { healthcheck } from './utils/health';
12
+ import { logger } from './utils/logger';
13
+ import { generateOpenAPISpec, renderDocsHTML } from './utils/openapi';
14
+ export type EdgeNext = () => Promise<any> | any;
15
+ export type EdgeMiddleware<Env = Record<string, any>> = (ctx: EdgeContext<Env>, next: EdgeNext) => Promise<any> | any;
16
+ export type EdgeHandler<Env = Record<string, any>> = (ctx: EdgeContext<Env>) => Promise<any> | any;
17
+ /**
18
+ * Pure Web-Standard request/response Context for Edge runtimes
19
+ * (Cloudflare Workers, Vercel Edge, Deno Deploy, Fastly Compute, Bun).
20
+ * Zero `node:*` imports.
21
+ */
22
+ export declare class EdgeContext<Env = Record<string, any>> {
23
+ req: Request;
24
+ params: Record<string, string>;
25
+ env: Env;
26
+ executionCtx: any;
27
+ store: Map<string, any>;
28
+ body: any;
29
+ user: any;
30
+ _status: number;
31
+ _headers: Record<string, string> | undefined;
32
+ _setCookies: string[] | undefined;
33
+ private _query;
34
+ private _cookies;
35
+ private _jsonCache;
36
+ private _jsonParsed;
37
+ private _requestId;
38
+ constructor(req: Request, params?: Record<string, string>, env?: Env, executionCtx?: any);
39
+ get requestId(): string;
40
+ get ip(): string;
41
+ get query(): Record<string, string>;
42
+ get cookies(): Record<string, string>;
43
+ get(key: string): any;
44
+ set(key: string, value: any): this;
45
+ status(code: number): this;
46
+ setHeader(name: string, value: string): this;
47
+ appendHeader(name: string, value: string): this;
48
+ setCookie(name: string, value: string, opts?: {
49
+ maxAge?: number;
50
+ path?: string;
51
+ domain?: string;
52
+ httpOnly?: boolean;
53
+ secure?: boolean;
54
+ sameSite?: 'Strict' | 'Lax' | 'None';
55
+ }): this;
56
+ deleteCookie(name: string, path?: string): this;
57
+ jsonBody(maxBytes?: number): Promise<any>;
58
+ textBody(): Promise<string>;
59
+ private buildHeaders;
60
+ json(data: any, status?: number): Response;
61
+ text(data: string, status?: number): Response;
62
+ html(data: string, status?: number): Response;
63
+ send(msg: string, extra?: Record<string, any>): Response;
64
+ redirect(url: string, status?: number): Response;
65
+ }
66
+ /**
67
+ * Zero-Node Edge Web Framework (`barejs/edge`).
68
+ * Drop-in `export default app` for Cloudflare Workers, Vercel Edge, Deno Deploy, and Bun.
69
+ */
70
+ export declare class BareEdge<Env = Record<string, any>> {
71
+ private staticRoutes;
72
+ private dynamicTrees;
73
+ private middlewares;
74
+ private requestHooks;
75
+ private responseHooks;
76
+ private errorHandler;
77
+ use(mw: EdgeMiddleware<Env>): this;
78
+ onRequest(fn: (ctx: EdgeContext<Env>) => Promise<void> | void): this;
79
+ onResponse(fn: (ctx: EdgeContext<Env>, res: Response) => Promise<void> | void): this;
80
+ onError(fn: (err: any, ctx: EdgeContext<Env>) => Response | Promise<Response>): this;
81
+ private add;
82
+ get(path: string, ...fns: EdgeMiddleware<Env>[]): this;
83
+ post(path: string, ...fns: EdgeMiddleware<Env>[]): this;
84
+ put(path: string, ...fns: EdgeMiddleware<Env>[]): this;
85
+ patch(path: string, ...fns: EdgeMiddleware<Env>[]): this;
86
+ delete(path: string, ...fns: EdgeMiddleware<Env>[]): this;
87
+ options(path: string, ...fns: EdgeMiddleware<Env>[]): this;
88
+ head(path: string, ...fns: EdgeMiddleware<Env>[]): this;
89
+ all(path: string, ...fns: EdgeMiddleware<Env>[]): this;
90
+ private normalizeResponse;
91
+ fetch: (req: Request, env?: Env, executionCtx?: any) => Promise<Response>;
92
+ request(path: string, init?: RequestInit, env?: Env): Promise<Response>;
93
+ }
94
+ export declare function createSingleflight(): {
95
+ do<T>(key: string, fn: () => Promise<T>): Promise<T>;
96
+ size(): number;
97
+ };
98
+ export { tracing, serverTiming, type TracingOptions, type TracingSpan } from './utils/tracing';
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, validate, schemaValidator, createResponseFilter, Z, type RouteSchemas, type RouteDetail } from './security/validators';
20
- export { typebox, typebox as t, zod, zod as z, Z, Z as Zod, native, native as n, validate, validate as v, schemaValidator, createResponseFilter, type RouteSchemas, type RouteDetail };
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, type BareClient, 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';
@@ -1,4 +1,18 @@
1
1
  import type { WebSocketRouteHandler } from '../core/ws-match';
2
+ export interface ServeTlsOptions {
3
+ /** Path to TLS private key file, or PEM string/bytes (Bun & Node https) */
4
+ key?: string | Uint8Array;
5
+ /** Path to TLS certificate file, or PEM string/bytes (Bun & Node https) */
6
+ cert?: string | Uint8Array;
7
+ /** Optional key file path alias (uWebSockets.js parity) */
8
+ keyFileName?: string;
9
+ /** Optional cert file path alias (uWebSockets.js parity) */
10
+ certFileName?: string;
11
+ /** Optional passphrase for encrypted private key */
12
+ passphrase?: string;
13
+ /** Optional CA certificate file path or PEM bytes */
14
+ ca?: string | Uint8Array;
15
+ }
2
16
  export interface ServeOptions {
3
17
  port: number;
4
18
  hostname: string;
@@ -7,6 +21,7 @@ export interface ServeOptions {
7
21
  fetch: (req: Request, peerIp?: string) => Response | Promise<Response>;
8
22
  routes?: Record<string, any>;
9
23
  engine?: 'auto' | 'http' | 'uws';
24
+ tls?: ServeTlsOptions;
10
25
  uwsRoutes?: any[];
11
26
  ws?: {
12
27
  routes: Map<string, WebSocketRouteHandler>;
@@ -19,6 +19,39 @@ export declare const native: (schema: any) => Middleware;
19
19
  * Zod Engine (z)
20
20
  */
21
21
  export declare const zod: (schema: z.ZodSchema) => Middleware;
22
+ export interface StandardSchemaV1Issue {
23
+ readonly message: string;
24
+ readonly path?: ReadonlyArray<PropertyKey | {
25
+ readonly key: PropertyKey;
26
+ }>;
27
+ }
28
+ export type StandardSchemaV1Result<Output = unknown> = {
29
+ readonly value: Output;
30
+ readonly issues?: undefined;
31
+ } | {
32
+ readonly issues: ReadonlyArray<StandardSchemaV1Issue>;
33
+ };
34
+ /**
35
+ * Standard Schema v1 interface (https://standardschema.dev)
36
+ * Supported natively by Zod 4, Valibot, ArkType, Effect, Typia, and custom validators.
37
+ */
38
+ export interface StandardSchemaV1<Input = unknown, Output = Input> {
39
+ readonly '~standard': {
40
+ readonly version: 1;
41
+ readonly vendor: string;
42
+ readonly validate: (value: unknown) => StandardSchemaV1Result<Output> | Promise<StandardSchemaV1Result<Output>>;
43
+ readonly types?: {
44
+ readonly input: Input;
45
+ readonly output: Output;
46
+ };
47
+ };
48
+ }
49
+ export declare const isStandardSchema: (schema: any) => schema is StandardSchemaV1;
50
+ /**
51
+ * Universal Standard Schema v1 Engine (Valibot, ArkType, Zod 4, Effect, etc.)
52
+ * Always awaits async validators and fails closed on issues or thrown errors.
53
+ */
54
+ export declare const standard: (schema: StandardSchemaV1) => Middleware;
22
55
  /**
23
56
  * Smart Dispatcher (v)
24
57
  */
@@ -40,5 +73,17 @@ export interface RouteSchemas {
40
73
  detail?: RouteDetail;
41
74
  maxBodySize?: number;
42
75
  }
43
- 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);
44
89
  export declare const schemaValidator: (schemas: RouteSchemas) => Middleware;