barejs 0.1.50 → 0.1.52

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.
@@ -52,7 +52,11 @@ export class Context {
52
52
  public _cookies: Record<string, string> | undefined = undefined;
53
53
  public _setCookies: string[] | undefined = undefined;
54
54
  public _requestId: string | undefined = undefined;
55
- constructor() { }
55
+ public _peerIp: string | undefined = undefined;
56
+ public _trustProxy: boolean = true;
57
+ constructor(trustProxy: boolean = true) {
58
+ this._trustProxy = trustProxy;
59
+ }
56
60
 
57
61
  public get query(): Record<string, string> {
58
62
  if (this._query !== undefined) return this._query;
@@ -63,6 +67,8 @@ export class Context {
63
67
  if (qIdx !== -1) {
64
68
  let start = qIdx + 1;
65
69
  const len = url.length;
70
+ const hasPlus = url.indexOf('+', start) !== -1;
71
+ const hasPct = url.indexOf('%', start) !== -1;
66
72
  while (start < len) {
67
73
  let amp = url.indexOf('&', start);
68
74
  if (amp === -1) amp = len;
@@ -77,13 +83,17 @@ export class Context {
77
83
  k = url.slice(start, amp);
78
84
  v = '';
79
85
  }
80
- if (k.indexOf('+') !== -1) k = k.replaceAll('+', ' ');
81
- if (k.indexOf('%') !== -1) {
82
- try { k = decodeURIComponent(k); } catch { /* keep raw */ }
86
+ if (hasPlus) {
87
+ if (k.indexOf('+') !== -1) k = k.replaceAll('+', ' ');
88
+ if (v.indexOf('+') !== -1) v = v.replaceAll('+', ' ');
83
89
  }
84
- if (v.indexOf('+') !== -1) v = v.replaceAll('+', ' ');
85
- if (v.indexOf('%') !== -1) {
86
- try { v = decodeURIComponent(v); } catch { /* keep raw */ }
90
+ if (hasPct) {
91
+ if (k.indexOf('%') !== -1) {
92
+ try { k = decodeURIComponent(k); } catch { /* keep raw */ }
93
+ }
94
+ if (v.indexOf('%') !== -1) {
95
+ try { v = decodeURIComponent(v); } catch { /* keep raw */ }
96
+ }
87
97
  }
88
98
  if (k !== '__proto__' && k !== 'constructor' && k !== 'prototype') {
89
99
  result[k] = v;
@@ -217,6 +227,7 @@ export class Context {
217
227
  this._cookies = undefined;
218
228
  this._setCookies = undefined;
219
229
  this.body = undefined;
230
+ this._peerIp = undefined;
220
231
  return this;
221
232
  }
222
233
 
@@ -230,14 +241,21 @@ export class Context {
230
241
  let res: Response;
231
242
 
232
243
  if (!this._headers) {
233
- res = Response.json(data, { status });
244
+ res = status === 200
245
+ ? Response.json(data)
246
+ : Response.json(data, { status });
234
247
  } else {
235
- if (this._headers["content-type"] === undefined) {
236
- this._headers["content-type"] = "application/json";
248
+ let headers = this._headers;
249
+ if (headers["content-type"] === undefined) {
250
+ if (Object.isFrozen(headers)) {
251
+ headers = { ...headers };
252
+ this._headers = headers;
253
+ }
254
+ headers["content-type"] = "application/json";
237
255
  }
238
256
  res = Response.json(data, {
239
257
  status,
240
- headers: this._headers as any
258
+ headers: headers as any
241
259
  });
242
260
  }
243
261
 
@@ -368,13 +386,15 @@ export class Context {
368
386
  }
369
387
 
370
388
  public get ip(): string {
371
- const xff = this.req?.headers?.get('x-forwarded-for');
372
- if (xff) return xff.split(',')[0]!.trim();
373
- return (
374
- this.req?.headers?.get('x-real-ip') ||
375
- this.req?.headers?.get('cf-connecting-ip') ||
376
- '127.0.0.1'
377
- );
389
+ if (this._trustProxy) {
390
+ const xff = this.req?.headers?.get('x-forwarded-for');
391
+ if (xff) return xff.split(',')[0]!.trim();
392
+ const forwarded =
393
+ this.req?.headers?.get('x-real-ip') ||
394
+ this.req?.headers?.get('cf-connecting-ip');
395
+ if (forwarded) return forwarded;
396
+ }
397
+ return this._peerIp || '127.0.0.1';
378
398
  }
379
399
 
380
400
  public async upload(options: UploadOptions = {}): Promise<UploadResult> {
@@ -1,13 +1,75 @@
1
1
  import {
2
+ type Context,
2
3
  type Middleware,
3
4
  type Handler,
4
5
  type GroupCallback
5
6
  } from '../core/context';
6
7
  import { schemaValidator, type RouteSchemas } from '../security/validators';
7
8
 
9
+ import type { RouteEndpoint, RouteSchema } from '../client/index';
10
+
8
11
  type HandlersChain = (Middleware | Handler | RouteSchemas)[];
9
12
 
10
- export class BareRouter {
13
+ export type InferSchema<S> =
14
+ S extends { static: infer T } ? T
15
+ : S extends { _output: infer T } ? T
16
+ : any;
17
+
18
+ type StripLeadingSlash<S extends string> = S extends `/${infer Rest}` ? StripLeadingSlash<Rest> : S;
19
+ type StripTrailingSlash<S extends string> = S extends `${infer Rest}/` ? StripTrailingSlash<Rest> : S;
20
+ type NormalizePrefix<P extends string> = StripTrailingSlash<StripLeadingSlash<P>> extends ''
21
+ ? ''
22
+ : `/${StripTrailingSlash<StripLeadingSlash<P>>}`;
23
+
24
+ type JoinPath<P extends string, Sub extends string> =
25
+ NormalizePrefix<P> extends ''
26
+ ? (Sub extends '' ? '/' : (Sub extends `/${string}` ? Sub : `/${Sub}`))
27
+ : (StripLeadingSlash<Sub> extends ''
28
+ ? NormalizePrefix<P>
29
+ : `${NormalizePrefix<P>}/${StripLeadingSlash<Sub>}`);
30
+
31
+ export type PrefixRoutes<P extends string, R extends RouteSchema> = {
32
+ [K in keyof R as K extends `${infer M} ${infer Sub}`
33
+ ? `${M} ${JoinPath<P, Sub>}`
34
+ : K]: R[K] extends infer E extends RouteEndpoint
35
+ ? Omit<E, 'path'> & {
36
+ path: E['path'] extends string
37
+ ? JoinPath<P, E['path']>
38
+ : JoinPath<P, K extends `${string} ${infer Sub}` ? Sub : (K & string)>;
39
+ }
40
+ : R[K];
41
+ };
42
+
43
+ type TypedRouterHandler<S extends RouteSchemas, Res> = (
44
+ ctx: Context & {
45
+ body: S extends { body: infer B } ? InferSchema<B> : any;
46
+ query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, string>;
47
+ params: S extends { params: infer Pa } ? InferSchema<Pa> : Record<string, any>;
48
+ }
49
+ ) => Res | Promise<Res>;
50
+
51
+ type AddRouterRoute<Routes extends RouteSchema, M extends string> = {
52
+ <P extends string, S extends RouteSchemas, Res = S extends { response: infer R } ? InferSchema<R> : any>(
53
+ path: P,
54
+ schemas: S,
55
+ handler: TypedRouterHandler<S, Res>
56
+ ): BareRouter<Routes & Record<`${M} ${P}`, {
57
+ method: M;
58
+ path: P;
59
+ params: S extends { params: infer Pa } ? InferSchema<Pa> : Record<string, any>;
60
+ query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, any>;
61
+ headers: S extends { headers: infer H } ? InferSchema<H> : Record<string, string>;
62
+ body: S extends { body: infer B } ? InferSchema<B> : any;
63
+ response: S extends { response: infer R } ? InferSchema<R> : Awaited<Res>;
64
+ }>>;
65
+ <P extends string, Res = any>(
66
+ path: P,
67
+ ...handlers: any[]
68
+ ): BareRouter<Routes & Record<`${M} ${P}`, { method: M; path: P; response: Awaited<Res> }>>;
69
+ };
70
+
71
+ export class BareRouter<Routes extends RouteSchema = {}> {
72
+ declare readonly __routes: Routes;
11
73
  public routes: any[] = [];
12
74
 
13
75
  constructor(
@@ -15,7 +77,7 @@ export class BareRouter {
15
77
  public groupMiddleware: any[] = []
16
78
  ) { }
17
79
 
18
- private _add(method: string, path: string, handlers: HandlersChain) {
80
+ protected _add(method: string, path: string, handlers: HandlersChain) {
19
81
  let fullPath = (this.prefix + "/" + path)
20
82
  .replace(/\/+/g, "/");
21
83
 
@@ -39,33 +101,65 @@ export class BareRouter {
39
101
  return this;
40
102
  }
41
103
 
42
- public get = (path: string, ...h: HandlersChain) => this._add("GET", path, h);
43
- public post = (path: string, ...h: HandlersChain) => this._add("POST", path, h);
44
- public put = (path: string, ...h: HandlersChain) => this._add("PUT", path, h);
45
- public patch = (path: string, ...h: HandlersChain) => this._add("PATCH", path, h);
46
- public delete = (path: string, ...h: HandlersChain) => this._add("DELETE", path, h);
47
- public options = (path: string, ...h: HandlersChain) => this._add("OPTIONS", path, h);
104
+ public get: AddRouterRoute<Routes, 'GET'> = ((path: string, ...h: HandlersChain) => this._add("GET", path, h)) as any;
105
+ public post: AddRouterRoute<Routes, 'POST'> = ((path: string, ...h: HandlersChain) => this._add("POST", path, h)) as any;
106
+ public put: AddRouterRoute<Routes, 'PUT'> = ((path: string, ...h: HandlersChain) => this._add("PUT", path, h)) as any;
107
+ public patch: AddRouterRoute<Routes, 'PATCH'> = ((path: string, ...h: HandlersChain) => this._add("PATCH", path, h)) as any;
108
+ public delete: AddRouterRoute<Routes, 'DELETE'> = ((path: string, ...h: HandlersChain) => this._add("DELETE", path, h)) as any;
109
+ public options: AddRouterRoute<Routes, 'OPTIONS'> = ((path: string, ...h: HandlersChain) => this._add("OPTIONS", path, h)) as any;
110
+ public head: AddRouterRoute<Routes, 'HEAD'> = ((path: string, ...h: HandlersChain) => this._add("HEAD", path, h)) as any;
111
+ public all: AddRouterRoute<Routes, 'ALL'> = ((path: string, ...h: HandlersChain) => {
112
+ for (const m of ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]) {
113
+ this._add(m, path, h);
114
+ }
115
+ return this;
116
+ }) as any;
48
117
 
49
118
  public group = (path: string, ...args: any[]) => {
50
119
  const callback = args.pop();
51
120
  const middleware = args;
52
121
 
53
-
54
122
  const newPrefix = (this.prefix + "/" + path).replace(/\/+/g, "/");
55
123
  const subRouter = new BareRouter(newPrefix, [...this.groupMiddleware, ...middleware]);
56
124
 
57
125
  callback(subRouter);
58
126
  this.routes.push(...subRouter.routes);
59
127
  return this;
60
- };
128
+ };
129
+
130
+ private _mountRouter(prefix: string, router: BareRouter<any>) {
131
+ const base = (this.prefix + "/" + prefix).replace(/\/+/g, "/").replace(/\/$/, "");
132
+ for (const r of router.routes) {
133
+ let fullPath = (base + "/" + r.path).replace(/\/+/g, "/");
134
+ if (fullPath.endsWith("/")) fullPath = fullPath.slice(0, -1);
135
+ this.routes.push({
136
+ method: r.method,
137
+ path: fullPath || "",
138
+ handlers: [...this.groupMiddleware, ...r.handlers]
139
+ });
140
+ }
141
+ }
142
+
143
+ public route<P extends string, R2 extends RouteSchema = {}>(
144
+ prefix: P,
145
+ router: BareRouter<R2>
146
+ ): BareRouter<Routes & PrefixRoutes<P, R2>> {
147
+ this._mountRouter(prefix, router);
148
+ return this as any;
149
+ }
61
150
 
62
- public use(mw: any) {
63
- if (mw instanceof BareRouter || (mw && mw.routes)) {
64
- this.routes.push(...mw.routes);
65
- } else if (mw && typeof mw.install === 'function') {
66
- mw.install(this);
151
+ public use<R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareRouter<Routes & R2>;
152
+ public use<P extends string, R2 extends RouteSchema = {}>(prefix: P, mw: BareRouter<R2>): BareRouter<Routes & PrefixRoutes<P, R2>>;
153
+ public use(mw: any): BareRouter<Routes>;
154
+ public use(prefixOrMw: any, maybeMw?: any): any {
155
+ if (typeof prefixOrMw === 'string' && (maybeMw instanceof BareRouter || (maybeMw && maybeMw.routes))) {
156
+ this._mountRouter(prefixOrMw, maybeMw);
157
+ } else if (prefixOrMw instanceof BareRouter || (prefixOrMw && prefixOrMw.routes)) {
158
+ this._mountRouter("", prefixOrMw);
159
+ } else if (prefixOrMw && typeof prefixOrMw.install === 'function') {
160
+ prefixOrMw.install(this);
67
161
  } else {
68
- this.groupMiddleware.push(mw);
162
+ this.groupMiddleware.push(prefixOrMw);
69
163
  }
70
164
  return this;
71
165
  }
package/src/index.ts CHANGED
@@ -6,7 +6,8 @@
6
6
  */
7
7
 
8
8
  // --- 1. Core Engine ---
9
- export { BareJS, type WebSocketRouteHandler } from './core/bare';
9
+ export { BareJS, type WebSocketRouteHandler, type CronOptions } from './core/bare';
10
+ export { BareRouter, type InferSchema, type PrefixRoutes } from './core/router';
10
11
 
11
12
  /**
12
13
  * Plugin Interface for BareJS
@@ -58,20 +59,31 @@ export {
58
59
  };
59
60
 
60
61
  // --- 5. Middlewares & Utilities ---
61
- // export { logger } from './utils/logger';
62
+ export { logger, type LoggerOptions, type LogEntry } from './utils/logger';
63
+ export { healthcheck, type HealthcheckOptions, type HealthCheckFn } from './utils/health';
62
64
  export { cors } from './security/cors';
63
65
  export { csrf, type CsrfOptions } from './security/csrf';
64
66
  export { timeout, type TimeoutOptions } from './security/timeout';
65
67
  export { rateLimit, type RateLimitOptions } from './security/rateLimit';
66
68
  export { idempotency, createSingleflight, type IdempotencyOptions } from './security/idempotency';
69
+ export {
70
+ redisStore,
71
+ type BareStore,
72
+ type RateLimitStore,
73
+ type IdempotencyStore,
74
+ type CachedIdempotentEntry,
75
+ type RevocationStore,
76
+ type RedisStoreOptions,
77
+ } from './security/store';
78
+ export { circuitBreaker, type CircuitBreakerOptions, type CircuitState } from './security/resilience';
67
79
  export { securityHeaders, type SecurityHeadersOptions } from './security/headers';
68
- export { staticFile, type StaticOptions } from './utils/static';
80
+ export { staticFile, type StaticOptions, type StaticMetadataCacheOptions } from './utils/static';
81
+ export { compress, type CompressOptions, type CompressionEncoding } from './utils/compress';
69
82
  export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
70
- export { BareRouter } from './core/router';
71
83
 
72
84
  // --- 6. Authentication (Bun Native) ---
73
85
  // Always deploy using process.env [2026-01-06]
74
- export { bareAuth, createToken, basicAuth, hasRole } from './security/auth';
86
+ export { bareAuth, createToken, basicAuth, hasRole, revokeToken, isTokenRevoked, type BareAuthOptions, type JwtAlgorithm } from './security/auth';
75
87
  // --- 7. Hashing ---
76
88
  export { Hash as Password, Hash } from './security/hash';
77
89
 
@@ -81,5 +93,6 @@ export {
81
93
  type BareClient,
82
94
  type BareClientOptions,
83
95
  type ClientRequestOptions,
96
+ type RouteEndpoint,
84
97
  type RouteSchema
85
98
  } from './client/index';