burger-api 1.0.0-beta → 1.0.0-beta.2

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/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  </div>
6
6
 
7
7
  <p align="center">
8
- <a href="https://www.npmjs.com/package/burger-api"><img src="https://img.shields.io/badge/version-1.0.0--beta-orange.svg" alt="Version 1.0.0-beta" /></a>
8
+ <a href="https://www.npmjs.com/package/burger-api"><img src="https://img.shields.io/badge/version-1.0.0--beta.1-orange.svg" alt="Version 1.0.0-beta.1" /></a>
9
9
  <a href="https://github.com/isfhan/burger-api/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="MIT License" /></a>
10
10
  <a href="https://bun.sh"><img src="https://img.shields.io/badge/Bun-1.4.4%2B-black?logo=bun" alt="Bun 1.4.4+" /></a>
11
11
  </p>
@@ -94,6 +94,7 @@ export class DirectoryScanner {
94
94
  throw new Error(`Named wildcard folder '${name}' is not supported — ` +
95
95
  `use '${ROUTE_CONSTANTS.WILDCARD_SIMPLE}' (anonymous) instead.`);
96
96
  }
97
+ assertUsableFolderName(name, dir);
97
98
  const isDynamic = name.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
98
99
  name.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END) &&
99
100
  !name.startsWith(ROUTE_CONSTANTS.WILDCARD_START);
@@ -135,6 +136,19 @@ export class DirectoryScanner {
135
136
  isWildcard: routePath.includes(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX),
136
137
  });
137
138
  }
139
+ else if (conventionByStem.size > 0) {
140
+ // No `route.ts`, so every sibling convention file applies to
141
+ // nothing — routes never inherit from parent folders.
142
+ const relativeFolder = path
143
+ .relative(this.routesDir, dir)
144
+ .split(path.sep)
145
+ .join('/');
146
+ const fileNames = [...conventionByStem.values()]
147
+ .map((file) => path.basename(file))
148
+ .sort();
149
+ console.warn(`[burger-api] ${relativeFolder || '.'} has ${fileNames.join(', ')} but no route.ts, so they apply to nothing. ` +
150
+ `Convention files are not inherited by child routes: put hooks.ts/config.ts next to each route.ts.`);
151
+ }
138
152
  // Recurse into subdirectories.
139
153
  for (const name of subDirs) {
140
154
  const childPath = path.join(dir, name);
@@ -147,6 +161,31 @@ export class DirectoryScanner {
147
161
  }
148
162
  }
149
163
  }
