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.
@@ -1,7 +1,7 @@
1
1
  import { renderUncaught } from '../errors/http-error.js';
2
2
  import { dispatchOnError } from '../lifecycle/executor.js';
3
3
  import { applySet, notFound, methodNotAllowed, } from '../utils/response.js';
4
- import { extractPathnameFromUrl } from '../utils/wildcard.js';
4
+ import { extractPathnameFromUrl, urlPathnameEndsWithSlash, } from '../utils/wildcard.js';
5
5
  import { isThenable } from '../utils/thenable.js';
6
6
  import { RouterCompiler, buildGlobalResponsePlan } from './compiler.js';
7
7
  import { hasGlobalResponseHooks, runGlobalResponseHooks, } from '../lifecycle/executor.js';
@@ -11,6 +11,7 @@ import { StaticMap } from './static-map.js';
11
11
  import { Trie } from './trie.js';
12
12
  import { buildRegexMatcher, } from './regex-matcher.js';
13
13
  import { BurgerContext, EMPTY_SERVICES, createServices, isRequestIPSource, } from '../context/context.js';
14
+ import { HTTP_METHODS } from '../utils/routing.js';
14
15
  /**
15
16
  * Public router: owns the compiled dispatch state and orchestrates lookup
16
17
  * and execution.
@@ -91,7 +92,7 @@ export class Router {
91
92
  // Services are resolved once here (shared with the compiled handlers,
92
93
  // which receive the already-built object).
93
94
  this.appServices = createServices(providers);
94
- const result = this.compiler.compile(defs, plugins, this.appServices, onRequestHooks?.length ?? 0, globalHooks, this.ipHolder);
95
+ const result = this.compiler.compile(defs, plugins, this.appServices, onRequestHooks, globalHooks, this.ipHolder);
95
96
  this.staticMap = result.staticMap;
96
97
  this.trie = result.trie;
97
98
  this.allowCache = result.allowCache;
@@ -171,8 +172,9 @@ export class Router {
171
172
  /**
172
173
  * Returns the static routes as a `Bun.serve` `routes` map: one **method
173
174
  * object** per path (`{ GET: fnGet, POST: fnPost, HEAD: fnHead, ... }`).
174
- * Each method is specialized at compile time; methods not present fall
175
- * through to `fetch`, which answers 405 + Allow for known paths.
175
+ * Each method is specialized at compile time; a method the route does not
176
+ * declare answers 405 + Allow here, so Bun never falls through to a less
177
+ * specific route.
176
178
  */
