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.
@@ -38,6 +38,7 @@ export interface RouteEndpoint {
38
38
  headers?: Record<string, any>;
39
39
  body?: any;
40
40
  response?: any;
41
+ error?: any;
41
42
  }
42
43
 
43
44
  export type RouteSchema = Record<string, RouteEndpoint>;
@@ -64,57 +65,130 @@ type EndpointOptions<R extends RouteEndpoint, P extends string, WithBody extends
64
65
  headers?: R['headers'] extends Record<string, any> ? R['headers'] & Record<string, string> : ClientRequestOptions['headers'];
65
66
  } & (WithBody extends true ? { body?: R['body'] } : {});
66
67
 
68
+ type TreatyMethodOptions<R extends RouteEndpoint, WithBody extends boolean> =
69
+ Omit<ClientRequestOptions, 'params' | 'query' | 'headers' | (WithBody extends true ? 'body' : never)> & {
70
+ query?: R['query'] extends Record<string, any> ? R['query'] : ClientRequestOptions['query'];
71
+ headers?: R['headers'] extends Record<string, any> ? R['headers'] & Record<string, string> : ClientRequestOptions['headers'];
72
+ } & (WithBody extends true ? { body?: R['body'] } : {});
73
+
74
+ type EndpointError<R extends RouteEndpoint> = 'error' extends keyof R ? R['error'] : any;
75
+
67
76
  export interface BareSafeClient<Routes extends RouteSchema = RouteSchema> {
68
77
  get<P extends PathsForMethod<Routes, 'GET'> | (string & {})>(
69
78
  path: P,
70
79
  options?: LookupRoute<Routes, 'GET', P & string> extends infer R extends RouteEndpoint
71
80
  ? EndpointOptions<R, P & string, false>
72
81
  : ClientRequestOptions
73
- ): Promise<BareClientResult<LookupRoute<Routes, 'GET', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>>;
82
+ ): Promise<BareClientResult<
83
+ LookupRoute<Routes, 'GET', P & string> extends infer R extends RouteEndpoint ? R['response'] : any,
84
+ LookupRoute<Routes, 'GET', P & string> extends infer R extends RouteEndpoint ? EndpointError<R> : any
85
+ >>;
74
86
 
75
87
  post<P extends PathsForMethod<Routes, 'POST'> | (string & {})>(
76
88
  path: P,
77
89
  options?: LookupRoute<Routes, 'POST', P & string> extends infer R extends RouteEndpoint
78
90
  ? EndpointOptions<R, P & string, true>
79
91
  : ClientRequestOptions
80
- ): Promise<BareClientResult<LookupRoute<Routes, 'POST', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>>;
92
+ ): Promise<BareClientResult<
93
+ LookupRoute<Routes, 'POST', P & string> extends infer R extends RouteEndpoint ? R['response'] : any,
94
+ LookupRoute<Routes, 'POST', P & string> extends infer R extends RouteEndpoint ? EndpointError<R> : any
95
+ >>;
81
96
 
82
97
  put<P extends PathsForMethod<Routes, 'PUT'> | (string & {})>(
83
98
  path: P,
84
99
  options?: LookupRoute<Routes, 'PUT', P & string> extends infer R extends RouteEndpoint
85
100
  ? EndpointOptions<R, P & string, true>
86
101
  : ClientRequestOptions
87
- ): Promise<BareClientResult<LookupRoute<Routes, 'PUT', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>>;
102
+ ): Promise<BareClientResult<
103
+ LookupRoute<Routes, 'PUT', P & string> extends infer R extends RouteEndpoint ? R['response'] : any,
104
+ LookupRoute<Routes, 'PUT', P & string> extends infer R extends RouteEndpoint ? EndpointError<R> : any
105
+ >>;
88
106
 