164
+ /**
165
+ * Route folder labels allow every RFC 3986 path character except `(` `)` `[`
166
+ * `]`, which stay reserved for the `(group)`, `[param]` and `[...]`
167
+ * conventions. Anything else can never match (or crashes `Bun.serve`), so it
168
+ * fails at startup instead of silently 404ing.
169
+ */
170
+ const USABLE_FOLDER_CHARS = /^[A-Za-z0-9._~!$&'*+,;=:@-]+$/;
171
+ function assertUsableFolderName(name, dir) {
172
+ let label = name;
173
+ if (name.length >= 2 && name[0] === '(' && name[name.length - 1] === ')') {
174
+ label = name.slice(1, -1);
175
+ }
176
+ else if (name.length >= 2 &&
177
+ name[0] === '[' &&
178
+ name[name.length - 1] === ']') {
179
+ label = name.slice(1, -1);
180
+ if (label === '...')
181
+ return; // anonymous wildcard
182
+ if (label.startsWith('...'))
183
+ label = label.slice(3);
184
+ }
185
+ if (label.length === 0 || !USABLE_FOLDER_CHARS.test(label)) {
186
+ throw new Error(`Unusable route folder name '${name}' in '${dir}': use only letters, digits and - . _ ~ ! $ & ' * + , ; = : @ (spaces and non-ASCII characters can never match a request).`);
187
+ }
188
+ }
150
189
  /**
151
190
  * Discovers the app-level convention files (`hooks`, `openapi.config`,
152
191
  * `plugins`, `providers`) in `appRoot`. Conflicting extensions for one stem
@@ -124,17 +124,19 @@ function schemaToJsonSchema(schema, mapJsonSchema, io = 'output') {
124
124
  }
125
125
  /**
126
126
  * Builds a request body object for OpenAPI based on a SchemaInput.
127
+ *
128
+ * A schema with no JSON Schema available (e.g. a Standard Schema with no
129
+ * configured converter) still emits a body with `schema: {}`, matching how
130
+ * parameters fall back — never a silent omission.
127
131
  */
128
132
  function buildRequestBody(zodSchema, mapJsonSchema) {
129
133
  if (!(zodSchema instanceof ZodType) && !isStandardSchema(zodSchema))
130
134
  return undefined;
131
135
  const jsonSchema = schemaToJsonSchema(zodSchema, mapJsonSchema, 'input');
132
- if (!jsonSchema)
133
- return undefined;
134
136
  return {
135
137
  content: {
136
138
  'application/json': {
137
- schema: jsonSchema,
139
+ schema: jsonSchema ?? {},
138
140
  },
139
141
  },
140
142
  description: 'Request body',
@@ -1,4 +1,5 @@
1
1
  import { HTTPError } from './http-error.js';
2
+ import type { HTTPErrorOptions } from './http-error.js';
2
3
  /**
3
4
  * 403 Forbidden — thrown when the user is authenticated but lacks permission.
4
5
  *
@@ -10,5 +11,5 @@ import { HTTPError } from './http-error.js';
10
11
  export declare class ForbiddenError extends HTTPError {
11
12
  readonly name = "ForbiddenError";
12
13
  readonly status: 403;
13
- constructor(message?: string, options?: ErrorOptions);
14
+ constructor(message?: string, options?: HTTPErrorOptions);
14
15
  }
@@ -6,10 +6,17 @@
6
6
  * Details. Subclasses: ValidationError (422), NotFoundError (404),
7
7
  * UnauthorizedError (401), ForbiddenError (403), MethodNotAllowedError (405).
8
8
  */
9
+ /** Options accepted by `HTTPError` and its subclasses. */
10
+ export type HTTPErrorOptions = ErrorOptions & {
11
+ /** Response headers rendered with the error (e.g. `WWW-Authenticate`). */
12
+ headers?: HeadersInit;
13
+ };
9
14
  export declare class HTTPError extends Error {
10
15
  /** HTTP status code for this error. */
11
16
  readonly status: number;
12
- constructor(status: number, message: string, options?: ErrorOptions);
17
+ /** Response headers rendered with the error, when provided. */
18
+ readonly headers?: HeadersInit;
19
+ constructor(status: number, message: string, options?: HTTPErrorOptions);
13
20
  }
14
21
  /**
15
22
  * Logs a 5xx error that no user `onError` hook handled. Server-side only:
@@ -33,7 +40,9 @@ export declare function renderUncaught(error: unknown, request: {
33
40
  * - Dev mode adds `stack` and the `cause` chain; production emits only
34
41
  * `type`, `title`, `status`, `detail`.
35
42
  * - 500 responses always carry the fixed `Internal Server Error` detail — a
36
- * thrown message is never echoed to clients.
43
+ * thrown message is never echoed to clients. Other 5xx keep the message
44
+ * only for real `HTTPError` instances; a plain object with a `status`
45
+ * gets the bare status title.
37
46
  * - Non-HTTPError values are wrapped in `HTTPError(500)`.
38
47
  * - The status is clamped to 100-599 (integer); anything else renders as 500
39
48
  * instead of escaping as a `RangeError`.
@@ -1,12 +1,18 @@
1
1
  import { resolveDebug } from '../utils/env.js';
2
2
  /**
3
- * Base HTTP error class for BurgerAPI.
4
- *
5
- * All framework errors extend this; each subclass sets a static `status` and a
6
- * default `name`. The `onError` pipeline renders them as RFC 9457 Problem
7
- * Details. Subclasses: ValidationError (422), NotFoundError (404),
8
- * UnauthorizedError (401), ForbiddenError (403), MethodNotAllowedError (405).
3
+ * Cross-copy brand. A second installed copy of this package has a different
4
+ * `HTTPError` class, so `instanceof` is false even for a genuine error —
5
+ * ecosystem plugins import `burger-api` themselves and can resolve to another
6
+ * copy of the framework. `Symbol.for` is registry-global, so the brand still
7
+ * identifies the error on both sides.
9
8
  */
9
+ const HTTP_ERROR_BRAND = Symbol.for('burger-api.http-error');
10
+ /** True for an `HTTPError` from any copy of this package. */
11
+ function isHTTPError(value) {
12
+ return (value !== null &&
13
+ typeof value === 'object' &&
14
+ value[HTTP_ERROR_BRAND] === true);
15
+ }
10
16
  export class HTTPError extends Error {
11
17
  /** HTTP status code for this error. */
12
18
  status;
@@ -14,6 +20,11 @@ export class HTTPError extends Error {
14
20
  super(message, options);
15
21
  this.status = status;
16
22
  this.name = 'HTTPError';
23
+ // Non-enumerable own brand (see HTTP_ERROR_BRAND).
24
+ Object.defineProperty(this, HTTP_ERROR_BRAND, { value: true });
25
+ if (options?.headers !== undefined) {
26
+ this.headers = options.headers;
27
+ }
17
28
  }
18
29
  }
19
30
  /**
@@ -89,7 +100,9 @@ export function renderUncaught(error, request, debug) {
89
100
  * - Dev mode adds `stack` and the `cause` chain; production emits only
90
101
  * `type`, `title`, `status`, `detail`.
91
102
  * - 500 responses always carry the fixed `Internal Server Error` detail — a
92
- * thrown message is never echoed to clients.
103
+ * thrown message is never echoed to clients. Other 5xx keep the message
104
+ * only for real `HTTPError` instances; a plain object with a `status`
105
+ * gets the bare status title.
93
106
  * - Non-HTTPError values are wrapped in `HTTPError(500)`.
94
107
  * - The status is clamped to 100-599 (integer); anything else renders as 500
95
108
  * instead of escaping as a `RangeError`.
@@ -101,7 +114,7 @@ export function renderUncaught(error, request, debug) {
101
114
  * `title`/`detail`.
102
115
  */
103
116
  export function renderHTTPError(error, isDev, extras) {
104
- const httpError = error instanceof HTTPError ||
117
+ const httpError = isHTTPError(error) ||
105
118
  (error !== null &&
106
119
  typeof error === 'object' &&
107
120
  'status' in error &&
@@ -114,15 +127,22 @@ export function renderHTTPError(error, isDev, extras) {
114
127
  const status = Number.isInteger(rawStatus) && rawStatus >= 100 && rawStatus <= 599
115
128
  ? rawStatus
116
129
  : 500;
130
+ // Server-side failures never echo the thrown message to clients. A real
131
+ // HTTPError other than 500 is written by the developer, so it may; a
132
+ // thrown object that only carries a `status` (often a library error)
133
+ // may hold secrets, so its 5xx renders the bare status title.
134
+ const hide = !isDev &&
135
+ status >= 500 &&
136
+ (status === 500 || !isHTTPError(error));
137
+ const genericTitle = STATUS_TITLES[status] ?? 'Internal Server Error';
117
138
  const problem = {
118
139
  type: 'about:blank',
119
140
  // RFC 9457: the title is the status phrase, not the class name.
120
- title: STATUS_TITLES[status] ?? httpError.name ?? 'Error',
141
+ title: hide
142
+ ? genericTitle
143
+ : (STATUS_TITLES[status] ?? httpError.name ?? 'Error'),
121
144
  status,
122
- // Server-side failures never echo the thrown message to clients.
123
- detail: status === 500 && !isDev
124
- ? 'Internal Server Error'
125
- : httpError.message,
145
+ detail: hide ? genericTitle : httpError.message,
126
146
  ...extras,
127
147
  };
128
148
  if (isDev) {
@@ -139,8 +159,11 @@ export function renderHTTPError(error, isDev, extras) {
139
159
  : { message: String(httpError.cause) };
140
160
  }
141
161
  }
142
- return new Response(JSON.stringify(problem), {
143
- status,
144
- headers: { 'Content-Type': 'application/problem+json' },
145
- });
162
+ // Caller-supplied headers come from real HTTPError instances only; a
163
+ // duck-typed thrown object must not inject response headers. The brand
164
+ // makes this work across copies of the package.
165
+ const headers = new Headers(isHTTPError(error) ? error.headers : undefined);
166
+ // RFC 9457 media type is set last so it always wins.
167
+ headers.set('Content-Type', 'application/problem+json');
168
+ return new Response(JSON.stringify(problem), { status, headers });
146
169
  }
@@ -1,4 +1,5 @@
1
1
  import { HTTPError } from './http-error.js';
2
+ import type { HTTPErrorOptions } from './http-error.js';
2
3
  /**
3
4
  * 405 Method Not Allowed — thrown when the HTTP method is not supported.
4
5
  *
@@ -9,5 +10,5 @@ import { HTTPError } from './http-error.js';
9
10
  export declare class MethodNotAllowedError extends HTTPError {
10
11
  readonly name = "MethodNotAllowedError";
11
12
  readonly status: 405;
12
- constructor(message?: string, options?: ErrorOptions);
13
+ constructor(message?: string, options?: HTTPErrorOptions);
13
14
  }
@@ -1,4 +1,5 @@
1
1
  import { HTTPError } from './http-error.js';
2
+ import type { HTTPErrorOptions } from './http-error.js';
2
3
  /**
3
4
  * 404 Not Found — thrown when a requested resource does not exist.
4
5
  *
@@ -10,5 +11,5 @@ import { HTTPError } from './http-error.js';
10
11
  export declare class NotFoundError extends HTTPError {
11
12
  readonly name = "NotFoundError";
12
13
  readonly status: 404;
13
- constructor(message?: string, options?: ErrorOptions);
14
+ constructor(message?: string, options?: HTTPErrorOptions);
14
15
  }
@@ -1,4 +1,5 @@
1
1
  import { HTTPError } from './http-error.js';
2
+ import type { HTTPErrorOptions } from './http-error.js';
2
3
  /**
3
4
  * 401 Unauthorized — thrown when authentication is missing or invalid.
4
5
  *
@@ -10,5 +11,5 @@ import { HTTPError } from './http-error.js';
10
11
  export declare class UnauthorizedError extends HTTPError {
11
12
  readonly name = "UnauthorizedError";
12
13
  readonly status: 401;
13
- constructor(message?: string, options?: ErrorOptions);
14
+ constructor(message?: string, options?: HTTPErrorOptions);
14
15
  }
@@ -117,6 +117,14 @@ export declare class Burger {
117
117
  private routesProcessed;
118
118
  /** Set once page + asset routes are registered (serve / fetchHandler). */
119
119
  private pagesProcessed?;
120
+ /**
121
+ * Memoized API + WebSocket processing: concurrent `fetchHandler()` /
122
+ * `serve()` calls share one compilation and one plugins/providers run.
123
+ * A failed attempt clears the memo so a later call retries instead of
124
+ * replaying the rejection forever.
125
+ */
126
+ private apiRoutesProcessed?;
127
+ private wsRoutesProcessed?;
120
128
  /** Set when the scanned API directory contained no route files. */
121
129
  private emptyApiDir?;
122
130
  /** Set once convention directory defaults were applied. */
@@ -184,6 +192,10 @@ export declare class Burger {
184
192
  private registerRoute;
185
193
  /** Registers page + asset routes once (shared by serve and fetchHandler). */
186
194
  private processPageRoutesOnce;
195
+ /** Compiles API routes once (shared by serve and fetchHandler). */
196
+ private processApiRoutesOnce;
197
+ /** Processes WebSocket routes once (shared by serve and fetchHandler). */
198
+ private processWebSocketRoutesOnce;
187
199
  /** Loads prebuilt or filesystem page routes. */
188
200
  private processPageRoutes;
189
201
  /**
package/dist/src/index.js CHANGED
@@ -115,6 +115,14 @@ export class Burger {
115
115
  routesProcessed = false;
116
116
  /** Set once page + asset routes are registered (serve / fetchHandler). */
117
117
  pagesProcessed;
118
+ /**
119
+ * Memoized API + WebSocket processing: concurrent `fetchHandler()` /
120
+ * `serve()` calls share one compilation and one plugins/providers run.
121
+ * A failed attempt clears the memo so a later call retries instead of
122
+ * replaying the rejection forever.
123
+ */
124
+ apiRoutesProcessed;
125
+ wsRoutesProcessed;
118
126
  /** Set when the scanned API directory contained no route files. */
119
127
  emptyApiDir;
120
128
  /** Set once convention directory defaults were applied. */
@@ -241,6 +249,34 @@ export class Burger {
241
249
  processPageRoutesOnce() {
242
250
  return (this.pagesProcessed ??= this.processPageRoutes());
243
251
  }
252
+ /** Compiles API routes once (shared by serve and fetchHandler). */
253
+ async processApiRoutesOnce() {
254
+ const pending = (this.apiRoutesProcessed ??= this.processApiRoutes());
255
+ try {
256
+ return await pending;
257
+ }
258
+ catch (error) {
259
+ // Don't cache a failed startup; the next call retries.
260
+ if (this.apiRoutesProcessed === pending) {
261
+ this.apiRoutesProcessed = undefined;
262
+ }
263
+ throw error;
264
+ }
265
+ }
266
+ /** Processes WebSocket routes once (shared by serve and fetchHandler). */
267
+ async processWebSocketRoutesOnce() {
268
+ const pending = (this.wsRoutesProcessed ??=
269
+ this.processWebSocketRoutes());
270
+ try {
271
+ return await pending;
272
+ }
273
+ catch (error) {
274
+ if (this.wsRoutesProcessed === pending) {
275
+ this.wsRoutesProcessed = undefined;
276
+ }
277
+ throw error;
278
+ }
279
+ }
244
280
  /** Loads prebuilt or filesystem page routes. */
245
281
  async processPageRoutes() {
246
282
  // Production path: use pre-built page routes (no filesystem scan)
@@ -297,14 +333,24 @@ export class Burger {
297
333
  const ctx = prebuilt
298
334
  ? prebuilt.bind(request, ctxInit)
299
335
  : BurgerContext.create(request, ctxInit, undefined, this.dynamicRouter?.getAppServices(), undefined, env, executionCtx, this.dynamicRouter?.getRequestIPHolder());
300
- const response = await handler(ctx);
301
- // With no outer onRequest/global-hook wrapper there is nobody
302
- // else to apply `ctx.set`; do it here.
303
- return prebuilt
304
- ? response
305
- : ctx.hasSet()
306
- ? applySet(response, ctx.set)
307
- : response;
336
+ try {
337
+ const response = await handler(ctx);
338
+ // With no outer onRequest/global-hook wrapper there is
339
+ // nobody else to apply `ctx.set`; do it here.
340
+ return prebuilt
341
+ ? response
342
+ : ctx.hasSet()
343
+ ? applySet(response, ctx.set)
344
+ : response;
345
+ }
346
+ catch (error) {
347
+ // The outer onRequest wrapper owns the error chain when
348
+ // present; otherwise this page wrapper is the only one that
349
+ // can run it.
350
+ if (prebuilt || !this.dynamicRouter)
351
+ throw error;
352
+ return this.dynamicRouter.renderNonRouteError(error, request, ctx, env, executionCtx);
353
+ }
308
354
  };
309
355
  return wrapped;
310
356
  }
@@ -711,7 +757,7 @@ export class Burger {
711
757
  * ```
712
758
  */
713
759
  async fetchHandler() {
714
- await this.processApiRoutes();
760
+ await this.processApiRoutesOnce();
715
761
  await this.processPageRoutesOnce();
716
762
  // Prepare WebSocket handling for WinterCG runtimes (Cloudflare /
717
763
  // Deno consume upgrades right here). Bun's `serve()` path wires the
@@ -720,7 +766,7 @@ export class Burger {
720
766
  this.programmaticWsRoutes.size > 0 ||
721
767
  !!this.wsDir;
722
768
  if (!this.wsAdapter && hasWsSources) {
723
- await this.processWebSocketRoutes();
769
+ await this.processWebSocketRoutesOnce();
724
770
  }
725
771
  const wsAdapter = this.wsAdapter;
726
772
  // Direct lookups are exact static paths: page/asset/docs handlers and
@@ -819,10 +865,10 @@ export class Burger {
819
865
  }
820
866
  // Process API routes first so convention files (plugins.ts, providers.ts)
821
867
  // are loaded before WebSocket reads the registries (avoids race).
822
- const apiConfigured = await this.processApiRoutes();
868
+ const apiConfigured = await this.processApiRoutesOnce();
823
869
  const [pagesConfigured, wsConfigured] = await Promise.all([
824
870
  this.processPageRoutesOnce(),
825
- this.processWebSocketRoutes(),
871
+ this.processWebSocketRoutesOnce(),
826
872
  ]);
827
873
  const routesConfigured = pagesConfigured || apiConfigured || wsConfigured;
828
874
  if (routesConfigured) {
@@ -975,8 +1021,16 @@ function mergeWsConfig(globalConfig, routeConfig) {
975
1021
  globalAuth === false || routeAuth === false
976
1022
  ? false
977
1023
  : {
978
- ...(typeof globalAuth === 'object' ? globalAuth : {}),
979
- ...(typeof routeAuth === 'object' ? routeAuth : {}),
1024
+ ...(globalAuth === true
1025
+ ? { required: true }
1026
+ : typeof globalAuth === 'object'
1027
+ ? globalAuth
1028
+ : {}),
1029
+ ...(routeAuth === true
1030
+ ? { required: true }
1031
+ : typeof routeAuth === 'object'
1032
+ ? routeAuth
1033
+ : {}),
980
1034
  };
981
1035
  }
982
1036
  return merged;
@@ -1,7 +1,7 @@
1
1
  import type { RouteDefinition } from '../types/index.js';
2
2
  import type { RouteModule } from '../compiler/route-module.js';
3
3
  import type { GlobalResponsePlan } from '../lifecycle/executor.js';
4
- import type { RouteHooks } from '../lifecycle/types.js';
4
+ import type { Hook, RouteHooks } from '../lifecycle/types.js';
5
5
  import type { ResolvedPlugin } from '../plugin/types.js';
6
6
  import type { BurgerServices, RequestIPHolder } from '../context/context.js';
7
7
  import type { CompiledRouter } from './types.js';
@@ -26,7 +26,7 @@ export declare class RouterCompiler {
26
26
  /** JIT HookPlan compilation (capability-gated; on unless `jit: false`). */
27
27
  private jit;
28
28
  constructor(debug?: boolean, config?: ValidatorConfig, jit?: boolean);
29
- compile(defs: RouteDefinition[], plugins?: ResolvedPlugin[], providers?: Map<string, unknown> | BurgerServices, onRequestHooksCount?: number, globalHooks?: RouteHooks, ipHolder?: RequestIPHolder): CompiledRouter;
29
+ compile(defs: RouteDefinition[], plugins?: ResolvedPlugin[], providers?: Map<string, unknown> | BurgerServices, onRequestHooks?: Hook[], globalHooks?: RouteHooks, ipHolder?: RequestIPHolder): CompiledRouter;
30
30
  /**
31
31
  * Compiles a `RouteModule[]` (the Module Loader's output) into the
32
32
  * dispatch structures — the compiler entry point for the file-based
@@ -75,7 +75,7 @@ export class RouterCompiler {
75
75
  this.config = config;
76
76
  this.jit = jit;
77
77
  }
78
- compile(defs, plugins, providers, onRequestHooksCount = 0, globalHooks, ipHolder) {
78
+ compile(defs, plugins, providers, onRequestHooks = [], globalHooks, ipHolder) {
79
79
  const staticMap = new StaticMap();
80
80
  const trie = new Trie();
81
81
  const allowCache = new AllowCache();
@@ -97,7 +97,7 @@ export class RouterCompiler {
97
97
  // Plugin / app-level hook functions every route runs; the route-access
98
98
  // analyzer scans them alongside the route's own source (once per
99
99
  // compile pass).
100
- const accessSources = collectAccessSources(plugins, globalHooks);
100
+ const accessSources = collectAccessSources(plugins, globalHooks, onRequestHooks);
101
101
  // Reserved transform keys fail startup, even for apps without routes.
102
102
  assertTransformKeys(globalHooks?.transform, 'global hooks');
103
103
  if (plugins) {
@@ -110,6 +110,7 @@ export class RouterCompiler {
110
110
  const globalResponse = buildGlobalResponsePlan(plugins, globalHooks);
111
111
  for (const def of defs) {
112
112
  const path = def.path;
113
+ assertUsableRoutePath(path);
113
114
  // Allow header: every method the route answers. HEAD is advertised
114
115
  // when GET exists (auto-HEAD) or was defined explicitly; OPTIONS is
115
116
  // always answered (auto OPTIONS), so it is always listed.
@@ -244,7 +245,7 @@ export class RouterCompiler {
244
245
  // Optional: cache provably-constant OPTIONS responses natively.
245
246
  // (Loose trailing-slash equivalence is resolved at lookup time in
246
247
  // Router.fetch, so it never shadows a `:param` empty-value match.)
247
- registerNativeOptions(path, { ...def, handlers }, hasSchema, onRequestHooksCount);
248
+ registerNativeOptions(path, { ...def, handlers }, hasSchema, onRequestHooks.length);
248
249
  }
249
250
  else {
250
251
  if (registeredPaths.has(path)) {
@@ -511,7 +512,7 @@ function omitResponseValidators(validators) {
511
512
  * their transform factories. Used by the route-access analyzer so a "known"
512
513
  * result accounts for every framework-known reader.
513
514
  */
514
- function collectAccessSources(plugins, globalHooks) {
515
+ function collectAccessSources(plugins, globalHooks, onRequestHooks) {
515
516
  const out = [];
516
517
  const pushStage = (value) => {
517
518
  if (value === undefined)
@@ -525,6 +526,7 @@ function collectAccessSources(plugins, globalHooks) {
525
526
  }
526
527
  };
527
528
  const pushHooks = (hooks) => {
529
+ pushStage(hooks.onRequest);
528
530
  pushStage(hooks.beforeRoute);
529
531
  pushStage(hooks.afterRoute);
530
532
  pushStage(hooks.mapResponse);
@@ -538,6 +540,10 @@ function collectAccessSources(plugins, globalHooks) {
538
540
  for (let i = 0; i < plugins.length; i++)
539
541
  pushHooks(plugins[i].hooks);
540
542
  }
543
+ // `onRequest` runs before routing, so its mappers read params outside the
544
+ // route handler and must be part of the analysis.
545
+ if (onRequestHooks)
546
+ pushStage(onRequestHooks);
541
547
  return out;
542
548
  }
543
549
  /**
@@ -599,9 +605,17 @@ function buildMethodCore(method, errorMethod, rawHandler, planHandler, plan, met
599
605
  // extraction.
600
606
  const bunParams = request
601
607
  .params;
602
- return bunParams !== undefined
603
- ? { params: bunParams, pattern }
604
- : extractCtxInitWithSegments(request, pattern, compiledPattern);
608
+ if (bunParams !== undefined) {
609
+ // Bun turns malformed percent escapes into U+FFFD; re-extract
610
+ // from the URL so the raw segment survives, like the fetch path.
611
+ for (const key in bunParams) {
612
+ if (bunParams[key].includes('\uFFFD')) {
613
+ return extractCtxInitWithSegments(request, pattern, compiledPattern);
614
+ }
615
+ }
616
+ return { params: bunParams, pattern };
617
+ }
618
+ return extractCtxInitWithSegments(request, pattern, compiledPattern);
605
619
  };
606
620
  const makeCtx = (request, ctxInit, prebuilt, env, executionCtx) => {
607
621
  const init = ctxInit ?? resolveCtxInit(request);
@@ -776,6 +790,42 @@ function isStaticPath(path) {
776
790
  return (!path.includes(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX) &&
777
791
  !path.includes(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX));
778
792
  }
793
+ /**
794
+ * Route path segments allow every RFC 3986 path character, plus the `:param`,
795
+ * `*` and `(group)` conventions. Fail at startup instead of emitting a dead
796
+ * route (or crashing `Bun.serve` on non-ASCII).
797
+ */
798
+ const USABLE_SEGMENT_CHARS = /^[A-Za-z0-9._~!$&'()*+,;=:@-]+$/;
799
+ function assertUsableRoutePath(path) {
800
+ const segments = path.split('/');
801
+ for (let i = 0; i < segments.length; i++) {
802
+ const segment = segments[i];
803
+ if (segment === '')
804
+ continue;
805
+ if (segment === ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX ||
806
+ segment.charCodeAt(0) === 58 /* ':' */) {
807
+ continue;
808
+ }
809
+ let label = segment;
810
+ if (segment.length >= 2 &&
811
+ segment[0] === '(' &&
812
+ segment[segment.length - 1] === ')') {
813
+ label = segment.slice(1, -1);
814
+ }
815
+ else if (segment.length >= 2 &&
816
+ segment[0] === '[' &&
817
+ segment[segment.length - 1] === ']') {
818
+ label = segment.slice(1, -1);
819
+ if (label === '...')
820
+ continue;
821
+ if (label.startsWith('...'))
822
+ label = label.slice(3);
823
+ }
824
+ if (label.length === 0 || !USABLE_SEGMENT_CHARS.test(label)) {
825
+ throw new Error(`Unusable route path segment '${label || segment}' in '${path}': use only letters, digits and - . _ ~ ! $ & ' ( ) * + , ; = : @ (spaces and non-ASCII characters can never match a request).`);
826
+ }
827
+ }
828
+ }
779
829
  /**
780
830
  * Optionally registers a provably-constant `OPTIONS` (204) response via
781
831
  * `Bun.nativeStaticResponse`. Only safe when the route has no hooks, no
@@ -2,6 +2,7 @@ import type { CompiledHandler, CompiledRoute, NativeMethodHandlers, RouterConfig
2
2
  import type { ResolvedPlugin } from '../plugin/types.js';
3
3
  import type { Hook } from '../lifecycle/types.js';
4
4
  import type { BurgerEnv, BurgerExecutionContext, BurgerServices, RequestIPHolder } from '../context/context.js';
5
+ import { BurgerContext } from '../context/context.js';
5
6
  /**
6
7
  * Public router: owns the compiled dispatch state and orchestrates lookup
7
8
  * and execution.
@@ -101,14 +102,18 @@ export declare class Router {
101
102
  /**
102
103
  * Returns the static routes as a `Bun.serve` `routes` map: one **method
103
104
  * object** per path (`{ GET: fnGet, POST: fnPost, HEAD: fnHead, ... }`).
104
- * Each method is specialized at compile time; methods not present fall
105
- * through to `fetch`, which answers 405 + Allow for known paths.
105
+ * Each method is specialized at compile time; a method the route does not
106
+ * declare answers 405 + Allow here, so Bun never falls through to a less
107
+ * specific route.
106
108
  */
107
109
  staticRoutes(): Record<string, NativeMethodHandlers>;
108
110
  /**
109
111
  * Same method-object shape for `:param` / `*` routes: Bun matches the
110
- * pattern natively and passes decoded `request.params`, so no URL
111
- * re-parsing happens on the hot path.
112
+ * pattern natively. Wildcard requests with a trailing slash are handed to
113
+ * the fetch dispatch (which strips the slash before matching); ordinary
114
+ * wildcard requests keep their native dispatch. Every HTTP method key is
115
+ * present, matching the fetch path's 405 + Allow instead of falling
116
+ * through.
112
117
  */
113
118
  nativeRoutes(): Record<string, NativeMethodHandlers>;
114
119
  /**
@@ -123,19 +128,27 @@ export declare class Router {
123
128
  staticDispatchMap(): Map<string, CompiledHandler>;
124
129
  private buildStaticDispatch;
125
130
  /**
126
- * Builds the Bun method object for one compiled path. Without hooks each
127
- * method forwards straight to the compiled core; with hooks each method
128
- * runs onRequest once before the core and binds the resulting context
129
- * onto the route.
131
+ * Builds the Bun method object for one compiled path. Every HTTP method
132
+ * key is present: a declared method runs its compiled core (wrapped by
133
+ * onRequest when hooks exist), an undeclared one answers the same
134
+ * 405 + Allow as the fetch path.
130
135
  */
131
136
  private buildMethods;
132
137
  /**
133
138
  * Wraps a non-API handler registered on the native routes map (pages,
134
139
  * static assets, `/openapi.json`, `/docs`) so global/plugin `onRequest`
135
140
  * hooks (CORS, logging, auth, rate limiting) apply to it exactly like
136
- * API routes. Returned unchanged when no `onRequest` hooks exist.
141
+ * API routes. Also catches its errors for the global/plugin `onError`
142
+ * chain. Returned unchanged when no hooks exist.
137
143
  */
138
144
  wrapWithOnRequest<T extends (request: Request) => unknown>(handler: T): T;
145
+ /**
146
+ * Runs the pre-routing `onError` chain (plugin + global) for a response
147
+ * source that has no matched route plan (page, asset, docs), then the
148
+ * global response hooks and `ctx.set` — the non-route equivalent of a
149
+ * route's error exit.
150
+ */
151
+ renderNonRouteError(error: unknown, request: Request, prebuilt?: BurgerContext, env?: BurgerEnv, executionCtx?: BurgerExecutionContext): Promise<Response>;
139
152
  /** Renders an error that escaped the pipeline; logs it when 5xx. */
140
153
  private renderUnhandled;
141
154
  /**