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.
@@ -1,8 +1,23 @@
1
- export interface WebSocketRouteHandler {
1
+ export interface WebSocketRouteHandler<Body = string | Buffer, Query = any, Headers = any, Res = any> {
2
+ /** Optional schema (Standard Schema v1 / TypeBox / Zod / Native) for incoming JSON messages */
3
+ body?: any;
4
+ /** Optional schema for WebSocket upgrade query parameters */
5
+ query?: any;
6
+ /** Optional schema for WebSocket upgrade request headers */
7
+ headers?: any;
8
+ /** Optional schema describing outgoing server messages (for typed bareTreaty/bareClient) */
9
+ response?: any;
10
+ /** Optional error callback when an incoming WS message fails `body` validation */
11
+ onValidationError?: (ws: any, error: { code: string; error: any; raw: any }) => void;
2
12
  open?: (ws: any) => void;
3
- message?: (ws: any, message: string | Buffer) => void;
13
+ message?: (ws: any, message: Body) => void | Promise<void>;
4
14
  close?: (ws: any, code: number, reason: string) => void;
5
15
  drain?: (ws: any) => void;
16
+ /** @internal Pre-compiled fail-closed upgrade validator (only present when query/headers schema is set) */
17
+ __validateUpgrade?: (urlOrReq: string | Request, headers?: Record<string, string> | Headers) =>
18
+ | { ok: true; query?: Query; headers?: Headers }
19
+ | { ok: false; code: string; error: any }
20
+ | Promise<{ ok: true; query?: Query; headers?: Headers } | { ok: false; code: string; error: any }>;
6
21
  }
7
22
 
8
23
  export interface WsMatchResult {
package/src/edge.ts CHANGED
@@ -468,6 +468,8 @@ export function createSingleflight() {
468
468
  };
469
469
  }
470
470
 
471
+ export { tracing, serverTiming, type TracingOptions, type TracingSpan } from './utils/tracing';
472
+
471
473
  export {
472
474
  BareEdge as BareJS,
473
475
  BareRouter,
package/src/index.ts CHANGED
@@ -6,8 +6,8 @@
6
6
  */
7
7
 
8
8
  // --- 1. Core Engine ---
9
- export { BareJS, normalizePoolSize, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
10
- export { BareRouter, type InferSchema, type PrefixRoutes } from './core/router';
9
+ export { BareJS, normalizePoolSize, type MacroDefinition, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
10
+ export { BareRouter, type InferSchema, type InferResponseSuccess, type InferResponseError, type PrefixRoutes } from './core/router';
11
11
 
12
12
  /**
13
13
  * Plugin Interface for BareJS
@@ -37,7 +37,7 @@ import { Type } from "@sinclair/typebox";
37
37
  export { Type, Type as T, Type as TypeBox };
38
38
 
39
39
  // --- 4. The Validation Suite (Engines - สำหรับเป็น Middleware) ---
40
- import { typebox, zod, native, standard, validate, schemaValidator, createResponseFilter, Z, type RouteSchemas, type RouteDetail, type StandardSchemaV1 } from './security/validators';
40
+ import { typebox, zod, native, standard, validate, schemaValidator, createResponseFilter, isStatusResponseMap, Z, type RouteSchemas, type RouteDetail, type StandardSchemaV1 } from './security/validators';
41
41
  export {
42
42
  // TypeBox Engine
43
43
  typebox,
@@ -58,6 +58,7 @@ export {
58
58
  // Unified Route Schema Engine (body, query, params, headers, response, detail, maxBodySize)
59
59
  schemaValidator,
60
60
  createResponseFilter,
61
+ isStatusResponseMap,
61
62
  type RouteSchemas,
62
63
  type RouteDetail,
63
64
  type StandardSchemaV1
@@ -85,6 +86,7 @@ export { securityHeaders, type SecurityHeadersOptions } from './security/headers
85
86
  export { staticFile, type StaticOptions, type StaticMetadataCacheOptions } from './utils/static';
86
87
  export { compress, type CompressOptions, type CompressionEncoding } from './utils/compress';
87
88
  export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
89
+ export { tracing, serverTiming, type TracingOptions, type TracingSpan } from './utils/tracing';
88
90
 
89
91
  // --- 6. Authentication (Bun Native) ---
90
92
  // Always deploy using process.env [2026-01-06]
@@ -99,6 +101,7 @@ export {
99
101
  type BareClient,
100
102
  type BareSafeClient,
101
103
  type BareTreatyNode,
104
+ type TreatyTree,
102
105
  type BareClientResult,
103
106
  type BareWsClient,
104
107
  type BareClientOptions,
@@ -34,13 +34,33 @@ export const bunDriver: RuntimeDriver = {
34
34
  fetch(req: Request, srv: any) {
35
35
  if (req.headers.get('upgrade')?.toLowerCase() === 'websocket') {
36
36
  const matched = matchWsRoute(wsCfg.routes, req.url);
37
- if (
38
- matched &&
39
- srv.upgrade(req, {
40
- data: matched.params ? { ...matched.handler, params: matched.params } : matched.handler
41
- })
42
- ) {
43
- return undefined as any;
37
+ if (matched) {
38
+ const doUpgrade = (extra?: { query?: any; headers?: any }) => {
39
+ const data =
40
+ matched.params || extra
41
+ ? { ...matched.handler, ...(matched.params ? { params: matched.params } : {}), ...(extra || {}) }
42
+ : matched.handler;
43
+ return srv.upgrade(req, { data }) ? (undefined as any) : new Response('Upgrade failed', { status: 400 });
44
+ };
45
+ const validate = matched.handler.__validateUpgrade;
46
+ if (validate) {
47
+ const vr = validate(req);
48
+ if (vr && typeof (vr as any).then === 'function') {
49
+ return (vr as Promise<any>).then((r) =>
50
+ r?.ok
51
+ ? doUpgrade({ query: r.query, headers: r.headers })
52
+ : Response.json({ status: 'error', code: r?.code || 'WS_UPGRADE_INVALID', error: r?.error }, { status: 400 })
53
+ );
54
+ }
55
+ if (!(vr as any)?.ok) {
56
+ return Response.json(
57
+ { status: 'error', code: (vr as any)?.code || 'WS_UPGRADE_INVALID', error: (vr as any)?.error },
58
+ { status: 400 }
59
+ );
60
+ }
61
+ return doUpgrade({ query: (vr as any).query, headers: (vr as any).headers });
62
+ }
63
+ if (doUpgrade() === undefined) return undefined as any;
44
64
  }
45
65
  }
46
66
  return opts.fetch(req, srv?.requestIP?.(req)?.address);
@@ -446,8 +446,23 @@ export const nodeDriver: RuntimeDriver = {
446
446
  return;
447
447
  }
448
448
  try {
449
+ let extra: { query?: any; headers?: any } | undefined;
450
+ if (matched.handler.__validateUpgrade) {
451
+ const vr = await matched.handler.__validateUpgrade(req.url || '/', req.headers as Record<string, string>);
452
+ if (!vr?.ok) {
453
+ try {
454
+ socket.write('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n');
455
+ } catch {}
456
+ socket.destroy();
457
+ return;
458
+ }
459
+ extra = { query: vr.query, headers: vr.headers };
460
+ }
449
461
  const wss = await getWss();
450
- const data = matched.params ? { ...matched.handler, params: matched.params } : matched.handler;
462
+ const data =
463
+ matched.params || extra
464
+ ? { ...matched.handler, ...(matched.params ? { params: matched.params } : {}), ...(extra || {}) }
465
+ : matched.handler;
451
466
  if (!wss) {
452
467
  handleNativeWsUpgrade(req, socket, head, data);
453
468
  return;
@@ -581,16 +581,56 @@ export function serveUws(
581
581
  res.writeStatus('404 Not Found').end();
582
582
  return;
583
583
  }
584
- const handler: any = matched.params
585
- ? { ...matched.handler, params: matched.params }
586
- : matched.handler;
587
- res.upgrade(
588
- { handler, wrapped: null },
589
- req.getHeader('sec-websocket-key'),
590
- req.getHeader('sec-websocket-protocol'),
591
- req.getHeader('sec-websocket-extensions'),
592
- context
593
- );
584
+ const wsKey = req.getHeader('sec-websocket-key');
585
+ const wsProto = req.getHeader('sec-websocket-protocol');
586
+ const wsExt = req.getHeader('sec-websocket-extensions');
587
+ const validate = matched.handler.__validateUpgrade;
588
+ if (!validate) {
589
+ const handler: any = matched.params
590
+ ? { ...matched.handler, params: matched.params }
591
+ : matched.handler;
592
+ res.upgrade({ handler, wrapped: null }, wsKey, wsProto, wsExt, context);
593
+ return;
594
+ }
595
+
596
+ const hdrs: Record<string, string> = {};
597
+ req.forEach((k: string, v: string) => {
598
+ const lower = k.toLowerCase();
599
+ if (lower !== '__proto__' && lower !== 'constructor' && lower !== 'prototype') hdrs[lower] = v;
600
+ });
601
+
602
+ const finishUpgrade = (vr: any, isAsync: boolean) => {
603
+ if (!vr?.ok) {
604
+ const body = JSON.stringify({ status: 'error', code: vr?.code || 'WS_UPGRADE_INVALID', error: vr?.error });
605
+ const sendErr = () => {
606
+ res.writeStatus('400 Bad Request').writeHeader('content-type', 'application/json').end(body);
607
+ };
608
+ if (isAsync) res.cork(sendErr);
609
+ else sendErr();
610
+ return;
611
+ }
612
+ const handler: any = {
613
+ ...matched.handler,
614
+ ...(matched.params ? { params: matched.params } : {}),
615
+ ...(vr.query !== undefined ? { query: vr.query } : {}),
616
+ ...(vr.headers !== undefined ? { headers: vr.headers } : {})
617
+ };
618
+ const doUp = () => res.upgrade({ handler, wrapped: null }, wsKey, wsProto, wsExt, context);
619
+ if (isAsync) res.cork(doUp);
620
+ else doUp();
621
+ };
622
+
623
+ const vr = validate(fullUrl, hdrs);
624
+ if (vr && typeof (vr as any).then === 'function') {
625
+ let aborted = false;
626
+ res.onAborted(() => { aborted = true; });
627
+ (vr as Promise<any>).then(
628
+ (resolved) => { if (!aborted) finishUpgrade(resolved, true); },
629
+ () => { if (!aborted) finishUpgrade({ ok: false, code: 'WS_UPGRADE_INVALID' }, true); }
630
+ );
631
+ return;
632
+ }
633
+ finishUpgrade(vr, false);
594
634
  },
595
635
  open(ws: any) {
596
636
  wsCfg.adapter.open(getWrapped(ws));
@@ -527,7 +527,7 @@ const compileNativeCheck = (schema: any): ((val: any) => { ok: boolean; data?: a
527
527
  type CheckResult = { ok: boolean; data?: any; error?: any };
528
528
  type SchemaChecker = (val: any) => CheckResult | Promise<CheckResult>;
529
529
 
530
- const compileSingleSchema = (schema: any): SchemaChecker => {
530
+ export const compileSingleSchema = (schema: any): SchemaChecker => {
531
531
  if (schema && '_def' in schema) {
532
532
  return (val: any) => {
533
533
  const r = schema.safeParse(val);
@@ -794,7 +794,52 @@ const compileProjector = (schema: any): ((val: any) => any) | null => {
794
794
  )();
795
795
  };
796
796
 
797
- export const createResponseFilter = (schema: any): ((val: any) => any) => {
797
+ const STATUS_CODE_RE = /^[1-5]\d\d$/;
798
+
799
+ /**
800
+ * Detects whether a `response` option is a per-status schema map
801
+ * (e.g. `{ 200: UserSchema, 404: NotFoundSchema }`) rather than a single schema.
802
+ */
803
+ export const isStatusResponseMap = (schema: any): boolean => {
804
+ if (!schema || typeof schema !== 'object' || Array.isArray(schema)) return false;
805
+ if (
806
+ '~standard' in schema ||
807
+ '_def' in schema ||
808
+ typeof schema.parse === 'function' ||
809
+ 'type' in schema ||
810
+ 'properties' in schema ||
811
+ 'anyOf' in schema ||
812
+ 'oneOf' in schema ||
813
+ 'allOf' in schema ||
814
+ '$ref' in schema ||
815
+ Symbol.for('TypeBox.Kind') in schema
816
+ ) {
817
+ return false;
818
+ }
819
+ const keys = Object.keys(schema);
820
+ if (keys.length === 0) return false;
821
+ for (let i = 0; i < keys.length; i++) {
822
+ if (!STATUS_CODE_RE.test(keys[i]!)) return false;
823
+ }
824
+ return true;
825
+ };
826
+
827
+ export const createResponseFilter = (schema: any): ((val: any, status?: number) => any) => {
828
+ if (isStatusResponseMap(schema)) {
829
+ const byStatus = new Map<number, (val: any, status?: number) => any>();
830
+ for (const [codeStr, subSchema] of Object.entries(schema)) {
831
+ const code = Number(codeStr);
832
+ if (Number.isInteger(code) && code >= 100 && code <= 599) {
833
+ byStatus.set(code, createResponseFilter(subSchema));
834
+ }
835
+ }
836
+ return (val: any, status?: number) => {
837
+ const code = status ?? (val instanceof Response ? val.status : 200);
838
+ const filter = byStatus.get(code);
839
+ return filter ? filter(val, code) : val;
840
+ };
841
+ }
842
+
798
843
  const check = compileSingleSchema(schema);
799
844
  const project = compileProjector(schema);
800
845
 
@@ -1,3 +1,5 @@
1
+ import { isStatusResponseMap } from '../security/validators';
2
+
1
3
  export interface OpenAPIOptions {
2
4
  title?: string;
3
5
  version?: string;
@@ -119,7 +121,7 @@ export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {})
119
121
  }
120
122
  }
121
123
  if (rs.response) {
122
- responseSchema = extractSchema(rs.response);
124
+ responseSchema = rs.response;
123
125
  }
124
126
  }
125
127
  if ((h as any).__schema && !requestBody) {
@@ -151,6 +153,41 @@ export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {})
151
153
  }
152
154
  const allParams = [...pathParams, ...params];
153
155
 
156
+ const STATUS_DESCRIPTIONS: Record<string, string> = {
157
+ '200': 'Success',
158
+ '201': 'Created',
159
+ '202': 'Accepted',
160
+ '204': 'No Content',
161
+ '400': 'Bad Request',
162
+ '401': 'Unauthorized',
163
+ '403': 'Forbidden',
164
+ '404': 'Not Found',
165
+ '409': 'Conflict',
166
+ '413': 'Payload Too Large',
167
+ '415': 'Unsupported Media Type',
168
+ '422': 'Unprocessable Entity',
169
+ '429': 'Too Many Requests',
170
+ '500': 'Internal Server Error',
171
+ '503': 'Service Unavailable'
172
+ };
173
+
174
+ const responses: Record<string, any> = {};
175
+ if (responseSchema && isStatusResponseMap(responseSchema)) {
176
+ for (const [code, subSchema] of Object.entries(responseSchema)) {
177
+ responses[code] = {
178
+ description: STATUS_DESCRIPTIONS[code] || `Response ${code}`,
179
+ content: { 'application/json': { schema: extractSchema(subSchema) } }
180
+ };
181
+ }
182
+ } else {
183
+ responses['200'] = {
184
+ description: 'Success',
185
+ ...(responseSchema
186
+ ? { content: { 'application/json': { schema: extractSchema(responseSchema) } } }
187
+ : {})
188
+ };
189
+ }
190
+
154
191
  paths[openApiPath][method] = {
155
192
  summary: detail?.summary || `${route.method} ${openApiPath}`,
156
193
  ...(detail?.description ? { description: detail.description } : {}),
@@ -158,14 +195,7 @@ export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {})
158
195
  ...(routeSecurity.length ? { security: routeSecurity } : {}),
159
196
  ...(allParams.length ? { parameters: allParams } : {}),
160
197
  ...(requestBody ? { requestBody } : {}),
161
- responses: {
162
- '200': {
163
- description: 'Success',
164
- ...(responseSchema
165
- ? { content: { 'application/json': { schema: responseSchema } } }
166
- : {})
167
- }
168
- }
198
+ responses
169
199
  };
