barejs 0.2.4 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,12 +7,13 @@ 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
+ 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,
@@ -85,19 +86,58 @@ export interface UseLogOptions {
85
86
  onLog?: (entry: UseLogEntry) => void;
86
87
  }
87
88
 
88
- type TypedRouteHandler<Derived, S extends RouteSchemas, Res> = (
89
- 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> & {
90
121
  body: S extends { body: infer B } ? InferSchema<B> : any;
91
122
  query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, string>;
92
123
  params: S extends { params: infer Pa } ? InferSchema<Pa> : Record<string, any>;
93
124
  }
94
125
  ) => Res | Promise<Res>;
95
126
 
96
- type AddRoute<Derived extends Record<string, any>, Routes extends RouteSchema, M extends string> = {
97
- <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
+ >(
98
138
  path: P,
99
139
  schemas: S,
100
- handler: TypedRouteHandler<Derived, S, Res>
140
+ handler: TypedRouteHandler<Derived, Macros, S, Res>
101
141
  ): BareJS<Derived, Routes & Record<`${M} ${P}`, {
102
142
  method: M;
103
143
  path: P;
@@ -105,17 +145,19 @@ type AddRoute<Derived extends Record<string, any>, Routes extends RouteSchema, M
105
145
  query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, any>;
106
146
  headers: S extends { headers: infer H } ? InferSchema<H> : Record<string, string>;
107
147
  body: S extends { body: infer B } ? InferSchema<B> : any;
108
- response: S extends { response: infer R } ? InferSchema<R> : Awaited<Res>;
109
- }>>;
148
+ response: S extends { response: infer R } ? InferResponseSuccess<R> : Awaited<Res>;
149
+ error: S extends { response: infer R } ? InferResponseError<R> : any;
150
+ }>, Macros>;
110
151
  <P extends string, Res = any>(
111
152
  path: P,
112
153
  ...handlers: any[]
113
- ): 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>;
114
155
  };
115
156
 
116
157
  export class BareJS<
117
158
  Derived extends Record<string, any> = {},