89
107
  patch<P extends PathsForMethod<Routes, 'PATCH'> | (string & {})>(
90
108
  path: P,
91
109
  options?: LookupRoute<Routes, 'PATCH', P & string> extends infer R extends RouteEndpoint
92
110
  ? EndpointOptions<R, P & string, true>
93
111
  : ClientRequestOptions
94
- ): Promise<BareClientResult<LookupRoute<Routes, 'PATCH', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>>;
112
+ ): Promise<BareClientResult<
113
+ LookupRoute<Routes, 'PATCH', P & string> extends infer R extends RouteEndpoint ? R['response'] : any,
114
+ LookupRoute<Routes, 'PATCH', P & string> extends infer R extends RouteEndpoint ? EndpointError<R> : any
115
+ >>;
95
116
 
96
117
  delete<P extends PathsForMethod<Routes, 'DELETE'> | (string & {})>(
97
118
  path: P,
98
119
  options?: LookupRoute<Routes, 'DELETE', P & string> extends infer R extends RouteEndpoint
99
120
  ? EndpointOptions<R, P & string, false>
100
121
  : ClientRequestOptions
101
- ): Promise<BareClientResult<LookupRoute<Routes, 'DELETE', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>>;
122
+ ): Promise<BareClientResult<
123
+ LookupRoute<Routes, 'DELETE', P & string> extends infer R extends RouteEndpoint ? R['response'] : any,
124
+ LookupRoute<Routes, 'DELETE', P & string> extends infer R extends RouteEndpoint ? EndpointError<R> : any
125
+ >>;
102
126
  }
103
127
 
104
- // Chained Proxy RPC type (Eden Treaty-style):
105
- // Supports api.users({ id: 42 }).get({ query }), api.orders.post({ body }), etc.
128
+ // Chained Proxy RPC fallback type (for untyped remote URLs)
106
129
  export type BareTreatyNode = {
107
- get<T = any>(options?: ClientRequestOptions): Promise<BareClientResult<T>>;
108
- post<T = any>(options?: ClientRequestOptions): Promise<BareClientResult<T>>;
109
- put<T = any>(options?: ClientRequestOptions): Promise<BareClientResult<T>>;
110
- patch<T = any>(options?: ClientRequestOptions): Promise<BareClientResult<T>>;
111
- delete<T = any>(options?: ClientRequestOptions): Promise<BareClientResult<T>>;
112
- subscribe<In = any, Out = In>(options?: { query?: Record<string, string | number | boolean | undefined> }): BareWsClient<In, Out>;
130
+ get<T = any, E = any>(options?: ClientRequestOptions): Promise<BareClientResult<T, E>>;
131
+ post<T = any, E = any>(options?: ClientRequestOptions): Promise<BareClientResult<T, E>>;
132
+ put<T = any, E = any>(options?: ClientRequestOptions): Promise<BareClientResult<T, E>>;
133
+ patch<T = any, E = any>(options?: ClientRequestOptions): Promise<BareClientResult<T, E>>;
134
+ delete<T = any, E = any>(options?: ClientRequestOptions): Promise<BareClientResult<T, E>>;
135
+ subscribe<In = any, Out = In>(options?: { query?: Record<string, string | number | boolean | undefined>; headers?: Record<string, string> }): BareWsClient<In, Out>;
113
136
  (params: Record<string, string | number> | string | number): BareTreatyNode;
114
137
  } & {
115
138
  [segment: string]: BareTreatyNode;
116
139
  };
117
140
 
