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.
package/src/core/bare.ts CHANGED
@@ -1,4 +1,4 @@
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 { RadixNode } from './radix';
3
3
  import { Context } from './context';
4
4
  import { Type as typebox, Type as t } from '@sinclair/typebox';
@@ -7,7 +7,7 @@ import { readFileSync } from "node:fs";
7
7
  import { bootstrapConfig } from "./loader";
8
8
  import { BARE_CONFIG } from "./config";
9
9
  import { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from "../utils/openapi";
10
- import type { RouteSchemas } from "../security/validators";
10
+ import { compileSingleSchema, type RouteSchemas } from "../security/validators";
11
11
  import type { RouteSchema } from "../client/index";
12
12
  import { runtime, type ServerHandle } from "../runtime";
13
13
  import type { ServeTlsOptions } from "../runtime/types";
@@ -86,19 +86,58 @@ export interface UseLogOptions {
86
86
  onLog?: (entry: UseLogEntry) => void;
87
87
  }
88
88
 
89
- type TypedRouteHandler<Derived, S extends RouteSchemas, Res> = (
90
- ctx: Context & Derived & {
89
+ export interface MacroDefinition<
90
+ OptVal = any,
91
+ Derived extends Record<string, any> = {},
92
+ Out extends Record<string, any> = {}
93
+ > {
94
+ /** Runs before the route handler when enabled on a route; return a Response to short-circuit */
95
+ beforeHandle?: (ctx: Context & Derived, value: OptVal) => Response | void | Promise<Response | void>;
96
+ /** Resolves per-route derived properties attached to ctx (auto-cleaned on pool release) */
97
+ resolve?: (ctx: Context & Derived, value: OptVal) => Out | Promise<Out>;
98
+ }
99
+
100
+ type UnionToIntersection<U> = (U extends any ? (x: U) => void : never) extends (x: infer I) => void ? I : never;
101
+
102
+ type MacroOptions<Macros extends Record<string, MacroDefinition<any, any, any>>> = {
103
+ [K in keyof Macros]?: Macros[K] extends MacroDefinition<infer V, any, any> ? V | false : any;
104
+ };
105
+
106
+ type MacroResolved<
107
+ Macros extends Record<string, MacroDefinition<any, any, any>>,
108
+ S
109
+ > = [keyof Macros & keyof S] extends [never]
110
+ ? {}
111
+ : UnionToIntersection<{
112
+ [K in keyof Macros & keyof S]: S[K] extends false | undefined
113
+ ? {}
114
+ : Macros[K] extends { resolve: (...args: any[]) => infer R }
115
+ ? Awaited<R>
116
+ : {};
117
+ }[keyof Macros & keyof S]>;
118
+
119
+ type TypedRouteHandler<Derived, Macros extends Record<string, MacroDefinition<any, any, any>>, S, Res> = (
120
+ ctx: Context & Derived & MacroResolved<Macros, S> & {
91
121
  body: S extends { body: infer B } ? InferSchema<B> : any;
92
122
  query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, string>;
93
123
  params: S extends { params: infer Pa } ? InferSchema<Pa> : Record<string, any>;
94
124
  }
95
125
  ) => Res | Promise<Res>;
96
126
 
97
- type AddRoute<Derived extends Record<string, any>, Routes extends RouteSchema, M extends string> = {
98
- <P extends string, S extends RouteSchemas, Res = S extends { response: infer R } ? InferSchema<R> : any>(
127
+ type AddRoute<
128
+ Derived extends Record<string, any>,
129
+ Routes extends RouteSchema,
130
+ M extends string,
131
+ Macros extends Record<string, MacroDefinition<any, any, any>> = {}
132
+ > = {
133
+ <
134
+ P extends string,
135
+ S extends RouteSchemas & MacroOptions<Macros>,
136
+ Res = S extends { response: infer R } ? (InferResponseSuccess<R> | InferResponseError<R>) : any
137
+ >(
99
138
  path: P,
100
139
  schemas: S,
101
- handler: TypedRouteHandler<Derived, S, Res>
140
+ handler: TypedRouteHandler<Derived, Macros, S, Res>
102
141
  ): BareJS<Derived, Routes & Record<`${M} ${P}`, {
103
142
  method: M;
104
143
  path: P;
@@ -106,17 +145,19 @@ type AddRoute<Derived extends Record<string, any>, Routes extends RouteSchema, M
106
145
  query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, any>;
107
146
  headers: S extends { headers: infer H } ? InferSchema<H> : Record<string, string>;
108
147
  body: S extends { body: infer B } ? InferSchema<B> : any;
109
- response: S extends { response: infer R } ? InferSchema<R> : Awaited<Res>;
110
- }>>;
148
+ response: S extends { response: infer R } ? InferResponseSuccess<R> : Awaited<Res>;
149
+ error: S extends { response: infer R } ? InferResponseError<R> : any;
150
+ }>, Macros>;
111
151
  <P extends string, Res = any>(
112
152
  path: P,
113
153
  ...handlers: any[]
114
- ): BareJS<Derived, Routes & Record<`${M} ${P}`, { method: M; path: P; response: Awaited<Res> }>>;
154
+ ): BareJS<Derived, Routes & Record<`${M} ${P}`, { method: M; path: P; response: Awaited<Res>; error: any }>, Macros>;
115
155
  };
116
156
 
117
157
  export class BareJS<
118
158
  Derived extends Record<string, any> = {},
119
- Routes extends RouteSchema = {}
159
+ Routes extends RouteSchema = {},
160
+ Macros extends Record<string, MacroDefinition<any, any, any>> = {}
120
161
  > extends BareRouter<Routes> {
121
162
  declare readonly __routes: Routes;
122
163
  private tree = new RadixNode();
@@ -130,6 +171,7 @@ export class BareJS<
130
171
  private _logFormat: 'pretty' | 'json' = 'pretty';
131
172
  private _logSink?: (entry: UseLogEntry) => void;
132
173
  private _trustProxyBox: { val: boolean | string[] } = { val: false };
174
+ private macros: Record<string, MacroDefinition<any, any, any>> = Object.create(null);
133
175
 
134
176
  protected override _onRouteMutate(): void {
135
177
  if (this.compiled) {
@@ -314,10 +356,178 @@ export class BareJS<
314
356
  return this;
315
357
  }
316
358
 
317
- public ws(path: string, handler: WebSocketRouteHandler): this {
359
+ public ws<
360
+ P extends string,
361
+ BodySchema = undefined,
362
+ QuerySchema = undefined,
363
+ HeadersSchema = undefined,
364
+ ResponseSchema = undefined
365
+ >(
366
+ path: P,
367
+ handler: Omit<WebSocketRouteHandler<any, any, any, any>, 'body' | 'query' | 'headers' | 'response' | 'message'> & {
368
+ body?: BodySchema;
369
+ query?: QuerySchema;
370
+ headers?: HeadersSchema;
371
+ response?: ResponseSchema;
372
+ message?: (
373
+ ws: any,
374
+ message: BodySchema extends undefined ? (string | Buffer) : InferSchema<BodySchema>
375
+ ) => void | Promise<void>;
376
+ }
377
+ ): BareJS<
378
+ Derived,
379
+ Routes & Record<`WS ${P}`, {
380
+ method: 'WS';
381
+ path: P;
382
+ query: QuerySchema extends undefined ? Record<string, string> : InferSchema<QuerySchema>;
383
+ headers: HeadersSchema extends undefined ? Record<string, string> : InferSchema<HeadersSchema>;
384
+ body: BodySchema extends undefined ? any : InferSchema<BodySchema>;
385
+ response: ResponseSchema extends undefined ? any : InferSchema<ResponseSchema>;
386
+ error: any;
387
+ }>,
388
+ Macros
389
+ > {
318
390
  const normalized = ('/' + path).replace(/\/+/g, '/').replace(/\/$/, '') || '/';
319
- this.wsRoutes.set(normalized, handler);
320
- return this;
391
+ const hasBody = Boolean(handler.body);
392
+ const hasQuery = Boolean(handler.query);
393
+ const hasHeaders = Boolean(handler.headers);
394
+
395
+ // Zero-overhead fast-path when no WS schemas are declared (preserves raw native speed)
396
+ if (!hasBody && !hasQuery && !hasHeaders) {
397
+ this.wsRoutes.set(normalized, handler as WebSocketRouteHandler);
398
+ return this as any;
399
+ }
400
+
401
+ const bodyCheck = hasBody ? compileSingleSchema(handler.body) : null;
402
+ const queryCheck = hasQuery ? compileSingleSchema(handler.query) : null;
403
+ const headersCheck = hasHeaders ? compileSingleSchema(handler.headers) : null;
404
+
405
+ const wrapped: WebSocketRouteHandler = {
406
+ ...(handler as any),
407
+ message: bodyCheck && handler.message
408
+ ? (ws: any, raw: any) => {
409
+ const reportErr = (code: string, error: any) => {
410
+ if (handler.onValidationError) {
411
+ handler.onValidationError(ws, { code, error, raw });
412
+ } else {
413
+ try {
414
+ ws.send?.(JSON.stringify({ status: 'error', code, error }));
415
+ } catch {}
416
+ }
417
+ };
418
+
419
+ let parsed: any = raw;
420
+ if (typeof raw === 'string') {
421
+ try {
422
+ parsed = JSON.parse(raw);
423
+ } catch {
424
+ reportErr('WS_INVALID_JSON', 'Malformed JSON message');
425
+ return;
426
+ }
427
+ } else if (raw instanceof Uint8Array || Buffer.isBuffer(raw)) {
428
+ try {
429
+ parsed = JSON.parse(new TextDecoder().decode(raw));
430
+ } catch {
431
+ reportErr('WS_INVALID_JSON', 'Malformed JSON message');
432
+ return;
433
+ }
434
+ }
435
+
436
+ let res: any;
437
+ try {
438
+ res = bodyCheck(parsed);
439
+ } catch (e: any) {
440
+ reportErr('WS_VALIDATION_FAILED', e?.message || 'Validation failed');
441
+ return;
442
+ }
443
+
444
+ if (res && typeof res.then === 'function') {
445
+ return (res as Promise<{ ok: boolean; data?: any; error?: any }>).then(
446
+ (resolved) => {
447
+ if (!resolved || !resolved.ok) {
448
+ reportErr('WS_VALIDATION_FAILED', resolved?.error ?? 'Validation failed');
449
+ return;
450
+ }
451
+ return handler.message!(ws, resolved.data);
452
+ },
453
+ (err) => {
454
+ reportErr('WS_VALIDATION_FAILED', err?.message || 'Validation failed');
455
+ }
456
+ );
457
+ }
458
+
459
+ if (!res || !res.ok) {
460
+ reportErr('WS_VALIDATION_FAILED', res?.error ?? 'Validation failed');
461
+ return;
462
+ }
463
+ return handler.message!(ws, res.data);
464
+ }
465
+ : (handler.message as any)
466
+ };
467
+
468
+ if (queryCheck || headersCheck) {
469
+ wrapped.__validateUpgrade = (urlOrReq: string | Request, rawHeaders?: Record<string, string> | Headers) => {
470
+ const urlStr = typeof urlOrReq === 'string' ? urlOrReq : urlOrReq.url;
471
+ const runHeaders = (validQuery?: any): any => {
472
+ if (!headersCheck) return { ok: true, query: validQuery };
473
+ const hdrObj: Record<string, string> = {};
474
+ const src = rawHeaders ?? (typeof urlOrReq !== 'string' ? urlOrReq.headers : undefined);
475
+ if (src) {
476
+ if (typeof (src as Headers).forEach === 'function') {
477
+ (src as Headers).forEach((v, k) => {
478
+ const lower = k.toLowerCase();
479
+ if (lower !== '__proto__' && lower !== 'constructor' && lower !== 'prototype') hdrObj[lower] = v;
480
+ });
481
+ } else {
482
+ for (const [k, v] of Object.entries(src as Record<string, string>)) {
483
+ const lower = k.toLowerCase();
484
+ if (lower !== '__proto__' && lower !== 'constructor' && lower !== 'prototype') hdrObj[lower] = String(v);
485
+ }
486
+ }
487
+ }
488
+ try {
489
+ const hr: any = headersCheck(hdrObj);
490
+ if (hr && typeof hr.then === 'function') {
491
+ return (hr as Promise<any>).then(
492
+ (r) => (r?.ok ? { ok: true, query: validQuery, headers: r.data } : { ok: false, code: 'WS_HEADERS_INVALID', error: r?.error }),
493
+ (e) => ({ ok: false, code: 'WS_HEADERS_INVALID', error: e?.message || 'Validation failed' })
494
+ );
495
+ }
496
+ return hr?.ok ? { ok: true, query: validQuery, headers: hr.data } : { ok: false, code: 'WS_HEADERS_INVALID', error: hr?.error };
497
+ } catch (e: any) {
498
+ return { ok: false, code: 'WS_HEADERS_INVALID', error: e?.message || 'Validation failed' };
499
+ }
500
+ };
501
+
502
+ if (queryCheck) {
503
+ const qIdx = urlStr.indexOf('?');
504
+ const qObj: Record<string, string> = {};
505
+ if (qIdx !== -1) {
506
+ const sp = new URLSearchParams(urlStr.slice(qIdx + 1));
507
+ sp.forEach((v, k) => {
508
+ if (k !== '__proto__' && k !== 'constructor' && k !== 'prototype') qObj[k] = v;
509
+ });
510
+ }
511
+ try {
512
+ const qr: any = queryCheck(qObj);
513
+ if (qr && typeof qr.then === 'function') {
514
+ return (qr as Promise<any>).then(
515
+ (r) => (r?.ok ? runHeaders(r.data) : { ok: false, code: 'WS_QUERY_INVALID', error: r?.error }),
516
+ (e) => ({ ok: false, code: 'WS_QUERY_INVALID', error: e?.message || 'Validation failed' })
517
+ );
518
+ }
519
+ if (!qr?.ok) return { ok: false, code: 'WS_QUERY_INVALID', error: qr?.error };
520
+ return runHeaders(qr.data);
521
+ } catch (e: any) {
522
+ return { ok: false, code: 'WS_QUERY_INVALID', error: e?.message || 'Validation failed' };
523
+ }
524
+ }
525
+ return runHeaders();
526
+ };
527
+ }
528
+
529
+ this.wsRoutes.set(normalized, wrapped);
530
+ return this as any;
321
531
  }
322
532
 
323
533
  public docs(pathOrOptions: string | OpenAPIOptions = '/docs', options: OpenAPIOptions = {}): this {
@@ -400,26 +610,104 @@ export class BareJS<
400
610
  }
401
611
 
402
612
 
403
- declare public get: AddRoute<Derived, Routes, 'GET'>;
404
- declare public post: AddRoute<Derived, Routes, 'POST'>;
405
- declare public put: AddRoute<Derived, Routes, 'PUT'>;
406
- declare public patch: AddRoute<Derived, Routes, 'PATCH'>;
407
- declare public delete: AddRoute<Derived, Routes, 'DELETE'>;
408
- declare public options: AddRoute<Derived, Routes, 'OPTIONS'>;
409
- declare public head: AddRoute<Derived, Routes, 'HEAD'>;
410
- declare public all: AddRoute<Derived, Routes, 'ALL'>;
613
+ declare public get: AddRoute<Derived, Routes, 'GET', Macros>;
614
+ declare public post: AddRoute<Derived, Routes, 'POST', Macros>;
615
+ declare public put: AddRoute<Derived, Routes, 'PUT', Macros>;
616
+ declare public patch: AddRoute<Derived, Routes, 'PATCH', Macros>;
617
+ declare public delete: AddRoute<Derived, Routes, 'DELETE', Macros>;
618
+ declare public options: AddRoute<Derived, Routes, 'OPTIONS', Macros>;
619
+ declare public head: AddRoute<Derived, Routes, 'HEAD', Macros>;
620
+ declare public all: AddRoute<Derived, Routes, 'ALL', Macros>;
411
621
 
412
622
  declare public route: <P extends string, R2 extends RouteSchema = {}>(
413
623
  prefix: P,
414
624
  router: BareRouter<R2>
415
- ) => BareJS<Derived, Routes & PrefixRoutes<P, R2>>;
625
+ ) => BareJS<Derived, Routes & PrefixRoutes<P, R2>, Macros>;
416
626
 
417
627
  declare public use: {
418
- <R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareJS<Derived, Routes & R2>;
419
- <P extends string, R2 extends RouteSchema = {}>(prefix: P, mw: BareRouter<R2>): BareJS<Derived, Routes & PrefixRoutes<P, R2>>;
420
- (mw: any): BareJS<Derived, Routes>;
628
+ <R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareJS<Derived, Routes & R2, Macros>;
629
+ <P extends string, R2 extends RouteSchema = {}>(prefix: P, mw: BareRouter<R2>): BareJS<Derived, Routes & PrefixRoutes<P, R2>, Macros>;
630
+ (mw: any): BareJS<Derived, Routes, Macros>;
421
631
  };
422
632
 
633
+ /**
634
+ * Registers declarative per-route macros (`beforeHandle` and/or `resolve`).
635
+ * Zero overhead on routes that do not opt into a macro.
636
+ */
637
+ public macro<M extends Record<string, MacroDefinition<any, Derived, any>>>(
638
+ defs: M
639
+ ): BareJS<Derived, Routes, Macros & M> {
640
+ for (const [name, def] of Object.entries(defs)) {
641
+ if (name === '__proto__' || name === 'constructor' || name === 'prototype') continue;
642
+ if (def && typeof def === 'object') {
643
+ this.macros[name] = def;
644
+ }
645
+ }
646
+ return this as any;
647
+ }
648
+
649
+ protected override _add(method: string, path: string, handlers: any[]) {
650
+ const macroKeys = Object.keys(this.macros);
651
+ if (macroKeys.length === 0) {
652
+ return super._add(method, path, handlers);
653
+ }
654
+
655
+ const expanded: any[] = [];
656
+ for (let i = 0; i < handlers.length; i++) {
657
+ const h = handlers[i];
658
+ if (h && typeof h === 'object' && typeof h !== 'function') {
659
+ const macroMws: any[] = [];
660
+ for (let m = 0; m < macroKeys.length; m++) {
661
+ const mk = macroKeys[m]!;
662
+ if (!Object.hasOwn(h, mk)) continue;
663
+ const optVal = (h as any)[mk];
664
+ if (optVal === undefined || optVal === false) continue;
665
+ const def = this.macros[mk]!;
666
+ if (def.beforeHandle) {
667
+ const bh = def.beforeHandle;
668
+ macroMws.push((ctx: any, next: any) => {
669
+ const r = bh(ctx, optVal);
670
+ if (r && typeof (r as any).then === 'function') {
671
+ return (r as Promise<any>).then((res) => (res !== undefined ? res : next()));
672
+ }
673
+ return r !== undefined ? r : next();
674
+ });
675
+ }
676
+ if (def.resolve) {
677
+ const resFn = def.resolve;
678
+ const resolveMw: any = async (ctx: any, next: any) => {
679
+ const resolved = await resFn(ctx, optVal);
680
+ if (resolved && typeof resolved === 'object') {
681
+ const keys = Object.keys(resolved);
682
+ if (!ctx._derivedKeys) ctx._derivedKeys = [];
683
+ for (let kIdx = 0; kIdx < keys.length; kIdx++) {
684
+ const k = keys[kIdx]!;
685
+ if (k === 'user') {
686
+ ctx.set('user', (resolved as any)[k]);
687
+ } else if (!BareJS.DERIVE_RESERVED.has(k)) {
688
+ ctx[k] = (resolved as any)[k];
689
+ ctx._derivedKeys.push(k);
690
+ }
691
+ }
692
+ }
693
+ return next();
694
+ };
695
+ resolveMw.__isDerive = true;
696
+ macroMws.push(resolveMw);
697
+ }
698
+ }
699
+ // Only pass schemaValidator if any RouteSchemas key is present
700
+ const hasSchemaKey =
701
+ 'body' in h || 'query' in h || 'params' in h || 'headers' in h || 'response' in h || 'detail' in h || 'maxBodySize' in h;
702
+ if (hasSchemaKey) expanded.push(h);
703
+ for (let j = 0; j < macroMws.length; j++) expanded.push(macroMws[j]);
704
+ } else {
705
+ expanded.push(h);
706
+ }
707
+ }
708
+ return super._add(method, path, expanded);
709
+ }
710
+
423
711
  private _hasDerive = false;
424
712
  private static readonly DERIVE_RESERVED = new Set([
425
713
  '__proto__', 'constructor', 'prototype',
@@ -432,7 +720,7 @@ export class BareJS<
432
720
  '_requestId', '_peerIp', '_trustProxy', '_detached',
433
721
  '_derivedKeys', '_idempotencyKey', '_idemInFlight'
434
722
  ]);
435
- public derive<T extends Record<string, any>>(fn: (ctx: Context & Derived) => Promise<T> | T): BareJS<Derived & T, Routes> {
723
+ public derive<T extends Record<string, any>>(fn: (ctx: Context & Derived) => Promise<T> | T): BareJS<Derived & T, Routes, Macros> {
436
724
  this._hasDerive = true;
437
725
  const deriveMw = async (ctx: any, next: any) => {
438
726
  const derived = await fn(ctx);
@@ -664,7 +952,7 @@ export class BareJS<
664
952
  `;
665
953
  const finalizeCode = rFilter
666
954
  ? `
667
- res = rFilter(res);
955
+ res = rFilter(res, ctx._status || 200);
668
956
  if (res && typeof res.then === 'function') {
669
957
  return res.then((v) => { res = v; ${finalizeBody} });
670
958
  }
@@ -1240,21 +1528,43 @@ export class BareJS<
1240
1528
  if (req.headers.get('upgrade')?.toLowerCase() === 'websocket') {
1241
1529
  const matched = matchWsRoute(wsRoutes, req.url);
1242
1530
  if (matched) {
1243
- const { socket, response } = denoUpgrade(req);
1244
- (socket as any).data = matched.params
1245
- ? { ...matched.handler, params: matched.params }
1246
- : matched.handler;
1247
- if (matched.handler.open) socket.onopen = () => matched.handler.open!(socket);
1248
- if (matched.handler.message) {
1249
- socket.onmessage = (ev: MessageEvent) => {
1250
- const payload = ev.data instanceof ArrayBuffer ? new Uint8Array(ev.data) : ev.data;
1251
- matched.handler.message!(socket, payload as any);
1252
- };
1253
- }
1254
- if (matched.handler.close) {
1255
- socket.onclose = (ev: CloseEvent) => matched.handler.close!(socket, ev.code, ev.reason);
1531
+ const completeDenoUpgrade = (extra?: { query?: any; headers?: any }) => {
1532
+ const { socket, response } = denoUpgrade(req);
1533
+ (socket as any).data =
1534
+ matched.params || extra
1535
+ ? { ...matched.handler, ...(matched.params ? { params: matched.params } : {}), ...(extra || {}) }
1536
+ : matched.handler;
1537
+ if (matched.handler.open) socket.onopen = () => matched.handler.open!(socket);
1538
+ if (matched.handler.message) {
1539
+ socket.onmessage = (ev: MessageEvent) => {
1540
+ const payload = ev.data instanceof ArrayBuffer ? new Uint8Array(ev.data) : ev.data;
1541
+ matched.handler.message!(socket, payload as any);
1542
+ };
1543
+ }
1544
+ if (matched.handler.close) {
1545
+ socket.onclose = (ev: CloseEvent) => matched.handler.close!(socket, ev.code, ev.reason);
1546
+ }
1547
+ return response;
1548
+ };
1549
+ const validate = matched.handler.__validateUpgrade;
1550
+ if (validate) {
1551
+ const vr = validate(req);
1552
+ if (vr && typeof (vr as any).then === 'function') {
1553
+ return (vr as Promise<any>).then((r) =>
1554
+ r?.ok
1555
+ ? completeDenoUpgrade({ query: r.query, headers: r.headers })
1556
+ : Response.json({ status: 'error', code: r?.code || 'WS_UPGRADE_INVALID', error: r?.error }, { status: 400 })
1557
+ );
1558
+ }
1559
+ if (!(vr as any)?.ok) {
1560
+ return Response.json(
1561
+ { status: 'error', code: (vr as any)?.code || 'WS_UPGRADE_INVALID', error: (vr as any)?.error },
1562
+ { status: 400 }
1563
+ );
1564
+ }
1565
+ return completeDenoUpgrade({ query: (vr as any).query, headers: (vr as any).headers });
1256
1566
  }
1257
- return response;
1567
+ return completeDenoUpgrade();
1258
1568
  }
1259
1569
  }
1260
1570
  return compiledFetch(req, peerIp);
package/src/core/radix.ts CHANGED
@@ -204,47 +204,70 @@ export class RadixNode {
204
204
  list.push(key);
205
205
  }
206
206
  code += `${innerIndent}const seg${level} = ${pathPrefix}.slice(${idxPrefix}, slash${level});\n`;
207
- code += `${innerIndent}switch(seg${level}) {\n`;
207
+
208
+ const singletons: string[] = [];
209
+ let groupIdx = 0;
208
210
  for (const [tmpl, groupKeys] of byBody) {
209
211
  if (groupKeys.length === 1) {
210
- const key = groupKeys[0]!;
212
+ singletons.push(groupKeys[0]!);
213
+ continue;
214
+ }
215
+ const fnLists: Function[][] = [];
216
+ for (const key of groupKeys) {
211
217
  const child = this.children[key]!;
212
- code += `${innerIndent} case ${JSON.stringify(key)}:\n`;
213
- code += child.jitCompile(register, level + 1, pathPrefix, `slash${level} + 1`, paramVars, emitCall);
214
- code += `${innerIndent} break;\n`;
215
- } else {
216
- const fnLists: string[][] = [];
217
- for (const key of groupKeys) {
218
- const child = this.children[key]!;
219
- const fns: string[] = [];
220
- child.jitCompile((h) => { const n = register(h); fns.push(n); return n; }, level + 1, pathPrefix, `slash${level} + 1`, paramVars, emitCall);
221
- fnLists.push(fns);
222
- }
223
- const slotCount = fnLists[0]!.length;
224
- const slotVars = Array.from({ length: slotCount }, (_, idx) => `_rh${level}_${idx}`);
218
+ const fns: Function[] = [];
219
+ child.jitCompile((h) => { fns.push(h); return ''; }, level + 1, pathPrefix, `slash${level} + 1`, paramVars, emitCall);
220
+ fnLists.push(fns);
221
+ }
222
+ const slotCount = fnLists[0]!.length;
223
+ const gid = `${level}_${groupIdx++}`;
224
+ const slotVars = Array.from({ length: slotCount }, (_, idx) => `_rh${gid}_${idx}`);
225
+ let bodyCode = tmpl;
226
+ for (let si = 0; si < slotCount; si++) {
227
+ bodyCode = bodyCode.replaceAll(`__H${si}__`, slotVars[si]!);
228
+ }
229
+
230
+ if (slotCount === 0) {
231
+ const keySet: Record<string, 1> = Object.create(null);
232
+ for (let gi = 0; gi < groupKeys.length; gi++) keySet[groupKeys[gi]!] = 1;
233
+ const setVar = register(keySet as any);
234
+ code += `${innerIndent}if (${setVar}[seg${level}] === 1) {\n`;
235
+ code += bodyCode;
236
+ code += `${innerIndent}}\n`;
237
+ } else if (slotCount === 1) {
238
+ const dispatchMap: Record<string, Function> = Object.create(null);
225
239
  for (let gi = 0; gi < groupKeys.length; gi++) {
226
- code += `${innerIndent} case ${JSON.stringify(groupKeys[gi]!)}:\n`;
240
+ dispatchMap[groupKeys[gi]!] = fnLists[gi]![0]!;
227
241
  }
228
- code += `${innerIndent} {\n`;
229
- if (slotCount > 0) {
230
- code += `${innerIndent} let ${slotVars.join(', ')};\n`;
231
- code += `${innerIndent} switch(seg${level}) {\n`;
232
- for (let gi = 0; gi < groupKeys.length; gi++) {
233
- const assigns = slotVars.map((sv, si) => `${sv} = ${fnLists[gi]![si]}`).join('; ');
234
- code += `${innerIndent} case ${JSON.stringify(groupKeys[gi]!)}: ${assigns}; break;\n`;
235
- }
236
- code += `${innerIndent} }\n`;
237
- }
238
- let bodyCode = tmpl;
239
- for (let si = 0; si < slotCount; si++) {
240
- bodyCode = bodyCode.replaceAll(`__H${si}__`, slotVars[si]!);
242
+ const mapVar = register(dispatchMap as any);
243
+ code += `${innerIndent}const ${slotVars[0]} = ${mapVar}[seg${level}];\n`;
244
+ code += `${innerIndent}if (${slotVars[0]} !== undefined) {\n`;
245
+ code += bodyCode;
246
+ code += `${innerIndent}}\n`;
247
+ } else {
248
+ const dispatchMap: Record<string, Function[]> = Object.create(null);
249
+ for (let gi = 0; gi < groupKeys.length; gi++) {
250
+ dispatchMap[groupKeys[gi]!] = fnLists[gi]!;
241
251
  }
252
+ const mapVar = register(dispatchMap as any);
253
+ code += `${innerIndent}const _rm${gid} = ${mapVar}[seg${level}];\n`;
254
+ code += `${innerIndent}if (_rm${gid} !== undefined) {\n`;
255
+ code += `${innerIndent} const ${slotVars.map((sv, si) => `${sv} = _rm${gid}[${si}]`).join(', ')};\n`;
242
256
  code += bodyCode;
257
+ code += `${innerIndent}}\n`;
258
+ }
259
+ }
260
+
261
+ if (singletons.length > 0) {
262
+ code += `${innerIndent}switch(seg${level}) {\n`;
263
+ for (const key of singletons) {
264
+ const child = this.children[key]!;
265
+ code += `${innerIndent} case ${JSON.stringify(key)}:\n`;
266
+ code += child.jitCompile(register, level + 1, pathPrefix, `slash${level} + 1`, paramVars, emitCall);
243
267
  code += `${innerIndent} break;\n`;
244
- code += `${innerIndent} }\n`;
245
268
  }
269
+ code += `${innerIndent}}\n`;
246
270
  }
247
- code += `${innerIndent}}\n`;
248
271
  } else {
249
272
  code += `${innerIndent}switch(len${level}) {\n`;
250
273
  for (const [kLen, keysForLen] of byLen) {
@@ -15,6 +15,37 @@ export type InferSchema<S> =
15
15
  : S extends { _output: infer T } ? T
16
16
  : any;
17
17
 
18
+ type SuccessStatusKey = 200 | 201 | 202 | 203 | 204 | '200' | '201' | '202' | '203' | '204';
19
+ type ErrorStatusKey =
20
+ | 400 | 401 | 403 | 404 | 409 | 413 | 415 | 422 | 429 | 500 | 502 | 503
21
+ | '400' | '401' | '403' | '404' | '409' | '413' | '415' | '422' | '429' | '500' | '502' | '503';
22
+
23
+ type IsSingleSchema<S> =
24
+ S extends { '~standard': any } ? true
25
+ : S extends { static: any } ? true
26
+ : S extends { _output: any } ? true
27
+ : S extends { type: string } ? true
28
+ : S extends { properties: Record<string, any> } ? true
29
+ : false;
30
+
31
+ export type InferResponseSuccess<R> =
32
+ IsSingleSchema<R> extends true
33
+ ? InferSchema<R>
34
+ : R extends Record<string | number, any>
35
+ ? ([Extract<keyof R, SuccessStatusKey>] extends [never]
36
+ ? InferSchema<R[keyof R]>
37
+ : InferSchema<R[Extract<keyof R, SuccessStatusKey>]>)
38
+ : InferSchema<R>;
39
+
40
+ export type InferResponseError<R> =
41
+ IsSingleSchema<R> extends true
42
+ ? any
43
+ : R extends Record<string | number, any>
44
+ ? ([Extract<keyof R, ErrorStatusKey>] extends [never]
45
+ ? any
46
+ : InferSchema<R[Extract<keyof R, ErrorStatusKey>]>)
47
+ : any;
48
+
18
49
  type StripLeadingSlash<S extends string> = S extends `/${infer Rest}` ? StripLeadingSlash<Rest> : S;
19
50
  type StripTrailingSlash<S extends string> = S extends `${infer Rest}/` ? StripTrailingSlash<Rest> : S;
20
51
  type NormalizePrefix<P extends string> = StripTrailingSlash<StripLeadingSlash<P>> extends ''
@@ -49,7 +80,7 @@ type TypedRouterHandler<S extends RouteSchemas, Res> = (
49
80
  ) => Res | Promise<Res>;
50
81
 
51
82
  type AddRouterRoute<Routes extends RouteSchema, M extends string> = {
52
- <P extends string, S extends RouteSchemas, Res = S extends { response: infer R } ? InferSchema<R> : any>(
83
+ <P extends string, S extends RouteSchemas, Res = S extends { response: infer R } ? (InferResponseSuccess<R> | InferResponseError<R>) : any>(
53
84
  path: P,
54
85
  schemas: S,
55
86
  handler: TypedRouterHandler<S, Res>
@@ -60,12 +91,13 @@ type AddRouterRoute<Routes extends RouteSchema, M extends string> = {
60
91
  query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, any>;
61
92
  headers: S extends { headers: infer H } ? InferSchema<H> : Record<string, string>;
62
93
  body: S extends { body: infer B } ? InferSchema<B> : any;
63
- response: S extends { response: infer R } ? InferSchema<R> : Awaited<Res>;
94
+ response: S extends { response: infer R } ? InferResponseSuccess<R> : Awaited<Res>;
95
+ error: S extends { response: infer R } ? InferResponseError<R> : any;
64
96
  }>>;
65
97
  <P extends string, Res = any>(
66
98
  path: P,
67
99
  ...handlers: any[]
68
- ): BareRouter<Routes & Record<`${M} ${P}`, { method: M; path: P; response: Awaited<Res> }>>;
100
+ ): BareRouter<Routes & Record<`${M} ${P}`, { method: M; path: P; response: Awaited<Res>; error: any }>>;
69
101
  };
70
102
 
71
103
  export class BareRouter<Routes extends RouteSchema = {}> {