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.
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,59 @@ 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>;
124
+ cookies: S extends { cookies: infer C } ? InferSchema<C> : Record<string, string>;
94
125
  }
95
126
  ) => Res | Promise<Res>;
96
127
 
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>(
128
+ type AddRoute<
129
+ Derived extends Record<string, any>,
130
+ Routes extends RouteSchema,
131
+ M extends string,
132
+ Macros extends Record<string, MacroDefinition<any, any, any>> = {}
133
+ > = {
134
+ <
135
+ P extends string,
136
+ S extends RouteSchemas & MacroOptions<Macros>,
137
+ Res = S extends { response: infer R } ? (InferResponseSuccess<R> | InferResponseError<R>) : any
138
+ >(
99
139
  path: P,
100
140
  schemas: S,
101
- handler: TypedRouteHandler<Derived, S, Res>
141
+ handler: TypedRouteHandler<Derived, Macros, S, Res>
102
142
  ): BareJS<Derived, Routes & Record<`${M} ${P}`, {
103
143
  method: M;
104
144
  path: P;
@@ -106,17 +146,19 @@ type AddRoute<Derived extends Record<string, any>, Routes extends RouteSchema, M
106
146
  query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, any>;
107
147
  headers: S extends { headers: infer H } ? InferSchema<H> : Record<string, string>;
108
148
  body: S extends { body: infer B } ? InferSchema<B> : any;
109
- response: S extends { response: infer R } ? InferSchema<R> : Awaited<Res>;
110
- }>>;
149
+ response: S extends { response: infer R } ? InferResponseSuccess<R> : Awaited<Res>;
150
+ error: S extends { response: infer R } ? InferResponseError<R> : any;
151
+ }>, Macros>;
111
152
  <P extends string, Res = any>(
112
153
  path: P,
113
154
  ...handlers: any[]
114
- ): BareJS<Derived, Routes & Record<`${M} ${P}`, { method: M; path: P; response: Awaited<Res> }>>;
155
+ ): BareJS<Derived, Routes & Record<`${M} ${P}`, { method: M; path: P; response: Awaited<Res>; error: any }>, Macros>;
115
156
  };
116
157
 
117
158
  export class BareJS<
118
159
  Derived extends Record<string, any> = {},