118
- Routes extends RouteSchema = {}
159
+ Routes extends RouteSchema = {},
160
+ Macros extends Record<string, MacroDefinition<any, any, any>> = {}
119
161
  > extends BareRouter<Routes> {
120
162
  declare readonly __routes: Routes;
121
163
  private tree = new RadixNode();
@@ -129,6 +171,7 @@ export class BareJS<
129
171
  private _logFormat: 'pretty' | 'json' = 'pretty';
130
172
  private _logSink?: (entry: UseLogEntry) => void;
131
173
  private _trustProxyBox: { val: boolean | string[] } = { val: false };
174
+ private macros: Record<string, MacroDefinition<any, any, any>> = Object.create(null);
132
175
 
133
176
  protected override _onRouteMutate(): void {
134
177
  if (this.compiled) {
@@ -313,10 +356,178 @@ export class BareJS<
313
356
  return this;
314
357
  }
315
358
 
316
- 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
+ > {
317
390
  const normalized = ('/' + path).replace(/\/+/g, '/').replace(/\/$/, '') || '/';
318
- this.wsRoutes.set(normalized, handler);
319
- 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;
320
531
  }
321
532
 
322
533
  public docs(pathOrOptions: string | OpenAPIOptions = '/docs', options: OpenAPIOptions = {}): this {
@@ -399,26 +610,104 @@ export class BareJS<
399
610
  }
400
611
 
401
612
 
402
- declare public get: AddRoute<Derived, Routes, 'GET'>;
403
- declare public post: AddRoute<Derived, Routes, 'POST'>;
404
- declare public put: AddRoute<Derived, Routes, 'PUT'>;
405
- declare public patch: AddRoute<Derived, Routes, 'PATCH'>;
406
- declare public delete: AddRoute<Derived, Routes, 'DELETE'>;
407
- declare public options: AddRoute<Derived, Routes, 'OPTIONS'>;
408
- declare public head: AddRoute<Derived, Routes, 'HEAD'>;
409
- 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>;
410
621
 
411
622
  declare public route: <P extends string, R2 extends RouteSchema = {}>(
412
623
  prefix: P,
413
624
  router: BareRouter<R2>
414
- ) => BareJS<Derived, Routes & PrefixRoutes<P, R2>>;
625
+ ) => BareJS<Derived, Routes & PrefixRoutes<P, R2>, Macros>;
415
626
 
416
627
  declare public use: {
417
- <R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareJS<Derived, Routes & R2>;
418
- <P extends string, R2 extends RouteSchema = {}>(prefix: P, mw: BareRouter<R2>): BareJS<Derived, Routes & PrefixRoutes<P, R2>>;
419
- (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>;
420
631
  };
421
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
+
422
711
  private _hasDerive = false;
423
712
  private static readonly DERIVE_RESERVED = new Set([
424
713
  '__proto__', 'constructor', 'prototype',
@@ -431,7 +720,7 @@ export class BareJS<
431
720
  '_requestId', '_peerIp', '_trustProxy', '_detached',
432
721
  '_derivedKeys', '_idempotencyKey', '_idemInFlight'
433
722
  ]);
434
- 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> {
435
724
  this._hasDerive = true;
436
725
  const deriveMw = async (ctx: any, next: any) => {
437
726
  const derived = await fn(ctx);
@@ -651,8 +940,7 @@ export class BareJS<
651
940
  `;
652
941
 
653
942
  // Inline Finalizer
654
- const finalizeCode = `
655
- ${rFilter ? 'res = rFilter(res);' : ''}
943
+ const finalizeBody = `
656
944
  if (res instanceof Response) {
657
945
  ${idemCommit ? 'const ic = idemCommit(ctx, res, res.status); if (ic && ic.then) return ic.then(() => { ' + buildResFinalize + ' });' : ''}
658
946
  ${buildResFinalize}
@@ -662,6 +950,15 @@ export class BareJS<
662
950
  ${idemCommit ? 'const ic = idemCommit(ctx, res, finalStatus); if (ic && ic.then) return ic.then(() => { ' + buildNonResFinalize + ' });' : ''}
663
951
  ${buildNonResFinalize}
664
952
  `;
953
+ const finalizeCode = rFilter
954
+ ? `
955
+ res = rFilter(res, ctx._status || 200);
956
+ if (res && typeof res.then === 'function') {
957
+ return res.then((v) => { res = v; ${finalizeBody} });
958
+ }
959
+ ${finalizeBody}
960
+ `
961
+ : finalizeBody;
665
962
 
666
963
  const argSig = isLog ? 'ctx, doLog' : 'ctx';
667
964
  const noop = () => { };
@@ -1231,21 +1528,43 @@ export class BareJS<
1231
1528
  if (req.headers.get('upgrade')?.toLowerCase() === 'websocket') {
1232
1529
  const matched = matchWsRoute(wsRoutes, req.url);
1233
1530
  if (matched) {
1234
- const { socket, response } = denoUpgrade(req);
1235
- (socket as any).data = matched.params
1236
- ? { ...matched.handler, params: matched.params }
1237
- : matched.handler;
1238
- if (matched.handler.open) socket.onopen = () => matched.handler.open!(socket);
1239
- if (matched.handler.message) {
1240
- socket.onmessage = (ev: MessageEvent) => {
1241
- const payload = ev.data instanceof ArrayBuffer ? new Uint8Array(ev.data) : ev.data;
1242
- matched.handler.message!(socket, payload as any);
1243
- };
1244
- }
1245
- if (matched.handler.close) {
1246
- 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 });
1247
1566
  }
1248
- return response;
1567
+ return completeDenoUpgrade();
1249
1568
  }
1250
1569
  }
1251
1570
  return compiledFetch(req, peerIp);
@@ -1504,7 +1823,7 @@ export class BareJS<
1504
1823
  port?: number,
1505
1824
  hostname: string = '0.0.0.0',
1506
1825
  reusePort: boolean = true,
1507
- options: { maxRequestBodySize?: number; trustProxy?: boolean | string[]; engine?: 'auto' | 'http' | 'uws' } = {}
1826
+ options: { maxRequestBodySize?: number; trustProxy?: boolean | string[]; engine?: 'auto' | 'http' | 'uws'; tls?: ServeTlsOptions } = {}
1508
1827
  ) {
1509
1828
  if (options.trustProxy !== undefined) {
1510
1829
  this.trustProxy(options.trustProxy);
@@ -1542,6 +1861,7 @@ export class BareJS<
1542
1861
  maxRequestBodySize,
1543
1862
  routes: bunRoutes,
1544
1863
  engine: options.engine,
1864
+ tls: options.tls,
1545
1865
  uwsRoutes,
1546
1866
  fetch(req: Request, peerIp?: string) {
1547
1867
  return self.fetch(req, peerIp);
@@ -1592,7 +1912,7 @@ export class BareJS<
1592
1912
  port?: number,
1593
1913
  workers?: number,
1594
1914
  hostname: string = '0.0.0.0',
1595
- options: { maxRequestBodySize?: number; trustProxy?: boolean | string[]; engine?: 'auto' | 'http' | 'uws' } = {}
1915
+ options: { maxRequestBodySize?: number; trustProxy?: boolean | string[]; engine?: 'auto' | 'http' | 'uws'; tls?: ServeTlsOptions } = {}
1596
1916
  ): Promise<{ stop: () => Promise<void> | void; workers: number }> {
1597
1917
  const os = await import('node:os');
1598
1918
  const count = Math.max(1, workers ?? (typeof os.availableParallelism === 'function' ? os.availableParallelism() : os.cpus().length));
@@ -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 lower = name.toLowerCase();
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 = value.split(',').map((s) => s.trim()).filter((s) => s && !parts.includes(s.toLowerCase()));
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] = value;
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/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) {