170
200
  }
171
201
 
@@ -0,0 +1,86 @@
1
+ import type { Context, Middleware, Next } from '../core/context';
2
+
3
+ export interface TracingSpan {
4
+ traceId: string;
5
+ spanId: string;
6
+ parentSpanId?: string;
7
+ traceparent: string;
8
+ method: string;
9
+ path: string;
10
+ status: number;
11
+ durationMs: number;
12
+ }
13
+
14
+ export interface TracingOptions {
15
+ /** Metric name emitted in `Server-Timing` header (default: `'app'`). Set `false` to omit. */
16
+ serverTiming?: string | false;
17
+ /** Echo W3C `traceparent` response header (default: `true`) */
18
+ exposeTraceparent?: boolean;
19
+ /** Optional span callback for forwarding to OTLP / APM / structured logger */
20
+ onSpan?: (span: TracingSpan) => void;
21
+ }
22
+
23
+ const TRACEPARENT_RE = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;
24
+ const HEX = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
25
+
26
+ const randomHex = (byteLen: number): string => {
27
+ const bytes = new Uint8Array(byteLen);
28
+ crypto.getRandomValues(bytes);
29
+ let out = '';
30
+ for (let i = 0; i < byteLen; i++) out += HEX[bytes[i]!]!;
31
+ return out;
32
+ };
33
+
34
+ /**
35
+ * Zero-dependency W3C `traceparent` + `Server-Timing` middleware.
36
+ * Tree-shakeable and Edge-safe (uses Web Crypto `crypto.getRandomValues` + `performance.now()`).
37
+ */
38
+ export const tracing = (options: TracingOptions = {}): Middleware => {
39
+ const metricName = options.serverTiming === false ? null : (options.serverTiming || 'app').replace(/[^a-zA-Z0-9_.-]/g, '');
40
+ const exposeTp = options.exposeTraceparent ?? true;
41
+ const onSpan = options.onSpan;
42
+
43
+ return async (ctx: Context, next: Next) => {
44
+ const t0 = performance.now();
45
+ const incoming = ctx.req.headers.get('traceparent')?.trim().toLowerCase();
46
+ const m = incoming ? TRACEPARENT_RE.exec(incoming) : null;
47
+
48
+ const traceId = m && m[2] !== '00000000000000000000000000000000' ? m[2]! : randomHex(16);
49
+ const parentSpanId = m && m[3] !== '0000000000000000' ? m[3]! : undefined;
50
+ const flags = m ? m[4]! : '01';
51
+ const spanId = randomHex(8);
52
+ const traceparent = `00-${traceId}-${spanId}-${flags}`;
53
+
54
+ ctx.set('traceId', traceId);
55
+ ctx.set('spanId', spanId);
56
+ if (parentSpanId) ctx.set('parentSpanId', parentSpanId);
57
+ ctx.set('traceparent', traceparent);
58
+ if (exposeTp) ctx.setHeader('traceparent', traceparent);
59
+
60
+ const res = await next();
61
+ const durationMs = performance.now() - t0;
62
+
63
+ if (metricName) {
64
+ const timingVal = `${metricName};dur=${durationMs.toFixed(2)}`;
65
+ if (res instanceof Response) {
66
+ try { res.headers.append('Server-Timing', timingVal); } catch {}
67
+ } else {
68
+ ctx.setHeader('Server-Timing', timingVal);
69
+ }
70
+ }
71
+
72
+ if (onSpan) {
73
+ const url = ctx.req.url;
74
+ const slash = url.indexOf('/', 8);
75
+ const q = slash === -1 ? -1 : url.indexOf('?', slash);
76
+ const path = slash === -1 ? '/' : (q === -1 ? url.slice(slash) : url.slice(slash, q));
77
+ const status = res instanceof Response ? res.status : (ctx._status || 200);
78
+ onSpan({ traceId, spanId, parentSpanId, traceparent, method: ctx.req.method, path, status, durationMs });
79
+ }
80
+
81
+ return res;
82
+ };
83
+ };
84
+
85
+ export const serverTiming = (metricName = 'app'): Middleware =>
86
+ tracing({ serverTiming: metricName, exposeTraceparent: false });