119
- Routes extends RouteSchema = {}
160
+ Routes extends RouteSchema = {},
161
+ Macros extends Record<string, MacroDefinition<any, any, any>> = {}
120
162
  > extends BareRouter<Routes> {
121
163
  declare readonly __routes: Routes;
122
164
  private tree = new RadixNode();
@@ -130,6 +172,7 @@ export class BareJS<
130
172
  private _logFormat: 'pretty' | 'json' = 'pretty';
131
173
  private _logSink?: (entry: UseLogEntry) => void;
132
174
  private _trustProxyBox: { val: boolean | string[] } = { val: false };
175
+ private macros: Record<string, MacroDefinition<any, any, any>> = Object.create(null);
133
176
 
134
177
  protected override _onRouteMutate(): void {
135
178
  if (this.compiled) {
@@ -314,10 +357,178 @@ export class BareJS<
314
357
  return this;
315
358
  }
316
359
 
317
- public ws(path: string, handler: WebSocketRouteHandler): this {
360
+ public ws<
361
+ P extends string,
362
+ BodySchema = undefined,
363
+ QuerySchema = undefined,
364
+ HeadersSchema = undefined,
365
+ ResponseSchema = undefined
366
+ >(
367
+ path: P,
368
+ handler: Omit<WebSocketRouteHandler<any, any, any, any>, 'body' | 'query' | 'headers' | 'response' | 'message'> & {
369
+ body?: BodySchema;
370
+ query?: QuerySchema;
371
+ headers?: HeadersSchema;
372
+ response?: ResponseSchema;
373
+ message?: (
374
+ ws: any,
375
+ message: BodySchema extends undefined ? (string | Buffer) : InferSchema<BodySchema>
376
+ ) => void | Promise<void>;
377
+ }
378
+ ): BareJS<
379
+ Derived,
380
+ Routes & Record<`WS ${P}`, {
381
+ method: 'WS';
382
+ path: P;
383
+ query: QuerySchema extends undefined ? Record<string, string> : InferSchema<QuerySchema>;
384
+ headers: HeadersSchema extends undefined ? Record<string, string> : InferSchema<HeadersSchema>;
385
+ body: BodySchema extends undefined ? any : InferSchema<BodySchema>;
386
+ response: ResponseSchema extends undefined ? any : InferSchema<ResponseSchema>;
387
+ error: any;
388
+ }>,
389
+ Macros
390
+ > {
318
391
  const normalized = ('/' + path).replace(/\/+/g, '/').replace(/\/$/, '') || '/';
319
- this.wsRoutes.set(normalized, handler);
320
- return this;
392
+ const hasBody = Boolean(handler.body);
393
+ const hasQuery = Boolean(handler.query);
394
+ const hasHeaders = Boolean(handler.headers);
395
+
396
+ // Zero-overhead fast-path when no WS schemas are declared (preserves raw native speed)
397
+ if (!hasBody && !hasQuery && !hasHeaders) {
398
+ this.wsRoutes.set(normalized, handler as WebSocketRouteHandler);
399
+ return this as any;
400
+ }
401
+
402
+ const bodyCheck = hasBody ? compileSingleSchema(handler.body) : null;
403
+ const queryCheck = hasQuery ? compileSingleSchema(handler.query) : null;
404
+ const headersCheck = hasHeaders ? compileSingleSchema(handler.headers) : null;
405
+
406
+ const wrapped: WebSocketRouteHandler = {
407
+ ...(handler as any),
408
+ message: bodyCheck && handler.message
409
+ ? (ws: any, raw: any) => {
410
+ const reportErr = (code: string, error: any) => {
411
+ if (handler.onValidationError) {
412
+ handler.onValidationError(ws, { code, error, raw });
413
+ } else {
414
+ try {
415
+ ws.send?.(JSON.stringify({ status: 'error', code, error }));
416
+ } catch {}
417
+ }
418
+ };
419
+
420
+ let parsed: any = raw;
421
+ if (typeof raw === 'string') {
422
+ try {
423
+ parsed = JSON.parse(raw);
424
+ } catch {
425
+ reportErr('WS_INVALID_JSON', 'Malformed JSON message');
426
+ return;
427
+ }
428
+ } else if (raw instanceof Uint8Array || Buffer.isBuffer(raw)) {
429
+ try {
430
+ parsed = JSON.parse(new TextDecoder().decode(raw));
431
+ } catch {
432
+ reportErr('WS_INVALID_JSON', 'Malformed JSON message');
433
+ return;
434
+ }
435
+ }
436
+
437
+ let res: any;
438
+ try {
439
+ res = bodyCheck(parsed);
440
+ } catch (e: any) {
441
+ reportErr('WS_VALIDATION_FAILED', e?.message || 'Validation failed');
442
+ return;
443
+ }
444
+
445
+ if (res && typeof res.then === 'function') {
446
+ return (res as Promise<{ ok: boolean; data?: any; error?: any }>).then(
447
+ (resolved) => {
448
+ if (!resolved || !resolved.ok) {
449
+ reportErr('WS_VALIDATION_FAILED', resolved?.error ?? 'Validation failed');
450
+ return;
451
+ }
452
+ return handler.message!(ws, resolved.data);
453
+ },
454
+ (err) => {
455
+ reportErr('WS_VALIDATION_FAILED', err?.message || 'Validation failed');
456
+ }
457
+ );
458
+ }
459
+
460
+ if (!res || !res.ok) {
461
+ reportErr('WS_VALIDATION_FAILED', res?.error ?? 'Validation failed');
462
+ return;
463
+ }
464
+ return handler.message!(ws, res.data);
465
+ }
466
+ : (handler.message as any)
467
+ };
468
+
469
+ if (queryCheck || headersCheck) {
470
+ wrapped.__validateUpgrade = (urlOrReq: string | Request, rawHeaders?: Record<string, string> | Headers) => {
471
+ const urlStr = typeof urlOrReq === 'string' ? urlOrReq : urlOrReq.url;
472
+ const runHeaders = (validQuery?: any): any => {
473
+ if (!headersCheck) return { ok: true, query: validQuery };
474
+ const hdrObj: Record<string, string> = {};
475
+ const src = rawHeaders ?? (typeof urlOrReq !== 'string' ? urlOrReq.headers : undefined);
476
+ if (src) {
477
+ if (typeof (src as Headers).forEach === 'function') {
478
+ (src as Headers).forEach((v, k) => {
479
+ const lower = k.toLowerCase();
480
+ if (lower !== '__proto__' && lower !== 'constructor' && lower !== 'prototype') hdrObj[lower] = v;
481
+ });
482
+ } else {
483
+ for (const [k, v] of Object.entries(src as Record<string, string>)) {
484
+ const lower = k.toLowerCase();
485
+ if (lower !== '__proto__' && lower !== 'constructor' && lower !== 'prototype') hdrObj[lower] = String(v);
486
+ }
487
+ }
488
+ }
489
+ try {
490
+ const hr: any = headersCheck(hdrObj);
491
+ if (hr && typeof hr.then === 'function') {
492
+ return (hr as Promise<any>).then(
493
+ (r) => (r?.ok ? { ok: true, query: validQuery, headers: r.data } : { ok: false, code: 'WS_HEADERS_INVALID', error: r?.error }),
494
+ (e) => ({ ok: false, code: 'WS_HEADERS_INVALID', error: e?.message || 'Validation failed' })
495
+ );
496
+ }
497
+ return hr?.ok ? { ok: true, query: validQuery, headers: hr.data } : { ok: false, code: 'WS_HEADERS_INVALID', error: hr?.error };
498
+ } catch (e: any) {
499
+ return { ok: false, code: 'WS_HEADERS_INVALID', error: e?.message || 'Validation failed' };
500
+ }
501
+ };
502
+
503
+ if (queryCheck) {
504
+ const qIdx = urlStr.indexOf('?');
505
+ const qObj: Record<string, string> = {};
506
+ if (qIdx !== -1) {
507
+ const sp = new URLSearchParams(urlStr.slice(qIdx + 1));
508
+ sp.forEach((v, k) => {
509
+ if (k !== '__proto__' && k !== 'constructor' && k !== 'prototype') qObj[k] = v;
510
+ });
511
+ }
512
+ try {
513
+ const qr: any = queryCheck(qObj);
514
+ if (qr && typeof qr.then === 'function') {
515
+ return (qr as Promise<any>).then(
516
+ (r) => (r?.ok ? runHeaders(r.data) : { ok: false, code: 'WS_QUERY_INVALID', error: r?.error }),
517
+ (e) => ({ ok: false, code: 'WS_QUERY_INVALID', error: e?.message || 'Validation failed' })
518
+ );
519
+ }
520
+ if (!qr?.ok) return { ok: false, code: 'WS_QUERY_INVALID', error: qr?.error };
521
+ return runHeaders(qr.data);
522
+ } catch (e: any) {
523
+ return { ok: false, code: 'WS_QUERY_INVALID', error: e?.message || 'Validation failed' };
524
+ }
525
+ }
526
+ return runHeaders();
527
+ };
528
+ }
529
+
530
+ this.wsRoutes.set(normalized, wrapped);
531
+ return this as any;
321
532
  }
322
533
 
323
534
  public docs(pathOrOptions: string | OpenAPIOptions = '/docs', options: OpenAPIOptions = {}): this {
@@ -400,25 +611,121 @@ export class BareJS<
400
611
  }
401
612
 
402
613
 
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'>;
614
+ declare public get: AddRoute<Derived, Routes, 'GET', Macros>;
615
+ declare public post: AddRoute<Derived, Routes, 'POST', Macros>;
616
+ declare public put: AddRoute<Derived, Routes, 'PUT', Macros>;
617
+ declare public patch: AddRoute<Derived, Routes, 'PATCH', Macros>;
618
+ declare public delete: AddRoute<Derived, Routes, 'DELETE', Macros>;
619
+ declare public options: AddRoute<Derived, Routes, 'OPTIONS', Macros>;
620
+ declare public head: AddRoute<Derived, Routes, 'HEAD', Macros>;
621
+ declare public all: AddRoute<Derived, Routes, 'ALL', Macros>;
411
622
 
412
623
  declare public route: <P extends string, R2 extends RouteSchema = {}>(
413
624
  prefix: P,
414
625
  router: BareRouter<R2>
415
- ) => BareJS<Derived, Routes & PrefixRoutes<P, R2>>;
626
+ ) => BareJS<Derived, Routes & PrefixRoutes<P, R2>, Macros>;
416
627
 
417
- 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>;
421
- };
628
+ public override use<D2 extends Record<string, any> = {}, R2 extends RouteSchema = {}, M2 extends Record<string, MacroDefinition<any, any, any>> = {}>(
629
+ mw: BareJS<D2, R2, M2>
630
+ ): BareJS<Derived & D2, Routes & R2, Macros & M2>;
631
+ public override use<P extends string, D2 extends Record<string, any> = {}, R2 extends RouteSchema = {}, M2 extends Record<string, MacroDefinition<any, any, any>> = {}>(
632
+ prefix: P,
633
+ mw: BareJS<D2, R2, M2>
634
+ ): BareJS<Derived & D2, Routes & PrefixRoutes<P, R2>, Macros & M2>;
635
+ public override use<R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareJS<Derived, Routes & R2, Macros>;
636
+ public override use<P extends string, R2 extends RouteSchema = {}>(prefix: P, mw: BareRouter<R2>): BareJS<Derived, Routes & PrefixRoutes<P, R2>, Macros>;
637
+ public override use(...mws: any[]): BareJS<Derived, Routes, Macros>;
638
+ public override use(prefixOrMw: any, ...rest: any[]): any {
639
+ const mergeMacrosFrom = (candidate: any) => {
640
+ if (candidate && typeof candidate === 'object' && candidate.macros && typeof candidate.macros === 'object') {
641
+ for (const [k, def] of Object.entries(candidate.macros)) {
642
+ if (k === '__proto__' || k === 'constructor' || k === 'prototype') continue;
643
+ if (def && typeof def === 'object') this.macros[k] = def as any;
644
+ }
645
+ }
646
+ };
647
+ mergeMacrosFrom(prefixOrMw);
648
+ for (let i = 0; i < rest.length; i++) mergeMacrosFrom(rest[i]);
649
+ return super.use(prefixOrMw, ...rest);
650
+ }
651
+
652
+ /**
653
+ * Registers declarative per-route macros (`beforeHandle` and/or `resolve`).
654
+ * Zero overhead on routes that do not opt into a macro.
655
+ */
656
+ public macro<M extends Record<string, MacroDefinition<any, Derived, any>>>(
657
+ defs: M
658
+ ): BareJS<Derived, Routes, Macros & M> {
659
+ for (const [name, def] of Object.entries(defs)) {
660
+ if (name === '__proto__' || name === 'constructor' || name === 'prototype') continue;
661
+ if (def && typeof def === 'object') {
662
+ this.macros[name] = def;
663
+ }
664
+ }
665
+ return this as any;
666
+ }
667
+
668
+ protected override _add(method: string, path: string, handlers: any[]) {
669
+ const macroKeys = Object.keys(this.macros);
670
+ if (macroKeys.length === 0) {
671
+ return super._add(method, path, handlers);
672
+ }
673
+
674
+ const expanded: any[] = [];
675
+ for (let i = 0; i < handlers.length; i++) {
676
+ const h = handlers[i];
677
+ if (h && typeof h === 'object' && typeof h !== 'function') {
678
+ const macroMws: any[] = [];
679
+ for (let m = 0; m < macroKeys.length; m++) {
680
+ const mk = macroKeys[m]!;
681
+ if (!Object.hasOwn(h, mk)) continue;
682
+ const optVal = (h as any)[mk];
683
+ if (optVal === undefined || optVal === false) continue;
684
+ const def = this.macros[mk]!;
685
+ if (def.beforeHandle) {
686
+ const bh = def.beforeHandle;
687
+ macroMws.push((ctx: any, next: any) => {
688
+ const r = bh(ctx, optVal);
689
+ if (r && typeof (r as any).then === 'function') {
690
+ return (r as Promise<any>).then((res) => (res !== undefined ? res : next()));
691
+ }
692
+ return r !== undefined ? r : next();
693
+ });
694
+ }
695
+ if (def.resolve) {
696
+ const resFn = def.resolve;
697
+ const resolveMw: any = async (ctx: any, next: any) => {
698
+ const resolved = await resFn(ctx, optVal);
699
+ if (resolved && typeof resolved === 'object') {
700
+ const keys = Object.keys(resolved);
701
+ if (!ctx._derivedKeys) ctx._derivedKeys = [];
702
+ for (let kIdx = 0; kIdx < keys.length; kIdx++) {
703
+ const k = keys[kIdx]!;
704
+ if (k === 'user') {
705
+ ctx.set('user', (resolved as any)[k]);
706
+ } else if (!BareJS.DERIVE_RESERVED.has(k)) {
707
+ ctx[k] = (resolved as any)[k];
708
+ ctx._derivedKeys.push(k);
709
+ }
710
+ }
711
+ }
712
+ return next();
713
+ };
714
+ resolveMw.__isDerive = true;
715
+ macroMws.push(resolveMw);
716
+ }
717
+ }
718
+ // Only pass schemaValidator if any RouteSchemas key is present
719
+ const hasSchemaKey =
720
+ 'body' in h || 'query' in h || 'params' in h || 'headers' in h || 'cookies' in h || 'response' in h || 'detail' in h || 'maxBodySize' in h;
721
+ if (hasSchemaKey) expanded.push(h);
722
+ for (let j = 0; j < macroMws.length; j++) expanded.push(macroMws[j]);
723
+ } else {
724
+ expanded.push(h);
725
+ }
726
+ }
727
+ return super._add(method, path, expanded);
728
+ }
422
729
 
423
730
  private _hasDerive = false;
424
731
  private static readonly DERIVE_RESERVED = new Set([
@@ -432,7 +739,7 @@ export class BareJS<
432
739
  '_requestId', '_peerIp', '_trustProxy', '_detached',
433
740
  '_derivedKeys', '_idempotencyKey', '_idemInFlight'
434
741
  ]);
435
- public derive<T extends Record<string, any>>(fn: (ctx: Context & Derived) => Promise<T> | T): BareJS<Derived & T, Routes> {
742
+ public derive<T extends Record<string, any>>(fn: (ctx: Context & Derived) => Promise<T> | T): BareJS<Derived & T, Routes, Macros> {
436
743
  this._hasDerive = true;
437
744
  const deriveMw = async (ctx: any, next: any) => {
438
745
  const derived = await fn(ctx);
@@ -617,6 +924,40 @@ export class BareJS<
617
924
  return res;
618
925
  `;
619
926
 
927
+ const genEncoder = new TextEncoder();
928
+ const generatorToResponse = (gen: any, status: number, hdrs?: Record<string, string>): Response => {
929
+ const stream = new ReadableStream<Uint8Array>({
930
+ async pull(controller) {
931
+ try {
932
+ const step = await gen.next();
933
+ if (step.done) {
934
+ controller.close();
935
+ return;
936
+ }
937
+ const val = step.value;
938
+ if (val === undefined || val === null) return;
939
+ if (val instanceof Uint8Array) {
940
+ controller.enqueue(val);
941
+ } else if (typeof val === 'string') {
942
+ controller.enqueue(genEncoder.encode(val));
943
+ } else {
944
+ controller.enqueue(genEncoder.encode(JSON.stringify(val) + '\n'));
945
+ }
946
+ } catch (err) {
947
+ controller.error(err);
948
+ }
949
+ },
950
+ cancel() {
951
+ try { gen.return?.(); } catch {}
952
+ }
953
+ });
954
+ const outHeaders: Record<string, string> = hdrs ? { ...hdrs } : {};
955
+ if (!outHeaders['content-type'] && !outHeaders['Content-Type']) {
956
+ outHeaders['content-type'] = 'text/plain; charset=utf-8';
957
+ }
958
+ return new Response(stream, { status, headers: outHeaders });
959
+ };
960
+
620
961
  const buildNonResFinalize = `
621
962
  ${logStatusCode}
622
963
  let outRes;
@@ -629,6 +970,8 @@ export class BareJS<
629
970
  headers: ctx._headers || text200.headers
630
971
  });
631
972
  }
973
+ } else if (res !== null && typeof res === 'object' && typeof res.next === 'function') {
974
+ outRes = genToRes(res, finalStatus, ctx._headers);
632
975
  } else if (finalStatus === 200 && !ctx._headers) {
633
976
  outRes = Response.json(res ?? null);
634
977
  } else if (finalStatus === 200 && ctx._headers === lastHdrs) {
@@ -664,7 +1007,7 @@ export class BareJS<
664
1007
  `;
665
1008
  const finalizeCode = rFilter
666
1009
  ? `
667
- res = rFilter(res);
1010
+ res = rFilter(res, ctx._status || 200);
668
1011
  if (res && typeof res.then === 'function') {
669
1012
  return res.then((v) => { res = v; ${finalizeBody} });
670
1013
  }
@@ -678,6 +1021,7 @@ export class BareJS<
678
1021
  const extraNames = [
679
1022
  'applyShortCircuit',
680
1023
  'noop',
1024
+ 'genToRes',
681
1025
  ...(rFilter ? ['rFilter'] : []),
682
1026
  ...(idemCommit ? ['idemCommit'] : []),
683
1027
  ...(idemRelease ? ['idemRelease'] : [])
@@ -685,6 +1029,7 @@ export class BareJS<
685
1029
  const extraVals = [
686
1030
  applyCtxHeadersToRes,
687
1031
  noop,
1032
+ generatorToResponse,
688
1033
  ...(rFilter ? [rFilter] : []),
689
1034
  ...(idemCommit ? [idemCommit] : []),
690
1035
  ...(idemRelease ? [idemRelease] : [])
@@ -1240,21 +1585,43 @@ export class BareJS<
1240
1585
  if (req.headers.get('upgrade')?.toLowerCase() === 'websocket') {
1241
1586
  const matched = matchWsRoute(wsRoutes, req.url);
1242
1587
  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);
1588
+ const completeDenoUpgrade = (extra?: { query?: any; headers?: any }) => {
1589
+ const { socket, response } = denoUpgrade(req);
1590
+ (socket as any).data =
1591
+ matched.params || extra
1592
+ ? { ...matched.handler, ...(matched.params ? { params: matched.params } : {}), ...(extra || {}) }
1593
+ : matched.handler;
1594
+ if (matched.handler.open) socket.onopen = () => matched.handler.open!(socket);
1595
+ if (matched.handler.message) {
1596
+ socket.onmessage = (ev: MessageEvent) => {
1597
+ const payload = ev.data instanceof ArrayBuffer ? new Uint8Array(ev.data) : ev.data;
1598
+ matched.handler.message!(socket, payload as any);
1599
+ };
1600
+ }
1601
+ if (matched.handler.close) {
1602
+ socket.onclose = (ev: CloseEvent) => matched.handler.close!(socket, ev.code, ev.reason);
1603
+ }
1604
+ return response;
1605
+ };
1606
+ const validate = matched.handler.__validateUpgrade;
1607
+ if (validate) {
1608
+ const vr = validate(req);
1609
+ if (vr && typeof (vr as any).then === 'function') {
1610
+ return (vr as Promise<any>).then((r) =>
1611
+ r?.ok
1612
+ ? completeDenoUpgrade({ query: r.query, headers: r.headers })
1613
+ : Response.json({ status: 'error', code: r?.code || 'WS_UPGRADE_INVALID', error: r?.error }, { status: 400 })
1614
+ );
1615
+ }
1616
+ if (!(vr as any)?.ok) {
1617
+ return Response.json(
1618
+ { status: 'error', code: (vr as any)?.code || 'WS_UPGRADE_INVALID', error: (vr as any)?.error },
1619
+ { status: 400 }
1620
+ );
1621
+ }
1622
+ return completeDenoUpgrade({ query: (vr as any).query, headers: (vr as any).headers });
1256
1623
  }
1257
- return response;
1624
+ return completeDenoUpgrade();
1258
1625
  }
1259
1626
  }
1260
1627
  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) {