141
+ // Strict compile-time path-tree builder for Eden Treaty-style autocomplete (0 runtime overhead)
142
+ type UnionToIntersection<U> = (U extends any ? (x: U) => void : never) extends (x: infer I) => void ? I : never;
143
+ type TrimLeadingSlash<P extends string> = P extends `/${infer Rest}` ? TrimLeadingSlash<Rest> : P;
144
+
145
+ type TreatyLeaf<R extends RouteEndpoint> =
146
+ R['method'] extends 'GET'
147
+ ? { get(options?: TreatyMethodOptions<R, false>): Promise<BareClientResult<R['response'], EndpointError<R>>> }
148
+ : R['method'] extends 'POST'
149
+ ? { post(options?: TreatyMethodOptions<R, true>): Promise<BareClientResult<R['response'], EndpointError<R>>> }
150
+ : R['method'] extends 'PUT'
151
+ ? { put(options?: TreatyMethodOptions<R, true>): Promise<BareClientResult<R['response'], EndpointError<R>>> }
152
+ : R['method'] extends 'PATCH'
153
+ ? { patch(options?: TreatyMethodOptions<R, true>): Promise<BareClientResult<R['response'], EndpointError<R>>> }
154
+ : R['method'] extends 'DELETE'
155
+ ? { delete(options?: TreatyMethodOptions<R, false>): Promise<BareClientResult<R['response'], EndpointError<R>>> }
156
+ : R['method'] extends 'WS'
157
+ ? {
158
+ subscribe(options?: {
159
+ query?: R['query'] extends Record<string, any> ? R['query'] : Record<string, string | number | boolean | undefined>;
160
+ headers?: R['headers'] extends Record<string, any> ? R['headers'] : Record<string, string>;
161
+ }): BareWsClient<R['response'], R['body']>;
162
+ }
163
+ : {};
164
+
165
+ type PathToTree<Path extends string, Leaf> =
166
+ Path extends ''
167
+ ? Leaf
168
+ : Path extends `:${infer Param}/${infer Rest}`
169
+ ? { (params: Record<Param, string | number> | string | number): PathToTree<Rest, Leaf> }
170
+ : Path extends `:${infer Param}`
171
+ ? { (params: Record<Param, string | number> | string | number): Leaf }
172
+ : Path extends `${infer Seg}/${infer Rest}`
173
+ ? { [K in Seg]: PathToTree<Rest, Leaf> }
174
+ : { [K in Path]: Leaf };
175
+
176
+ export type TreatyTree<Routes extends RouteSchema> =
177
+ string extends keyof Routes
178
+ ? BareTreatyNode
179
+ : [keyof Routes] extends [never]
180
+ ? BareTreatyNode
181
+ : UnionToIntersection<
182
+ {
183
+ [K in keyof Routes]: Routes[K] extends infer R extends RouteEndpoint
184
+ ? PathToTree<
185
+ TrimLeadingSlash<R['path'] extends string ? R['path'] : (K extends `${string} ${infer P}` ? P : '')>,
186
+ TreatyLeaf<R>
187
+ >
188
+ : never;
189
+ }[keyof Routes]
190
+ >;
191
+
118
192
  export interface BareClient<Routes extends RouteSchema = RouteSchema> {
119
193
  get<P extends PathsForMethod<Routes, 'GET'> | (string & {})>(
120
194
  path: P,
@@ -154,13 +228,17 @@ export interface BareClient<Routes extends RouteSchema = RouteSchema> {
154
228
  /** Discriminated Result Union client (never throws on 4xx/5xx) */
155
229
  safe: BareSafeClient<Routes>;
156
230
 
157
- /** Chained Proxy RPC client (api.users({ id: 42 }).get()) returning BareClientResult */
158
- treaty: BareTreatyNode;
231
+ /** Chained Proxy RPC client (api.users({ id: 42 }).get()) returning BareClientResult with strict compile-time inference */
232
+ treaty: TreatyTree<Routes>;
159
233
 
160
234
  /** Typed WebSocket client (supports both ws:// network URLs and in-memory BareJS app testing) */
161
235
  ws<In = any, Out = In>(
162
236
  path: string,
163
- options?: { params?: Record<string, string | number>; query?: Record<string, string | number | boolean | undefined> }
237
+ options?: {
238
+ params?: Record<string, string | number>;
239
+ query?: Record<string, string | number | boolean | undefined>;
240
+ headers?: Record<string, string>;
241
+ }
164
242
  ): BareWsClient<In, Out>;
165
243
  }
166
244
 
@@ -208,7 +286,11 @@ const serializeWsPayload = (data: any): any => {
208
286
  return JSON.stringify(data);
209
287
  };
210
288
 
211
- const createInMemoryWsClient = <In = any, Out = In>(app: any, url: string): BareWsClient<In, Out> => {
289
+ const createInMemoryWsClient = <In = any, Out = In>(
290
+ app: any,
291
+ url: string,
292
+ headers?: Record<string, string>
293
+ ): BareWsClient<In, Out> => {
212
294
  const msgListeners = new Set<(data: In) => void>();
213
295
  const openListeners = new Set<() => void>();
214
296
  const closeListeners = new Set<(code: number, reason: string) => void>();
@@ -257,7 +339,22 @@ const createInMemoryWsClient = <In = any, Out = In>(app: any, url: string): Bare
257
339
  }
258
340
  };
259
341
 
260
- queueMicrotask(() => {
342
+ queueMicrotask(async () => {
343
+ if (readyState !== 1) return;
344
+ if (matchedHandler?.__validateUpgrade) {
345
+ try {
346
+ const vr = await matchedHandler.__validateUpgrade(url, headers);
347
+ if (!vr?.ok) {
348
+ serverWs.close(1008, vr?.code || 'WS_UPGRADE_INVALID');
349
+ return;
350
+ }
351
+ if (vr.query !== undefined) serverWs.data.query = vr.query;
352
+ if (vr.headers !== undefined) serverWs.data.headers = vr.headers;
353
+ } catch {
354
+ serverWs.close(1008, 'WS_UPGRADE_INVALID');
355
+ return;
356
+ }
357
+ }
261
358
  if (readyState !== 1) return;
262
359
  matchedHandler?.open?.(serverWs);
263
360
  for (const cb of openListeners) cb();
@@ -415,10 +512,15 @@ export const bareClient = <AppOrRoutes = any>(
415
512
 
416
513
  const openWs = <In = any, Out = In>(
417
514
  path: string,
418
- options?: { params?: Record<string, string | number>; query?: Record<string, string | number | boolean | undefined> }
515
+ options?: {
516
+ params?: Record<string, string | number>;
517
+ query?: Record<string, string | number | boolean | undefined>;
518
+ headers?: Record<string, string>;
519
+ }
419
520
  ): BareWsClient<In, Out> => {
420
521
  const url = buildUrl(baseUrl, path, options);
421
- return isApp ? createInMemoryWsClient<In, Out>(baseUrlOrApp, url) : createNetworkWsClient<In, Out>(url);
522
+ const mergedHeaders = { ...defaultHeaders, ...(options?.headers || {}) };
523
+ return isApp ? createInMemoryWsClient<In, Out>(baseUrlOrApp, url, mergedHeaders) : createNetworkWsClient<In, Out>(url);
422
524
  };
423
525
 
424
526
  const makeTreatyProxy = (segments: string[]): BareTreatyNode => {
@@ -444,7 +546,8 @@ export const bareClient = <AppOrRoutes = any>(
444
546
  }
445
547
  if (prop === 'subscribe') {
446
548
  const path = '/' + segments.join('/');
447
- return (options?: { query?: Record<string, string | number | boolean | undefined> }) => openWs(path, options);
549
+ return (options?: { query?: Record<string, string | number | boolean | undefined>; headers?: Record<string, string> }) =>
550
+ openWs(path, options);
448
551
  }
449
552
  return makeTreatyProxy([...segments, prop]);
450
553
  }
@@ -472,10 +575,12 @@ export const bareClient = <AppOrRoutes = any>(
472
575
  };
473
576
 
474
577
  /**
475
- * Chained Proxy RPC client (Eden Treaty-style) returning discriminated BareClientResult unions.
476
- * Works both in-memory (`bareTreaty(app)`) and over network (`bareTreaty('https://api.example.com')`).
578
+ * Chained Proxy RPC client (Eden Treaty-style) with strict compile-time route,
579
+ * param, body, response, and per-status error inference (zero runtime overhead).
580
+ * Works both in-memory (`bareTreaty(app)`) and over network (`bareTreaty<typeof app>('https://api.example.com')`).
477
581
  */
478
582
  export const bareTreaty = <AppOrRoutes = any>(
479
583
  baseUrlOrApp: string | ({ fetch: (req: Request) => any } & AppOrRoutes),
480
584
  clientOptions: BareClientOptions = {}
481
- ): BareTreatyNode => bareClient(baseUrlOrApp, clientOptions).treaty;
585
+ ): TreatyTree<AppOrRoutes extends { __routes?: infer R extends RouteSchema } ? R : RouteSchema> =>
586
+ bareClient<AppOrRoutes>(baseUrlOrApp, clientOptions).treaty as any;