177
179
  staticRoutes() {
178
180
  if (this.cachedStaticRoutes)
@@ -186,15 +188,40 @@ export class Router {
186
188
  }
187
189
  /**
188
190
  * Same method-object shape for `:param` / `*` routes: Bun matches the
189
- * pattern natively and passes decoded `request.params`, so no URL
190
- * re-parsing happens on the hot path.
191
+ * pattern natively. Wildcard requests with a trailing slash are handed to
192
+ * the fetch dispatch (which strips the slash before matching); ordinary
193
+ * wildcard requests keep their native dispatch. Every HTTP method key is
194
+ * present, matching the fetch path's 405 + Allow instead of falling
195
+ * through.
191
196
  */
192
197
  nativeRoutes() {
193
198
  if (this.cachedNativeRoutes)
194
199
  return this.cachedNativeRoutes;
195
200
  const out = {};
196
201
  for (const pattern of this.nativeRoutesMap.keys()) {
197
- out[pattern] = this.buildMethods(pattern);
202
+ const methods = this.buildMethods(pattern);
203
+ // Bun matches a native wildcard before the fetch fallback, so a
204
+ // trailing slash arrives here instead of `dispatchMatched`. Hand
205
+ // it to the fetch path, which removes the slash before matching.
206
+ if (pattern.includes('*')) {
207
+ for (const key of HTTP_METHODS) {
208
+ const inner = methods[key];
209
+ methods[key] = (request) => {
210
+ // Newer Bun versions expose the wildcard remainder;
211
+ // older ones leave `request.params` empty, so fall
212
+ // back to the URL pathname (still allocation-free).
213
+ const wildcard = request.params?.['*'];
214
+ const trailing = wildcard !== undefined
215
+ ? wildcard.endsWith('/')
216
+ : urlPathnameEndsWithSlash(request.url);
217
+ if (trailing) {
218
+ return this.fetchWithPath(request, extractPathnameFromUrl(request.url));
219
+ }
220
+ return inner(request);
221
+ };
222
+ }
223
+ }
224
+ out[pattern] = methods;
198
225
  }
199
226
  this.cachedNativeRoutes = out;
200
227
  return out;
@@ -239,23 +266,46 @@ export class Router {
239
266
  };
240
267
  }
241
268
  /**
242
- * Builds the Bun method object for one compiled path. Without hooks each
243
- * method forwards straight to the compiled core; with hooks each method
244
- * runs onRequest once before the core and binds the resulting context
245
- * onto the route.
269
+ * Builds the Bun method object for one compiled path. Every HTTP method
270
+ * key is present: a declared method runs its compiled core (wrapped by
271
+ * onRequest when hooks exist), an undeclared one answers the same
272
+ * 405 + Allow as the fetch path.
246
273
  */
247
274
  buildMethods(path) {
248
275
  const cores = this.methodCores.get(path);
249
276
  const out = {};
277
+ const allow = this.allowCache.get(path) ?? '';
250
278
  if (!this.hasOnRequest) {
251
- for (const key of Object.keys(cores)) {
279
+ // Every method key must exist on a matched path: Bun falls
280
+ // through to a less specific route when the key is missing.
281
+ const missing = this.globalResponseActive
282
+ ? (request) => this.finishNonRouteResponse(methodNotAllowed(allow), request, undefined)
283
+ : () => methodNotAllowed(allow);
284
+ for (const key of HTTP_METHODS) {
252
285
  const core = cores[key];
253
- out[key] = (request) => core(request);
286
+ out[key] = core
287
+ ? (request) => core(request)
288
+ : missing;
254
289
  }
255
290
  return out;
256
291
  }
257
- for (const key of Object.keys(cores)) {
292
+ // Missing methods still run onRequest once and the global response
293
+ // hooks, exactly like the fetch path's 405.
294
+ const missing = async (request) => {
295
+ const outcome = await this.runOnRequest(request);
296
+ if (outcome.shortCircuit)
297
+ return outcome.shortCircuit;
298
+ const finished = await this.finishNonRouteResponse(methodNotAllowed(allow), request, outcome.ctx);
299
+ return outcome.mappers.length > 0
300
+ ? this.applyMappers(finished, outcome.mappers)
301
+ : finished;
302
+ };
303
+ for (const key of HTTP_METHODS) {
258
304
  const core = cores[key];
305
+ if (!core) {
306
+ out[key] = missing;
307
+ continue;
308
+ }
259
309
  const wrapped = async (request) => {
260
310
  const outcome = await this.runOnRequest(request);
261
311
  if (outcome.shortCircuit)
@@ -280,10 +330,13 @@ export class Router {
280
330
  * Wraps a non-API handler registered on the native routes map (pages,
281
331
  * static assets, `/openapi.json`, `/docs`) so global/plugin `onRequest`
282
332
  * hooks (CORS, logging, auth, rate limiting) apply to it exactly like
283
- * API routes. Returned unchanged when no `onRequest` hooks exist.
333
+ * API routes. Also catches its errors for the global/plugin `onError`
334
+ * chain. Returned unchanged when no hooks exist.
284
335
  */
285
336
  wrapWithOnRequest(handler) {
286
- if (this.onRequestHooks.length === 0 && !this.globalResponseActive) {
337
+ if (this.onRequestHooks.length === 0 &&
338
+ !this.globalResponseActive &&
339
+ this.onErrorHooks.length === 0) {
287
340
  return handler;
288
341
  }
289
342
  const inner = handler;
@@ -302,15 +355,28 @@ export class Router {
302
355
  : finished;
303
356
  }
304
357
  catch (error) {
305
- const rendered = this.renderUnhandled(request, error);
306
- const finished = await this.finishNonRouteResponse(rendered, request, ctx, env, executionCtx);
358
+ // Page/asset/docs errors use the same onError chain as API
359
+ // routes, then the global response hooks.
360
+ const rendered = await this.renderNonRouteError(error, request, ctx, env, executionCtx);
307
361
  return outcome.mappers.length > 0
308
- ? this.applyMappers(finished, outcome.mappers)
309
- : finished;
362
+ ? this.applyMappers(rendered, outcome.mappers)
363
+ : rendered;
310
364
  }
311
365
  };
312
366
  return wrapped;
313
367
  }
368
+ /**
369
+ * Runs the pre-routing `onError` chain (plugin + global) for a response
370
+ * source that has no matched route plan (page, asset, docs), then the
371
+ * global response hooks and `ctx.set` — the non-route equivalent of a
372
+ * route's error exit.
373
+ */
374
+ async renderNonRouteError(error, request, prebuilt, env, executionCtx) {
375
+ const ctx = prebuilt ??
376
+ BurgerContext.create(request, undefined, undefined, this.appServices, undefined, env, executionCtx, this.ipHolder);
377
+ const rendered = await dispatchOnError(error, this.onErrorHooks, ctx, this.debug);
378
+ return this.finishNonRouteResponse(rendered, request, ctx, env, executionCtx);
379
+ }
314
380
  /** Renders an error that escaped the pipeline; logs it when 5xx. */
315
381
  renderUnhandled(request, error) {
316
382
  return renderUncaught(error, request, this.debug);
@@ -469,9 +535,10 @@ export class Router {
469
535
  * response in collected onRequest mappers when any exist.
470
536
  */
471
537
  dispatchMatched(request, raw, prebuilt, apply, env, executionCtx) {
472
- // Collapse repeated slashes but PRESERVE a single trailing slash (the
473
- // exact form is tried first; the slash-less form is the fallback).
474
- // The regex runs only when the path actually carries `//`.
538
+ // Collapse repeated slashes but PRESERVE a single trailing slash (an
539
+ // explicitly registered static slash form is tried first; otherwise
540
+ // the slash is removed before dynamic matching). The regex runs only
541
+ // when the path actually carries `//`.
475
542
  const path = raw.indexOf('//') === -1 ? raw : raw.replace(/\/+/g, '/');
476
543
  // 1. Exact static route (slash-preserving — Bun already serves the exact
477
544
  // form natively; this catches the trailing-slash variants it missed).
@@ -490,18 +557,15 @@ export class Router {
490
557
  ? response
491
558
  : applyToResponse(response, apply);
492
559
  }
493
- // 2. Dynamic / wildcard routes (see matchDynamic). A `:param` never
494
- // matches an empty segment (`/users/` is not `/users/:id` with id "");
495
- // a trailing slash is retried without it, so `/users/1/` ≡ `/users/1`.
560
+ // 2. Loose trailing slash: remove it BEFORE matching so a sibling
561
+ // wildcard cannot steal a `:param` match (`/users/1/` ≡ `/users/1`,
562
+ // not the wildcard with `['1', '']`). The exact slash form of a
563
+ // static route was already tried above; `/` is never stripped.
496
564
  let routePath = path;
497
- let match = this.matchDynamic(path);
498
- if (!match && path.length > 1 && path.endsWith('/')) {
499
- // 3. Loose trailing-slash fallback: `/foo/` ≡ `/foo`.
500
- // `path` is already slash-collapsed, so stripping the trailing
501
- // slash is exactly `normalizePath(raw)`.
565
+ let match = null;
566
+ if (path.length > 1 && path.endsWith('/')) {
502
567
  const normalized = path.slice(0, -1);
503
- const loose = this.staticMap.getEntry(normalized) ??
504
- this.staticMap.getEntry(normalized + '/');
568
+ const loose = this.staticMap.getEntry(normalized);
505
569
  if (loose) {
506
570
  const ctxInit = {
507
571
  route: { path: normalized, pattern: normalized },
@@ -515,8 +579,14 @@ export class Router {
515
579
  : applyToResponse(response, apply);
516
580
  }
517
581
  match = this.matchDynamic(normalized);
518
- routePath = normalized;
582
+ if (match)
583
+ routePath = normalized;
519
584
  }
585
+ // 3. Dynamic / wildcard routes in their exact form (see
586
+ // matchDynamic). A `:param` never matches an empty segment
587
+ // (`/users/` is not `/users/:id` with id "").
588
+ if (!match)
589
+ match = this.matchDynamic(path);
520
590
  if (match) {
521
591
  // Auto-HEAD: a GET route implies HEAD is allowed.
522
592
  const method = request.method;
@@ -29,10 +29,10 @@ export type NativeMethodCores = Partial<Record<HTTPMethod, RouteCore>>;
29
29
  */
30
30
  export type NativeMethodHandler = (request: Request, server?: unknown) => Response | Promise<Response>;
31
31
  /**
32
- * A Bun `routes` method object: one specialized handler per defined method
33
- * (including the framework's derived `HEAD` and auto `OPTIONS`). A method
34
- * not present here falls through to the `fetch` fallback, where the
35
- * trie/static dispatcher answers 405 + Allow.
32
+ * A Bun `routes` method object: one specialized handler per HTTP method,
33
+ * including the framework's derived `HEAD`, auto `OPTIONS`, and a 405 +
34
+ * Allow for every method the route does not declare. Keeping every key
35
+ * present stops Bun from falling through to a less specific route.
36
36
  */
37
37
  export type NativeMethodHandlers = Partial<Record<HTTPMethod, NativeMethodHandler>>;
38
38
  /**
@@ -104,6 +104,22 @@ export function hasSetMutations(set) {
104
104
  }
105
105
  return false;
106
106
  }
107
+ /**
108
+ * Null-body statuses (1xx/204/205/304) reject a body on Node and would leak
109
+ * an unused stream elsewhere. Cancel it before dropping it.
110
+ */
111
+ function bodyForStatus(response, status) {
112
+ const nullBody = status === 204 ||
113
+ status === 205 ||
114
+ status === 304 ||
115
+ (status >= 100 && status < 200);
116
+ if (!nullBody)
117
+ return response.body;
118
+ if (response.body !== null) {
119
+ void response.body.cancel().catch(() => { });
120
+ }
121
+ return null;
122
+ }
107
123
  /**
108
124
  * Merges a `ContextSet` (`ctx.set`) into the outgoing `Response`:
109
125
  * - `set.headers` is merged over the response's headers; explicitly set values
@@ -118,6 +134,7 @@ export function applySet(response, set) {
118
134
  return response;
119
135
  // Errors are authoritative: `ctx.set.status` may only restyle successes.
120
136
  const setStatus = response.status >= 400 ? undefined : set.status;
137
+ const finalStatus = setStatus ?? response.status;
121
138
  if (set instanceof TrackedContextSet) {
122
139
  const flags = set.flags;
123
140
  if (flags === 0)
@@ -126,8 +143,8 @@ export function applySet(response, set) {
126
143
  // Status-only mutation: the `Response` constructor copies the
127
144
  // header list itself, so no explicit `new Headers(...)` copy is
128
145
  // needed.
129
- return new Response(response.body, {
130
- status: setStatus ?? response.status,
146
+ return new Response(bodyForStatus(response, finalStatus), {
147
+ status: finalStatus,
131
148
  statusText: response.statusText,
132
149
  headers: response.headers,
133
150
  });
@@ -174,8 +191,8 @@ export function applySet(response, set) {
174
191
  }
175
192
  }
176
193
  }
177
- return new Response(response.body, {
178
- status: setStatus ?? response.status,
194
+ return new Response(bodyForStatus(response, finalStatus), {
195
+ status: finalStatus,
179
196
  statusText: response.statusText,
180
197
  headers,
181
198
  });
@@ -5,3 +5,9 @@
5
5
  * @returns The extracted pathname (e.g., "/api/users/123/profile")
6
6
  */
7
7
  export declare function extractPathnameFromUrl(url: string): string;
8
+ /**
9
+ * True when the pathname of a full URL string ends with `/`, without
10
+ * allocating the pathname. Needed where Bun's native wildcard handler does not
11
+ * expose `request.params['*']`.
12
+ */
13
+ export declare function urlPathnameEndsWithSlash(url: string): boolean;
@@ -26,3 +26,24 @@ export function extractPathnameFromUrl(url) {
26
26
  }
27
27
  return url.slice(pathStart);
28
28
  }
29
+ /**
30
+ * True when the pathname of a full URL string ends with `/`, without
31
+ * allocating the pathname. Needed where Bun's native wildcard handler does not
32
+ * expose `request.params['*']`.
33
+ */
34
+ export function urlPathnameEndsWithSlash(url) {
35
+ const authorityEnd = url.charCodeAt(4) === 58 /* : */
36
+ ? 7
37
+ : url.charCodeAt(5) === 58 /* : */
38
+ ? 8
39
+ : url.indexOf('://') + 3;
40
+ const found = url.indexOf('/', authorityEnd);
41
+ const pathStart = found === -1 ? 0 : found;
42
+ for (let i = pathStart; i < url.length; i++) {
43
+ const code = url.charCodeAt(i);
44
+ if (code === 63 /* ? */ || code === 35 /* # */) {
45
+ return url.charCodeAt(i - 1) === 47;
46
+ }
47
+ }
48
+ return url.charCodeAt(url.length - 1) === 47;
49
+ }
@@ -9,6 +9,7 @@
9
9
  * schema internals.
10
10
  */
11
11
  import { HTTPError } from '../errors/http-error.js';
12
+ import type { HTTPErrorOptions } from '../errors/http-error.js';
12
13
  import type { ValidationIssue, ValidationResult, ValidatorConfig, ValidationSlot } from './types.js';
13
14
  /**
14
15
  * A structured validation error thrown when request validation fails.
@@ -26,7 +27,7 @@ export declare class ValidationError extends HTTPError {
26
27
  readonly issues: ValidationIssue[];
27
28
  /** Per-slot grouping of issues, when available. */
28
29
  readonly errorsBySlot?: Record<string, ValidationIssue[]>;
29
- constructor(slot: ValidationSlot | 'response', issues: ValidationIssue[], options?: ErrorOptions & {
30
+ constructor(slot: ValidationSlot | 'response', issues: ValidationIssue[], options?: HTTPErrorOptions & {
30
31
  errorsBySlot?: Record<string, ValidationIssue[]>;
31
32
  /** Custom status code; defaults to 422 (ValidatorConfig.status). */
32
33
  status?: number;
@@ -13,7 +13,13 @@ import { HTTPError, renderHTTPError } from '../errors/http-error.js';
13
13
  function selectResponseValidator(validators, method, status) {
14
14
  // The response map only has lowercase-method keys; the caller's runtime
15
15
  // method string may be any case, so index via the widened record.
16
- const methodResponses = validators.response?.[method];
16
+ const responses = validators.response;
17
+ if (!responses)
18
+ return undefined;
19
+ let methodResponses = responses[method];
20
+ // HEAD runs the GET handler, so it follows the GET contract.
21
+ if (!methodResponses && method === 'head')
22
+ methodResponses = responses.get;
17
23
  if (!methodResponses)
18
24
  return undefined;
19
25
  if (methodResponses[String(status)])
@@ -8,6 +8,14 @@ import type { BurgerEnv, BurgerExecutionContext, RequestIPHolder } from '../cont
8
8
  import type { Hook, TransformMap } from '../lifecycle/types.js';
9
9
  import { type NodeWsBridge, type NodeWsBridgeOptions, type WsUpgradeOutcome } from './platform.js';
10
10
  import { type RuntimeTarget } from '../runtime/capabilities.js';
11
+ /**
12
+ * The runtime's server-side socket (Bun, Cloudflare/Deno, or `ws` on Node).
13
+ * The adapter only keys per-socket state on it and reads the `data` set at
14
+ * upgrade; `BurgerWSContext` probes the rest.
15
+ */
16
+ export type RawWebSocket = {
17
+ data?: unknown;
18
+ };
11
19
  /**
12
20
  * WebSocket adapter options
13
21
  */
@@ -70,12 +78,12 @@ export interface WebSocketAdapterOptions {
70
78
  * Framework handlers plus forwarded connection limits from `WebSocketConfig`.
71
79
  */
72
80
  export interface WebSocketServeOption {
73
- open: (ws: any) => void | Promise<void>;
74
- message: (ws: any, message: string | Buffer) => void | Promise<void>;
75
- close: (ws: any, code: number, reason: string) => void | Promise<void>;
76
- drain: (ws: any) => void | Promise<void>;
77
- ping: (ws: any) => void | Promise<void>;
78
- pong: (ws: any) => void | Promise<void>;
81
+ open: (ws: RawWebSocket) => void | Promise<void>;
82
+ message: (ws: RawWebSocket, message: string | Buffer) => void | Promise<void>;
83
+ close: (ws: RawWebSocket, code: number, reason: string) => void | Promise<void>;
84
+ drain: (ws: RawWebSocket) => void | Promise<void>;
85
+ ping: (ws: RawWebSocket) => void | Promise<void>;
86
+ pong: (ws: RawWebSocket) => void | Promise<void>;
79
87
  maxPayloadLength?: number;
80
88
  idleTimeout?: number;
81
89
  backpressureLimit?: number;
@@ -160,7 +168,10 @@ export declare class WebSocketAdapter {
160
168
  * that target has no persistent process.
161
169
  */
162
170
  private capabilityUnsupportedResponse;
163
- /** Shared event sink pushed into by non-Bun platforms. */
171
+ /**
172
+ * Shared event sink pushed into by non-Bun platforms. Their sockets get
173
+ * `data` attached before any event fires (see `wirePushListeners`).
174
+ */
164
175
  private eventSink;
165
176
  /**
166
177
  * Fetch-shaped wrapper around {@link handleUpgrade}, kept for backward
@@ -3,7 +3,7 @@
3
3
  */
4
4
  import { BurgerWSContext } from './types.js';
5
5
  import { HTTPError, renderHTTPError } from '../errors/http-error.js';
6
- import { BurgerContext } from '../context/context.js';
6
+ import { BurgerContext, setRequestIP } from '../context/context.js';
7
7
  import { applyTransform } from '../lifecycle/transform.js';
8
8
  import { acceptWsUpgrade, detectWsPlatform, normalizeWsMessage, } from './platform.js';
9
9
  import { RUNTIME_CAPABILITIES } from '../runtime/capabilities.js';
@@ -354,7 +354,10 @@ export class WebSocketAdapter {
354
354
  'docs for what each runtime supports.', { status: 501 }),
355
355
  };
356
356
  }
357
- /** Shared event sink pushed into by non-Bun platforms. */
357
+ /**
358
+ * Shared event sink pushed into by non-Bun platforms. Their sockets get
359
+ * `data` attached before any event fires (see `wirePushListeners`).
360
+ */
358
361
  eventSink() {
359
362
  return {
360
363
  onOpen: (raw) => this.handleOpen(raw),
@@ -391,11 +394,27 @@ export class WebSocketAdapter {
391
394
  * ```
392
395
  */
393
396
  createNodeWsBridge(options) {
394
- const wss = new options.WebSocketServer({ noServer: true });
397
+ // `ws` exposes maxPayload (not maxPayloadLength); forward only that
398
+ // connection limit, which noServer mode otherwise leaves unbounded.
399
+ const serverOptions = {
400
+ noServer: true,
401
+ };
402
+ if (this.config.maxPayloadLength !== undefined) {
403
+ serverOptions.maxPayload = this.config.maxPayloadLength;
404
+ }
405
+ const wss = new options.WebSocketServer(serverOptions);
395
406
  const adapter = this;
396
407
  return {
397
408
  async handleUpgrade(req, socket, head) {
398
- const destroy = () => socket.destroy?.();
409
+ const rawSocket = socket;
410
+ const destroy = () => rawSocket.destroy?.();
411
+ // A raw socket can error while the async auth chain is still
412
+ // running; without a listener Node would crash the process.
413
+ rawSocket.on?.('error', (error) => {
414
+ if (adapter.debug) {
415
+ console.error('[WebSocket] Upgrade socket error:', error);
416
+ }
417
+ });
399
418
  const raw = req;
400
419
  // Copy real headers, not just `host`: auth hooks may read
401
420
  // cookies/Authorization, and the Upgrade check needs them.
@@ -425,6 +444,10 @@ export class WebSocketAdapter {
425
444
  destroy();
426
445
  return;
427
446
  }
447
+ const remoteAddress = raw.socket?.remoteAddress;
448
+ if (remoteAddress !== undefined) {
449
+ setRequestIP(request, remoteAddress);
450
+ }
428
451
  const upgradeHeader = request.headers.get('upgrade');
429
452
  if (upgradeHeader?.toLowerCase() !== 'websocket') {
430
453
  destroy();
@@ -440,19 +463,27 @@ export class WebSocketAdapter {
440
463
  destroy();
441
464
  return;
442
465
  }
443
- wss.handleUpgrade(req, socket, head, (ws) => {
466
+ wss.handleUpgrade(req, socket, head, (nodeWs) => {
444
467
  // `ws` sockets do not carry `data` natively (Bun sets it via
445
468
  // `server.upgrade`), so attach it for the handlers to find
446
469
  // the matched route (and any resolved user).
470
+ const ws = nodeWs;
447
471
  ws.data = result.data;
448
- ws.on('message', (...args) => {
449
- void adapter.handleMessage(ws,
450
- // `ws`'s `'message'` event signature is
451
- // `(data: Buffer, isBinary: boolean)`.
452
- normalizeWsMessage(args[0], args[1]));
472
+ // A malformed frame emits 'error'; without a listener the
473
+ // `ws` socket crashes the Node process. It closes itself.
474
+ ws.on('error', (error) => {
475
+ if (adapter.debug) {
476
+ console.error('[WebSocket] Socket error:', error);
477
+ }
478
+ });
479
+ // `ws`'s `'message'` event is `(data: Buffer, isBinary)`.
480
+ ws.on('message', (data, isBinary) => {
481
+ void adapter.handleMessage(ws, normalizeWsMessage(data, isBinary));
453
482
  });
454
- ws.on('close', (...args) => {
455
- void adapter.handleClose(ws, args[0] ?? 1005, args[1] ?? '');
483
+ // `ws` hands the close reason as a Buffer; handlers get a
484
+ // string, as on Bun.
485
+ ws.on('close', (code, reason) => {
486
+ void adapter.handleClose(ws, code ?? 1005, reason === undefined ? '' : String(reason));
456
487
  });
457
488
  void adapter.handleOpen(ws);
458
489
  });
@@ -472,10 +503,11 @@ export class WebSocketAdapter {
472
503
  getMatch(ws) {
473
504
  let match = this.wsMatches.get(ws);
474
505
  if (!match) {
475
- match = ws?.data?.[WS_ROUTE];
506
+ const data = ws?.data;
507
+ match = data?.[WS_ROUTE];
476
508
  // Hand-wired sockets (custom bridges, tests) may still carry the
477
509
  // `data.route` shape.
478
- const legacy = ws?.data?.route;
510
+ const legacy = data?.route;
479
511
  if (!match && legacy?.handlers) {
480
512
  match = {
481
513
  route: legacy,
@@ -546,6 +578,9 @@ export class WebSocketAdapter {
546
578
  const result = await hook(ctx);
547
579
  if (result instanceof Response)
548
580
  return reject(result);
581
+ if (typeof result === 'function') {
582
+ mappers.push(result);
583
+ }
549
584
  }
550
585
  for (const hook of this.globalBeforeRoute) {
551
586
  const result = await hook(ctx);
@@ -556,10 +591,12 @@ export class WebSocketAdapter {
556
591
  }
557
592
  // Extract user from context (set by transform hooks)
558
593
  const user = ctx.user;
559
- const authConfig = routeConfig?.auth !== undefined &&
560
- typeof routeConfig.auth === 'object'
561
- ? routeConfig.auth
562
- : undefined;
594
+ const authConfig = routeConfig?.auth === true
595
+ ? { required: true }
596
+ : routeConfig?.auth !== undefined &&
597
+ typeof routeConfig.auth === 'object'
598
+ ? routeConfig.auth
599
+ : undefined;
563
600
  // Auth is enforced regardless of whether any hook ran.
564
601
  if (authConfig?.required && !user) {
565
602
  return reject(renderHTTPError(new HTTPError(401, 'Authentication required'), this.debug));
@@ -32,7 +32,7 @@ export class WebSocketCompiler {
32
32
  */
33
33
  async compile(scanned) {
34
34
  // Import ws.ts module
35
- const wsModule = (await import(scanned.wsFile));
35
+ const wsModule = await importConvention(scanned.wsFile, 'route module', scanned.path);
36
36
  // Build handlers from module exports
37
37
  const handlers = {
38
38
  open: wsModule.open,
@@ -45,7 +45,7 @@ export class WebSocketCompiler {
45
45
  // Import hooks if present
46
46
  let hooks;
47
47
  if (scanned.hooksFile) {
48
- const hooksModule = (await import(scanned.hooksFile));
48
+ const hooksModule = await importConvention(scanned.hooksFile, 'hooks module', scanned.path);
49
49
  hooks = {
50
50
  onOpen: hooksModule.onOpen,
51
51
  onMessage: hooksModule.onMessage,
@@ -55,7 +55,7 @@ export class WebSocketCompiler {
55
55
  // Import config if present
56
56
  let routeConfig = {};
57
57
  if (scanned.configFile) {
58
- const configModule = (await import(scanned.configFile));
58
+ const configModule = await importConvention(scanned.configFile, 'config module', scanned.path);
59
59
  routeConfig =
60
60
  configModule.default ??
61
61
  { ...configModule };
@@ -82,8 +82,16 @@ export class WebSocketCompiler {
82
82
  globalAuth === false || routeAuth === false
83
83
  ? false
84
84
  : {
85
- ...(typeof globalAuth === 'object' ? globalAuth : {}),
86
- ...(typeof routeAuth === 'object' ? routeAuth : {}),
85
+ ...(globalAuth === true
86
+ ? { required: true }
87
+ : typeof globalAuth === 'object'
88
+ ? globalAuth
89
+ : {}),
90
+ ...(routeAuth === true
91
+ ? { required: true }
92
+ : typeof routeAuth === 'object'
93
+ ? routeAuth
94
+ : {}),
87
95
  };
88
96
  }
89
97
  // Merge global and route-specific hooks
@@ -107,7 +115,8 @@ export class WebSocketCompiler {
107
115
  compiled.push(compiledRoute);
108
116
  }
109
117
  catch (error) {
110
- console.error(`[WebSocket] Failed to compile route: ${route.path}`, error);
118
+ const detail = error instanceof Error ? error.message : String(error);
119
+ throw new Error(`[WebSocket] Failed to compile route "${route.path}": ${detail}`, { cause: error });
111
120
  }
112
121
  }
113
122
  return compiled;
@@ -119,6 +128,19 @@ export class WebSocketCompiler {
119
128
  return mergeWsHooks(global, route);
120
129
  }
121
130
  }
131
+ /**
132
+ * Imports a convention module, naming both the route and file on failure so
133
+ * a broken module fails loud at startup instead of disappearing.
134
+ */
135
+ async function importConvention(file, kind, routePath) {
136
+ try {
137
+ return (await import(file));
138
+ }
139
+ catch (error) {
140
+ const detail = error instanceof Error ? error.message : String(error);
141
+ throw new Error(`[WebSocket] Failed to load ${kind} for route "${routePath}" from "${file}": ${detail}`, { cause: error });
142
+ }
143
+ }
122
144
  /**
123
145
  * Merges app-level and route WS hooks — global runs first, then route.
124
146
  * Shared by file-based, prebuilt (AOT) and programmatic routes.
@@ -34,7 +34,7 @@ export type WsPlatformName = 'bun' | 'cloudflare' | 'deno' | 'node';
34
34
  * parameter types, which a rest-`never[]` listener would reject.
35
35
  */
36
36
  export interface NodeWsLike {
37
- on(event: 'message' | 'close', listener: (...args: any[]) => void): void;
37
+ on(event: 'message' | 'close' | 'error', listener: (...args: any[]) => void): void;
38
38
  }
39
39
  /** Minimal shape of a framing-library `WebSocketServer` in no-server mode. */
40
40
  export interface NodeWebSocketServerLike {
@@ -43,6 +43,7 @@ export interface NodeWebSocketServerLike {
43
43
  export interface NodeWsBridgeOptions {
44
44
  WebSocketServer: new (opts: {
45
45
  noServer: true;
46
+ maxPayload?: number;
46
47
  }) => NodeWebSocketServerLike;
47
48
  }
48
49
  export interface NodeWsBridge {