barejs 0.2.4 → 0.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +62 -33
- package/dist/edge.js +75 -0
- package/dist/index.js +185 -178
- package/dist/node.js +184 -177
- package/dist/types/client/index.d.ts +57 -0
- package/dist/types/core/bare.d.ts +4 -1
- package/dist/types/core/context.d.ts +1 -0
- package/dist/types/core/router.d.ts +6 -0
- package/dist/types/edge.d.ts +98 -0
- package/dist/types/index.d.ts +3 -3
- package/dist/types/runtime/types.d.ts +15 -0
- package/dist/types/security/validators.d.ts +33 -0
- package/llms.txt +9 -6
- package/package.json +5 -1
- package/src/client/index.ts +294 -6
- package/src/core/bare.ts +15 -5
- package/src/core/context.ts +10 -3
- package/src/core/router.ts +2 -1
- package/src/edge.ts +492 -0
- package/src/index.ts +11 -3
- package/src/runtime/bun.ts +12 -0
- package/src/runtime/node.ts +21 -3
- package/src/runtime/types.ts +16 -0
- package/src/runtime/uws.ts +10 -2
- package/src/security/auth.ts +7 -5
- package/src/security/validators.ts +194 -37
package/src/client/index.ts
CHANGED
|
@@ -10,6 +10,19 @@ export interface BareClientOptions {
|
|
|
10
10
|
fetch?: typeof fetch;
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
+
export type BareClientResult<T = any, E = any> =
|
|
14
|
+
| { ok: true; data: T; error: null; status: number; headers: Headers }
|
|
15
|
+
| { ok: false; data: null; error: E; status: number; headers: Headers };
|
|
16
|
+
|
|
17
|
+
export interface BareWsClient<In = any, Out = In> {
|
|
18
|
+
send(data: Out): void;
|
|
19
|
+
onMessage(cb: (data: In) => void): () => void;
|
|
20
|
+
onOpen(cb: () => void): () => void;
|
|
21
|
+
onClose(cb: (code: number, reason: string) => void): () => void;
|
|
22
|
+
close(code?: number, reason?: string): void;
|
|
23
|
+
readonly readyState: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
13
26
|
type ExtractParams<Path extends string> =
|
|
14
27
|
Path extends `${string}:${infer Param}/${infer Rest}`
|
|
15
28
|
? { [K in Param | keyof ExtractParams<`/${Rest}`>]: string | number }
|
|
@@ -51,6 +64,57 @@ type EndpointOptions<R extends RouteEndpoint, P extends string, WithBody extends
|
|
|
51
64
|
headers?: R['headers'] extends Record<string, any> ? R['headers'] & Record<string, string> : ClientRequestOptions['headers'];
|
|
52
65
|
} & (WithBody extends true ? { body?: R['body'] } : {});
|
|
53
66
|
|
|
67
|
+
export interface BareSafeClient<Routes extends RouteSchema = RouteSchema> {
|
|
68
|
+
get<P extends PathsForMethod<Routes, 'GET'> | (string & {})>(
|
|
69
|
+
path: P,
|
|
70
|
+
options?: LookupRoute<Routes, 'GET', P & string> extends infer R extends RouteEndpoint
|
|
71
|
+
? EndpointOptions<R, P & string, false>
|
|
72
|
+
: ClientRequestOptions
|
|
73
|
+
): Promise<BareClientResult<LookupRoute<Routes, 'GET', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>>;
|
|
74
|
+
|
|
75
|
+
post<P extends PathsForMethod<Routes, 'POST'> | (string & {})>(
|
|
76
|
+
path: P,
|
|
77
|
+
options?: LookupRoute<Routes, 'POST', P & string> extends infer R extends RouteEndpoint
|
|
78
|
+
? EndpointOptions<R, P & string, true>
|
|
79
|
+
: ClientRequestOptions
|
|
80
|
+
): Promise<BareClientResult<LookupRoute<Routes, 'POST', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>>;
|
|
81
|
+
|
|
82
|
+
put<P extends PathsForMethod<Routes, 'PUT'> | (string & {})>(
|
|
83
|
+
path: P,
|
|
84
|
+
options?: LookupRoute<Routes, 'PUT', P & string> extends infer R extends RouteEndpoint
|
|
85
|
+
? EndpointOptions<R, P & string, true>
|
|
86
|
+
: ClientRequestOptions
|
|
87
|
+
): Promise<BareClientResult<LookupRoute<Routes, 'PUT', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>>;
|
|
88
|
+
|
|
89
|
+
patch<P extends PathsForMethod<Routes, 'PATCH'> | (string & {})>(
|
|
90
|
+
path: P,
|
|
91
|
+
options?: LookupRoute<Routes, 'PATCH', P & string> extends infer R extends RouteEndpoint
|
|
92
|
+
? EndpointOptions<R, P & string, true>
|
|
93
|
+
: ClientRequestOptions
|
|
94
|
+
): Promise<BareClientResult<LookupRoute<Routes, 'PATCH', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>>;
|
|
95
|
+
|
|
96
|
+
delete<P extends PathsForMethod<Routes, 'DELETE'> | (string & {})>(
|
|
97
|
+
path: P,
|
|
98
|
+
options?: LookupRoute<Routes, 'DELETE', P & string> extends infer R extends RouteEndpoint
|
|
99
|
+
? EndpointOptions<R, P & string, false>
|
|
100
|
+
: ClientRequestOptions
|
|
101
|
+
): Promise<BareClientResult<LookupRoute<Routes, 'DELETE', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>>;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Chained Proxy RPC type (Eden Treaty-style):
|
|
105
|
+
// Supports api.users({ id: 42 }).get({ query }), api.orders.post({ body }), etc.
|
|
106
|
+
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>;
|
|
113
|
+
(params: Record<string, string | number> | string | number): BareTreatyNode;
|
|
114
|
+
} & {
|
|
115
|
+
[segment: string]: BareTreatyNode;
|
|
116
|
+
};
|
|
117
|
+
|
|
54
118
|
export interface BareClient<Routes extends RouteSchema = RouteSchema> {
|
|
55
119
|
get<P extends PathsForMethod<Routes, 'GET'> | (string & {})>(
|
|
56
120
|
path: P,
|
|
@@ -86,6 +150,18 @@ export interface BareClient<Routes extends RouteSchema = RouteSchema> {
|
|
|
86
150
|
? EndpointOptions<R, P & string, false>
|
|
87
151
|
: ClientRequestOptions
|
|
88
152
|
): Promise<LookupRoute<Routes, 'DELETE', P & string> extends infer R extends RouteEndpoint ? R['response'] : any>;
|
|
153
|
+
|
|
154
|
+
/** Discriminated Result Union client (never throws on 4xx/5xx) */
|
|
155
|
+
safe: BareSafeClient<Routes>;
|
|
156
|
+
|
|
157
|
+
/** Chained Proxy RPC client (api.users({ id: 42 }).get()) returning BareClientResult */
|
|
158
|
+
treaty: BareTreatyNode;
|
|
159
|
+
|
|
160
|
+
/** Typed WebSocket client (supports both ws:// network URLs and in-memory BareJS app testing) */
|
|
161
|
+
ws<In = any, Out = In>(
|
|
162
|
+
path: string,
|
|
163
|
+
options?: { params?: Record<string, string | number>; query?: Record<string, string | number | boolean | undefined> }
|
|
164
|
+
): BareWsClient<In, Out>;
|
|
89
165
|
}
|
|
90
166
|
|
|
91
167
|
const buildUrl = (baseUrl: string, path: string, options?: ClientRequestOptions): string => {
|
|
@@ -111,6 +187,152 @@ const buildUrl = (baseUrl: string, path: string, options?: ClientRequestOptions)
|
|
|
111
187
|
return url;
|
|
112
188
|
};
|
|
113
189
|
|
|
190
|
+
const parseWsPayload = (raw: any): any => {
|
|
191
|
+
if (typeof raw === 'string') {
|
|
192
|
+
const trimmed = raw.trim();
|
|
193
|
+
if ((trimmed.startsWith('{') && trimmed.endsWith('}')) || (trimmed.startsWith('[') && trimmed.endsWith(']'))) {
|
|
194
|
+
try {
|
|
195
|
+
return JSON.parse(trimmed);
|
|
196
|
+
} catch {
|
|
197
|
+
return raw;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
return raw;
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
const serializeWsPayload = (data: any): any => {
|
|
205
|
+
if (typeof data === 'string' || data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
|
|
206
|
+
return data;
|
|
207
|
+
}
|
|
208
|
+
return JSON.stringify(data);
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
const createInMemoryWsClient = <In = any, Out = In>(app: any, url: string): BareWsClient<In, Out> => {
|
|
212
|
+
const msgListeners = new Set<(data: In) => void>();
|
|
213
|
+
const openListeners = new Set<() => void>();
|
|
214
|
+
const closeListeners = new Set<(code: number, reason: string) => void>();
|
|
215
|
+
let readyState = 1; // OPEN
|
|
216
|
+
|
|
217
|
+
const parsed = new URL(url);
|
|
218
|
+
const wsRoutes: Map<string, any> | undefined = app?.wsRoutes;
|
|
219
|
+
let matchedHandler: any = null;
|
|
220
|
+
let matchedParams: Record<string, string> = {};
|
|
221
|
+
|
|
222
|
+
if (wsRoutes && wsRoutes.size > 0) {
|
|
223
|
+
const exact = wsRoutes.get(parsed.pathname);
|
|
224
|
+
if (exact) {
|
|
225
|
+
matchedHandler = exact;
|
|
226
|
+
} else {
|
|
227
|
+
const segs = parsed.pathname.split('/').filter(Boolean);
|
|
228
|
+
for (const [pattern, handler] of wsRoutes.entries()) {
|
|
229
|
+
const pSegs = pattern.split('/').filter(Boolean);
|
|
230
|
+
if (pSegs.length !== segs.length) continue;
|
|
231
|
+
const params: Record<string, string> = {};
|
|
232
|
+
let ok = true;
|
|
233
|
+
for (let i = 0; i < pSegs.length; i++) {
|
|
234
|
+
if (pSegs[i]!.startsWith(':')) params[pSegs[i]!.slice(1)] = decodeURIComponent(segs[i]!);
|
|
235
|
+
else if (pSegs[i] !== segs[i]) { ok = false; break; }
|
|
236
|
+
}
|
|
237
|
+
if (ok) {
|
|
238
|
+
matchedHandler = handler;
|
|
239
|
+
matchedParams = params;
|
|
240
|
+
break;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const serverWs = {
|
|
247
|
+
data: matchedHandler ? { ...matchedHandler, params: matchedParams } : { params: matchedParams },
|
|
248
|
+
send(payload: any) {
|
|
249
|
+
if (readyState !== 1) return;
|
|
250
|
+
const decoded = parseWsPayload(payload);
|
|
251
|
+
for (const cb of msgListeners) cb(decoded);
|
|
252
|
+
},
|
|
253
|
+
close(code = 1000, reason = '') {
|
|
254
|
+
if (readyState === 3) return;
|
|
255
|
+
readyState = 3;
|
|
256
|
+
for (const cb of closeListeners) cb(code, reason);
|
|
257
|
+
}
|
|
258
|
+
};
|
|
259
|
+
|
|
260
|
+
queueMicrotask(() => {
|
|
261
|
+
if (readyState !== 1) return;
|
|
262
|
+
matchedHandler?.open?.(serverWs);
|
|
263
|
+
for (const cb of openListeners) cb();
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
return {
|
|
267
|
+
get readyState() { return readyState; },
|
|
268
|
+
send(data: Out) {
|
|
269
|
+
if (readyState !== 1) throw new Error('WebSocket is closed');
|
|
270
|
+
matchedHandler?.message?.(serverWs, serializeWsPayload(data));
|
|
271
|
+
},
|
|
272
|
+
onMessage(cb) {
|
|
273
|
+
msgListeners.add(cb);
|
|
274
|
+
return () => msgListeners.delete(cb);
|
|
275
|
+
},
|
|
276
|
+
onOpen(cb) {
|
|
277
|
+
openListeners.add(cb);
|
|
278
|
+
return () => openListeners.delete(cb);
|
|
279
|
+
},
|
|
280
|
+
onClose(cb) {
|
|
281
|
+
closeListeners.add(cb);
|
|
282
|
+
return () => closeListeners.delete(cb);
|
|
283
|
+
},
|
|
284
|
+
close(code = 1000, reason = '') {
|
|
285
|
+
if (readyState === 3) return;
|
|
286
|
+
readyState = 3;
|
|
287
|
+
matchedHandler?.close?.(serverWs, code, reason);
|
|
288
|
+
for (const cb of closeListeners) cb(code, reason);
|
|
289
|
+
}
|
|
290
|
+
};
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
const createNetworkWsClient = <In = any, Out = In>(url: string): BareWsClient<In, Out> => {
|
|
294
|
+
const wsUrl = url.replace(/^http:/i, 'ws:').replace(/^https:/i, 'wss:');
|
|
295
|
+
const socket = new WebSocket(wsUrl);
|
|
296
|
+
const msgListeners = new Set<(data: In) => void>();
|
|
297
|
+
const openListeners = new Set<() => void>();
|
|
298
|
+
const closeListeners = new Set<(code: number, reason: string) => void>();
|
|
299
|
+
|
|
300
|
+
socket.onmessage = (ev) => {
|
|
301
|
+
const decoded = parseWsPayload(ev.data);
|
|
302
|
+
for (const cb of msgListeners) cb(decoded);
|
|
303
|
+
};
|
|
304
|
+
socket.onopen = () => {
|
|
305
|
+
for (const cb of openListeners) cb();
|
|
306
|
+
};
|
|
307
|
+
socket.onclose = (ev) => {
|
|
308
|
+
for (const cb of closeListeners) cb(ev.code, ev.reason);
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
return {
|
|
312
|
+
get readyState() { return socket.readyState; },
|
|
313
|
+
send(data: Out) {
|
|
314
|
+
socket.send(serializeWsPayload(data));
|
|
315
|
+
},
|
|
316
|
+
onMessage(cb) {
|
|
317
|
+
msgListeners.add(cb);
|
|
318
|
+
return () => msgListeners.delete(cb);
|
|
319
|
+
},
|
|
320
|
+
onOpen(cb) {
|
|
321
|
+
openListeners.add(cb);
|
|
322
|
+
return () => openListeners.delete(cb);
|
|
323
|
+
},
|
|
324
|
+
onClose(cb) {
|
|
325
|
+
closeListeners.add(cb);
|
|
326
|
+
return () => closeListeners.delete(cb);
|
|
327
|
+
},
|
|
328
|
+
close(code?: number, reason?: string) {
|
|
329
|
+
socket.close(code, reason);
|
|
330
|
+
}
|
|
331
|
+
};
|
|
332
|
+
};
|
|
333
|
+
|
|
334
|
+
const HTTP_METHODS = new Set(['get', 'post', 'put', 'patch', 'delete']);
|
|
335
|
+
|
|
114
336
|
export const bareClient = <AppOrRoutes = any>(
|
|
115
337
|
baseUrlOrApp: string | ({ fetch: (req: Request) => any } & AppOrRoutes),
|
|
116
338
|
clientOptions: BareClientOptions = {}
|
|
@@ -120,7 +342,7 @@ export const bareClient = <AppOrRoutes = any>(
|
|
|
120
342
|
const fetchImpl = clientOptions.fetch ?? (isApp ? ((input: any, init?: RequestInit) => baseUrlOrApp.fetch(new Request(String(input), init))) as any : fetch);
|
|
121
343
|
const defaultHeaders = clientOptions.headers ?? {};
|
|
122
344
|
|
|
123
|
-
const
|
|
345
|
+
const requestRaw = async (method: string, path: string, options?: ClientRequestOptions): Promise<BareClientResult> => {
|
|
124
346
|
const url = buildUrl(baseUrl, path, options);
|
|
125
347
|
const headers = new Headers();
|
|
126
348
|
for (const [k, v] of Object.entries(defaultHeaders)) {
|
|
@@ -175,12 +397,66 @@ export const bareClient = <AppOrRoutes = any>(
|
|
|
175
397
|
}
|
|
176
398
|
}
|
|
177
399
|
if (!res.ok) {
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
400
|
+
return { ok: false, data: null, error: data, status: res.status, headers: res.headers };
|
|
401
|
+
}
|
|
402
|
+
return { ok: true, data, error: null, status: res.status, headers: res.headers };
|
|
403
|
+
};
|
|
404
|
+
|
|
405
|
+
const request = async (method: string, path: string, options?: ClientRequestOptions) => {
|
|
406
|
+
const result = await requestRaw(method, path, options);
|
|
407
|
+
if (!result.ok) {
|
|
408
|
+
const err: any = new Error(`HTTP ${result.status}`);
|
|
409
|
+
err.status = result.status;
|
|
410
|
+
err.data = result.error;
|
|
181
411
|
throw err;
|
|
182
412
|
}
|
|
183
|
-
return data;
|
|
413
|
+
return result.data;
|
|
414
|
+
};
|
|
415
|
+
|
|
416
|
+
const openWs = <In = any, Out = In>(
|
|
417
|
+
path: string,
|
|
418
|
+
options?: { params?: Record<string, string | number>; query?: Record<string, string | number | boolean | undefined> }
|
|
419
|
+
): BareWsClient<In, Out> => {
|
|
420
|
+
const url = buildUrl(baseUrl, path, options);
|
|
421
|
+
return isApp ? createInMemoryWsClient<In, Out>(baseUrlOrApp, url) : createNetworkWsClient<In, Out>(url);
|
|
422
|
+
};
|
|
423
|
+
|
|
424
|
+
const makeTreatyProxy = (segments: string[]): BareTreatyNode => {
|
|
425
|
+
const target = ((paramArg: Record<string, string | number> | string | number) => {
|
|
426
|
+
if (typeof paramArg === 'string' || typeof paramArg === 'number') {
|
|
427
|
+
return makeTreatyProxy([...segments, encodeURIComponent(String(paramArg))]);
|
|
428
|
+
}
|
|
429
|
+
const nextSegs = [...segments];
|
|
430
|
+
for (const val of Object.values(paramArg)) {
|
|
431
|
+
nextSegs.push(encodeURIComponent(String(val)));
|
|
432
|
+
}
|
|
433
|
+
return makeTreatyProxy(nextSegs);
|
|
434
|
+
}) as any;
|
|
435
|
+
|
|
436
|
+
return new Proxy(target, {
|
|
437
|
+
get(_t, prop: string | symbol) {
|
|
438
|
+
if (typeof prop === 'symbol') return undefined;
|
|
439
|
+
if (prop === 'then' || prop === 'catch' || prop === 'finally') return undefined;
|
|
440
|
+
if (HTTP_METHODS.has(prop)) {
|
|
441
|
+
const method = prop.toUpperCase();
|
|
442
|
+
const path = '/' + segments.join('/');
|
|
443
|
+
return (options?: ClientRequestOptions) => requestRaw(method, path, options);
|
|
444
|
+
}
|
|
445
|
+
if (prop === 'subscribe') {
|
|
446
|
+
const path = '/' + segments.join('/');
|
|
447
|
+
return (options?: { query?: Record<string, string | number | boolean | undefined> }) => openWs(path, options);
|
|
448
|
+
}
|
|
449
|
+
return makeTreatyProxy([...segments, prop]);
|
|
450
|
+
}
|
|
451
|
+
});
|
|
452
|
+
};
|
|
453
|
+
|
|
454
|
+
const safe = {
|
|
455
|
+
get: (path: string, options?: ClientRequestOptions) => requestRaw('GET', path, options),
|
|
456
|
+
post: (path: string, options?: ClientRequestOptions) => requestRaw('POST', path, options),
|
|
457
|
+
put: (path: string, options?: ClientRequestOptions) => requestRaw('PUT', path, options),
|
|
458
|
+
patch: (path: string, options?: ClientRequestOptions) => requestRaw('PATCH', path, options),
|
|
459
|
+
delete: (path: string, options?: ClientRequestOptions) => requestRaw('DELETE', path, options)
|
|
184
460
|
};
|
|
185
461
|
|
|
186
462
|
return {
|
|
@@ -188,6 +464,18 @@ export const bareClient = <AppOrRoutes = any>(
|
|
|
188
464
|
post: (path: string, options?: ClientRequestOptions) => request('POST', path, options),
|
|
189
465
|
put: (path: string, options?: ClientRequestOptions) => request('PUT', path, options),
|
|
190
466
|
patch: (path: string, options?: ClientRequestOptions) => request('PATCH', path, options),
|
|
191
|
-
delete: (path: string, options?: ClientRequestOptions) => request('DELETE', path, options)
|
|
467
|
+
delete: (path: string, options?: ClientRequestOptions) => request('DELETE', path, options),
|
|
468
|
+
safe,
|
|
469
|
+
treaty: makeTreatyProxy([]),
|
|
470
|
+
ws: openWs
|
|
192
471
|
} as any;
|
|
193
472
|
};
|
|
473
|
+
|
|
474
|
+
/**
|
|
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')`).
|
|
477
|
+
*/
|
|
478
|
+
export const bareTreaty = <AppOrRoutes = any>(
|
|
479
|
+
baseUrlOrApp: string | ({ fetch: (req: Request) => any } & AppOrRoutes),
|
|
480
|
+
clientOptions: BareClientOptions = {}
|
|
481
|
+
): BareTreatyNode => bareClient(baseUrlOrApp, clientOptions).treaty;
|
package/src/core/bare.ts
CHANGED
|
@@ -10,9 +10,10 @@ import { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from "../uti
|
|
|
10
10
|
import type { RouteSchemas } from "../security/validators";
|
|
11
11
|
import type { RouteSchema } from "../client/index";
|
|
12
12
|
import { runtime, type ServerHandle } from "../runtime";
|
|
13
|
+
import type { ServeTlsOptions } from "../runtime/types";
|
|
13
14
|
import { matchWsRoute, type WebSocketRouteHandler } from "./ws-match";
|
|
14
15
|
|
|
15
|
-
export type { WebSocketRouteHandler };
|
|
16
|
+
export type { WebSocketRouteHandler, ServeTlsOptions };
|
|
16
17
|
|
|
17
18
|
export function normalizePoolSize(
|
|
18
19
|
poolSize: number,
|
|
@@ -651,8 +652,7 @@ export class BareJS<
|
|
|
651
652
|
`;
|
|
652
653
|
|
|
653
654
|
// Inline Finalizer
|
|
654
|
-
const
|
|
655
|
-
${rFilter ? 'res = rFilter(res);' : ''}
|
|
655
|
+
const finalizeBody = `
|
|
656
656
|
if (res instanceof Response) {
|
|
657
657
|
${idemCommit ? 'const ic = idemCommit(ctx, res, res.status); if (ic && ic.then) return ic.then(() => { ' + buildResFinalize + ' });' : ''}
|
|
658
658
|
${buildResFinalize}
|
|
@@ -662,6 +662,15 @@ export class BareJS<
|
|
|
662
662
|
${idemCommit ? 'const ic = idemCommit(ctx, res, finalStatus); if (ic && ic.then) return ic.then(() => { ' + buildNonResFinalize + ' });' : ''}
|
|
663
663
|
${buildNonResFinalize}
|
|
664
664
|
`;
|
|
665
|
+
const finalizeCode = rFilter
|
|
666
|
+
? `
|
|
667
|
+
res = rFilter(res);
|
|
668
|
+
if (res && typeof res.then === 'function') {
|
|
669
|
+
return res.then((v) => { res = v; ${finalizeBody} });
|
|
670
|
+
}
|
|
671
|
+
${finalizeBody}
|
|
672
|
+
`
|
|
673
|
+
: finalizeBody;
|
|
665
674
|
|
|
666
675
|
const argSig = isLog ? 'ctx, doLog' : 'ctx';
|
|
667
676
|
const noop = () => { };
|
|
@@ -1504,7 +1513,7 @@ export class BareJS<
|
|
|
1504
1513
|
port?: number,
|
|
1505
1514
|
hostname: string = '0.0.0.0',
|
|
1506
1515
|
reusePort: boolean = true,
|
|
1507
|
-
options: { maxRequestBodySize?: number; trustProxy?: boolean | string[]; engine?: 'auto' | 'http' | 'uws' } = {}
|
|
1516
|
+
options: { maxRequestBodySize?: number; trustProxy?: boolean | string[]; engine?: 'auto' | 'http' | 'uws'; tls?: ServeTlsOptions } = {}
|
|
1508
1517
|
) {
|
|
1509
1518
|
if (options.trustProxy !== undefined) {
|
|
1510
1519
|
this.trustProxy(options.trustProxy);
|
|
@@ -1542,6 +1551,7 @@ export class BareJS<
|
|
|
1542
1551
|
maxRequestBodySize,
|
|
1543
1552
|
routes: bunRoutes,
|
|
1544
1553
|
engine: options.engine,
|
|
1554
|
+
tls: options.tls,
|
|
1545
1555
|
uwsRoutes,
|
|
1546
1556
|
fetch(req: Request, peerIp?: string) {
|
|
1547
1557
|
return self.fetch(req, peerIp);
|
|
@@ -1592,7 +1602,7 @@ export class BareJS<
|
|
|
1592
1602
|
port?: number,
|
|
1593
1603
|
workers?: number,
|
|
1594
1604
|
hostname: string = '0.0.0.0',
|
|
1595
|
-
options: { maxRequestBodySize?: number; trustProxy?: boolean | string[]; engine?: 'auto' | 'http' | 'uws' } = {}
|
|
1605
|
+
options: { maxRequestBodySize?: number; trustProxy?: boolean | string[]; engine?: 'auto' | 'http' | 'uws'; tls?: ServeTlsOptions } = {}
|
|
1596
1606
|
): Promise<{ stop: () => Promise<void> | void; workers: number }> {
|
|
1597
1607
|
const os = await import('node:os');
|
|
1598
1608
|
const count = Math.max(1, workers ?? (typeof os.availableParallelism === 'function' ? os.availableParallelism() : os.cpus().length));
|
package/src/core/context.ts
CHANGED
|
@@ -484,14 +484,16 @@ export class Context {
|
|
|
484
484
|
public setHeader(name: string, value: string): this {
|
|
485
485
|
if (!this._headers) this._headers = {};
|
|
486
486
|
else if (Object.isFrozen(this._headers)) this._headers = { ...this._headers };
|
|
487
|
-
const
|
|
487
|
+
const safeName = (name.indexOf('\r') !== -1 || name.indexOf('\n') !== -1) ? name.replace(/[\r\n]+/g, '') : name;
|
|
488
|
+
const safeVal = (value.indexOf('\r') !== -1 || value.indexOf('\n') !== -1) ? value.replace(/[\r\n]+/g, '') : value;
|
|
489
|
+
const lower = safeName.toLowerCase();
|
|
488
490
|
if (lower === 'vary' && this._headers['vary']) {
|
|
489
491
|
const existing = this._headers['vary'];
|
|
490
492
|
const parts = existing.toLowerCase().split(',').map((s) => s.trim());
|
|
491
|
-
const toAdd =
|
|
493
|
+
const toAdd = safeVal.split(',').map((s) => s.trim()).filter((s) => s && !parts.includes(s.toLowerCase()));
|
|
492
494
|
this._headers['vary'] = toAdd.length > 0 ? `${existing}, ${toAdd.join(', ')}` : existing;
|
|
493
495
|
} else {
|
|
494
|
-
this._headers[lower] =
|
|
496
|
+
this._headers[lower] = safeVal;
|
|
495
497
|
}
|
|
496
498
|
return this;
|
|
497
499
|
}
|
|
@@ -499,6 +501,11 @@ export class Context {
|
|
|
499
501
|
public get user(): AuthUser | undefined {
|
|
500
502
|
return this.store.get('user');
|
|
501
503
|
}
|
|
504
|
+
|
|
505
|
+
public set user(value: AuthUser | undefined) {
|
|
506
|
+
if (value === undefined) this.store.delete('user');
|
|
507
|
+
else this.store.set('user', value);
|
|
508
|
+
}
|
|
502
509
|
|
|
503
510
|
|
|
504
511
|
public send(message: string, extra: Record<string, any> = {}): Response {
|
package/src/core/router.ts
CHANGED
|
@@ -10,7 +10,8 @@ import type { RouteEndpoint, RouteSchema } from '../client/index';
|
|
|
10
10
|
type HandlersChain = (Middleware | Handler | RouteSchemas)[];
|
|
11
11
|
|
|
12
12
|
export type InferSchema<S> =
|
|
13
|
-
S extends {
|
|
13
|
+
S extends { '~standard': { types?: { output: infer T } } } ? T
|
|
14
|
+
: S extends { static: infer T } ? T
|
|
14
15
|
: S extends { _output: infer T } ? T
|
|
15
16
|
: any;
|
|
16
17
|
|