keryx 0.41.2 → 0.42.0

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.
@@ -129,11 +129,13 @@ export class Swagger implements Action {
129
129
  });
130
130
  }
131
131
 
132
- // For GET/HEAD, convert remaining Zod inputs into query parameters
133
- if (
134
- (method === "get" || method === "head") &&
135
- Object.keys(zodProperties).length > 0
136
- ) {
132
+ // Endpoints whose inputs never come from the body: GET/HEAD, and raw-body
133
+ // actions (whose bodies Keryx hands to the action instead of parsing).
134
+ const inputsFromQuery =
135
+ method === "get" || method === "head" || action.web?.rawBody === true;
136
+
137
+ // Convert remaining Zod inputs into query parameters
138
+ if (inputsFromQuery && Object.keys(zodProperties).length > 0) {
137
139
  const fullSchema = z.toJSONSchema(action.inputs!, {
138
140
  io: "input",
139
141
  unrepresentable: "any",
@@ -157,7 +159,13 @@ export class Swagger implements Action {
157
159
 
158
160
  // Build requestBody if Zod inputs exist and method supports body
159
161
  let requestBody: Record<string, unknown> | undefined = undefined;
160
- if (
162
+ if (action.web?.rawBody && method !== "get" && method !== "head") {
163
+ // The body is opaque to the framework — document it as arbitrary bytes
164
+ requestBody = {
165
+ required: false,
166
+ content: { "*/*": { schema: { type: "string", format: "binary" } } },
167
+ };
168
+ } else if (
161
169
  action.inputs &&
162
170
  typeof action.inputs.parse === "function" &&
163
171
  method !== "get" &&
package/classes/Action.ts CHANGED
@@ -160,8 +160,30 @@ export type ActionConstructorInputs = {
160
160
  route?: RegExp | string;
161
161
  /** HTTP method to bind the route to */
162
162
  method?: HTTP_METHOD;
163
- /** When true, Swagger documents this endpoint as returning `text/event-stream` instead of JSON */
163
+ /**
164
+ * Declares this endpoint as a stream. Swagger documents it as returning
165
+ * `text/event-stream` instead of JSON, and the web server passes the response body
166
+ * through untouched — no compression, no idle timeout — so chunks reach the client as
167
+ * they are produced. Returning a `StreamingResponse` gets that treatment on its own;
168
+ * set this when the action hands back a raw `Response` wrapping a stream.
169
+ */
164
170
  streaming?: boolean;
171
+ /**
172
+ * When true, the framework never reads the request body. `params` are built
173
+ * from path and query params only, and the action reads the untouched body
174
+ * itself via `connection.rawRequest` (`.text()`, `.arrayBuffer()`,
175
+ * `.body` for a stream). Use this for proxies, webhook signature
176
+ * verification, and binary uploads — anything that needs the bytes exactly
177
+ * as sent, or needs to avoid buffering them twice.
178
+ *
179
+ * Because the body is never merged into `params`, a body key that collides
180
+ * with a path param cannot override it.
181
+ *
182
+ * `config.server.web.maxBodySize` is still enforced against the
183
+ * `Content-Length` header, but not while the action reads the stream — an
184
+ * action consuming a chunked body owns that limit itself.
185
+ */
186
+ rawBody?: boolean;
165
187
  };
166
188
 
167
189
  /** Per-action timeout in ms (overrides global `config.actions.timeout`; 0 disables) */
@@ -226,6 +248,7 @@ export abstract class Action {
226
248
  route: RegExp | string;
227
249
  method: HTTP_METHOD;
228
250
  streaming?: boolean;
251
+ rawBody?: boolean;
229
252
  };
230
253
  timeout?: number;
231
254
  task?: {
@@ -245,6 +268,7 @@ export abstract class Action {
245
268
  route: args.web?.route ?? `/${this.name}`,
246
269
  method: args.web?.method ?? HTTP_METHOD.GET,
247
270
  streaming: args.web?.streaming ?? false,
271
+ rawBody: args.web?.rawBody ?? false,
248
272
  };
249
273
  this.task = {
250
274
  frequency: args.task?.frequency,
@@ -112,6 +112,16 @@ export class Connection<
112
112
  sessionLoaded: boolean;
113
113
  /** The underlying transport handle (e.g., Bun `ServerWebSocket`). */
114
114
  rawConnection?: any;
115
+ /**
116
+ * The underlying `Request` for HTTP connections (`type === CONNECTION_TYPE.WEB`),
117
+ * giving actions access to headers, URL, and body. `undefined` for every other
118
+ * transport.
119
+ *
120
+ * The **body** is only readable when the action declares `web.rawBody: true` —
121
+ * otherwise the framework has already consumed it to build `params`, and
122
+ * `rawRequest.text()` resolves to `""`. Headers are always safe to read.
123
+ */
124
+ rawRequest?: Request;
115
125
  /** Rate-limit metadata populated by the rate-limit middleware. */
116
126
  rateLimitInfo?: RateLimitInfo;
117
127
  /** Request correlation ID for distributed tracing. Propagated from the incoming `X-Request-Id` header when `config.server.web.correlationId.trustProxy` is enabled. */
@@ -4,6 +4,8 @@
4
4
  * WebSocket (incremental messages), or MCP (logging messages + accumulated result).
5
5
  */
6
6
 
7
+ import { markStreamingResponse } from "../util/webStreaming";
8
+
7
9
  const encoder = new TextEncoder();
8
10
 
9
11
  /**
@@ -71,6 +73,11 @@ export class StreamingResponse {
71
73
  * the provided base headers (CORS, security, session cookie, etc.) with
72
74
  * the streaming-specific headers.
73
75
  *
76
+ * The result is marked as a stream (see `markStreamingResponse`) so the web server
77
+ * passes the body through untouched — no compression, no idle timeout — regardless
78
+ * of content type. Without the mark, anything other than `text/event-stream` would
79
+ * be buffered to completion before the first byte reached the client.
80
+ *
74
81
  * @param baseHeaders - Headers from `buildHeaders()` to merge in.
75
82
  * @returns A native `Response` with the stream as its body.
76
83
  */
@@ -78,10 +85,12 @@ export class StreamingResponse {
78
85
  const mergedHeaders = { ...baseHeaders, ...this.headers };
79
86
  mergedHeaders["Content-Type"] = this.contentType;
80
87
 
81
- return new Response(this.stream, {
82
- status: 200,
83
- headers: mergedHeaders,
84
- });
88
+ return markStreamingResponse(
89
+ new Response(this.stream, {
90
+ status: 200,
91
+ headers: mergedHeaders,
92
+ }),
93
+ );
85
94
  }
86
95
  }
87
96
 
@@ -60,6 +60,10 @@ export class Hooks extends Initializer {
60
60
  * Register a hook to run at the start of every HTTP request, before
61
61
  * routing. Covers static files, OAuth, MCP, metrics, and actions.
62
62
  * Does not fire for WebSocket upgrades.
63
+ *
64
+ * A hook that returns a `Response` answers the request itself: later
65
+ * `beforeRequest` hooks and all routing are skipped, while
66
+ * `afterRequest` hooks still fire.
63
67
  */
64
68
  beforeRequest(hook: BeforeRequestHook): void {
65
69
  self.webBeforeRequest.push(hook);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keryx",
3
- "version": "0.41.2",
3
+ "version": "0.42.0",
4
4
  "module": "index.ts",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/servers/web.ts CHANGED
@@ -30,6 +30,10 @@ import {
30
30
  } from "../util/webSocket";
31
31
  import { shouldWarnStackLeak } from "../util/webStackLeakWarning";
32
32
  import { handleStaticFile } from "../util/webStaticFiles";
33
+ import {
34
+ isStreamingResponse,
35
+ markStreamingResponse,
36
+ } from "../util/webStreaming";
33
37
 
34
38
  /**
35
39
  * Per-request context passed to {@link BeforeRequestHook} and {@link AfterRequestHook}.
@@ -66,11 +70,17 @@ export interface RequestOutcome {
66
70
  * Runs at the start of every HTTP request, before any routing or static file handling.
67
71
  * WebSocket upgrades do not fire this hook. Throwing an error propagates out of the
68
72
  * request handler. Hooks run sequentially in registration order.
73
+ *
74
+ * Returning a `Response` **short-circuits** the request: no later `beforeRequest` hook
75
+ * runs, routing (static files, OAuth, MCP, metrics, actions) is skipped, and the returned
76
+ * response is what the client receives. `afterRequest` hooks still fire, with
77
+ * `outcome.actionName` unset, and the response is still compressed. Return nothing — the
78
+ * common case — to let the request continue down the pipeline.
69
79
  */
70
80
  export type BeforeRequestHook = (
71
81
  req: Request,
72
82
  ctx: RequestContext,
73
- ) => Promise<void> | void;
83
+ ) => Promise<Response | void> | Response | void;
74
84
 
75
85
  /**
76
86
  * Runs after the `Response` is built and before compression. Receives the same `ctx`
@@ -228,7 +238,8 @@ export class WebServer extends Server<ReturnType<typeof Bun.serve>> {
228
238
 
229
239
  /**
230
240
  * Main request handler passed to `Bun.serve({ fetch })`. Dispatches to WebSocket upgrade,
231
- * static files, OAuth, MCP, or REST action handling in that order.
241
+ * static files, OAuth, MCP, or REST action handling in that order. A `beforeRequest` hook
242
+ * that returns a `Response` short-circuits everything after it.
232
243
  */
233
244
  async handleIncomingConnection(
234
245
  req: Request,
@@ -264,16 +275,24 @@ export class WebServer extends Server<ReturnType<typeof Bun.serve>> {
264
275
 
265
276
  const ctx: RequestContext = { ip, id, metadata: {} };
266
277
  const requestStart = Date.now();
278
+
279
+ // A `beforeRequest` hook that returns a Response answers the request itself —
280
+ // remaining hooks and all routing are skipped, but `afterRequest` still fires.
281
+ let response: Response | undefined;
282
+ let actionName: string | undefined;
267
283
  for (const hook of api.hooks.web.beforeRequestHooks) {
268
- await hook(req, ctx);
284
+ const hookResponse = await hook(req, ctx);
285
+ if (hookResponse instanceof Response) {
286
+ response = hookResponse;
287
+ break;
288
+ }
269
289
  }
270
290
 
271
- const { response, actionName } = await this.handleHttpRequest(
272
- req,
273
- server,
274
- ip,
275
- id,
276
- );
291
+ if (!response) {
292
+ const routed = await this.handleHttpRequest(req, server, ip, id);
293
+ response = routed.response;
294
+ actionName = routed.actionName;
295
+ }
277
296
 
278
297
  const outcome: RequestOutcome = {
279
298
  method: req.method.toUpperCase(),
@@ -285,8 +304,10 @@ export class WebServer extends Server<ReturnType<typeof Bun.serve>> {
285
304
  await hook(req, response, ctx, outcome);
286
305
  }
287
306
 
288
- // SSE and other streaming responses: disable idle timeout and skip compression
289
- if (response.headers.get("Content-Type")?.includes("text/event-stream")) {
307
+ // Streaming responses (SSE, chunked downloads, proxied bodies): disable the idle
308
+ // timeout so a stream that goes quiet between chunks is not cut, and skip compression
309
+ // so the body is passed through byte-for-byte as it is produced.
310
+ if (isStreamingResponse(response)) {
290
311
  server.timeout(req, 0);
291
312
  return response;
292
313
  }
@@ -531,6 +552,10 @@ export class WebServer extends Server<ReturnType<typeof Bun.serve>> {
531
552
 
532
553
  const connection = new Connection(CONNECTION_TYPE.WEB, ip, id);
533
554
 
555
+ // Expose the underlying request so actions can read headers and — when the
556
+ // action declares `web.rawBody` — the untouched body.
557
+ connection.rawRequest = req;
558
+
534
559
  if (
535
560
  config.server.web.correlationId.header &&
536
561
  config.server.web.correlationId.trustProxy
@@ -568,9 +593,17 @@ export class WebServer extends Server<ReturnType<typeof Bun.serve>> {
568
593
  );
569
594
  if (!actionName) errorStatusCode = 404;
570
595
 
596
+ // Actions that opt into `web.rawBody` read the body themselves off
597
+ // `connection.rawRequest`, so param parsing must leave it unread.
598
+ const rawBody =
599
+ api.actions.actions.find((a) => a.name === actionName)?.web?.rawBody ===
600
+ true;
601
+
571
602
  let params: Record<string, unknown>;
572
603
  try {
573
- params = await parseRequestParams(req, url, pathParams ?? undefined);
604
+ params = await parseRequestParams(req, url, pathParams ?? undefined, {
605
+ rawBody,
606
+ });
574
607
  } catch (e) {
575
608
  if (
576
609
  e instanceof TypedError &&
@@ -606,10 +639,21 @@ export class WebServer extends Server<ReturnType<typeof Bun.serve>> {
606
639
  errorStatusCode = ErrorStatusCodes[error.type];
607
640
  }
608
641
 
642
+ const builtResponse = error
643
+ ? buildError(connection, error, errorStatusCode, requestOrigin)
644
+ : buildResponse(connection, response, 200, requestOrigin);
645
+
646
+ // An action that declares `web.streaming` can also hand back a raw `Response` wrapping a
647
+ // stream (a proxied upstream, `Bun.file()`, an LLM relay). Treat the declaration as a
648
+ // transport hint so those bodies get the same pass-through treatment as a
649
+ // `StreamingResponse`. Errors are ordinary JSON, so they stay compressible.
650
+ if (!error && actionName) {
651
+ const action = api.actions.actions.find((a) => a.name === actionName);
652
+ if (action?.web?.streaming) markStreamingResponse(builtResponse);
653
+ }
654
+
609
655
  return {
610
- response: error
611
- ? buildError(connection, error, errorStatusCode, requestOrigin)
612
- : buildResponse(connection, response, 200, requestOrigin),
656
+ response: builtResponse,
613
657
  actionName: actionName ?? undefined,
614
658
  };
615
659
  }
@@ -1,4 +1,5 @@
1
1
  import { config } from "../config";
2
+ import { isStreamingResponse } from "./webStreaming";
2
3
 
3
4
  const INCOMPRESSIBLE_TYPES = new Set([
4
5
  "image/png",
@@ -71,13 +72,103 @@ function compressBody(body: ReadableStream, response: Response): Response {
71
72
  return new Response(stream, { status: response.status, headers });
72
73
  }
73
74
 
75
+ /**
76
+ * Reader/stream shapes described structurally, because Bun's and Node's `ReadableStream`
77
+ * typings disagree over members like `readMany` — a `Response.body` satisfies either.
78
+ */
79
+ type BodyReader = {
80
+ read(): Promise<{ done: boolean; value?: Uint8Array }>;
81
+ cancel(reason?: unknown): Promise<void>;
82
+ };
83
+ type BodyStream = { getReader(): BodyReader };
84
+
85
+ /**
86
+ * Read from a body stream until at least `limit` bytes are buffered or the stream ends.
87
+ *
88
+ * Used to answer "does this response clear the compression threshold?" for bodies with no
89
+ * `Content-Length`, without draining the whole body. The reader is returned still locked to
90
+ * the stream so the caller can resume from where this stopped.
91
+ *
92
+ * @param body The response body to read from.
93
+ * @param limit Stop reading once this many bytes have been buffered.
94
+ * @returns The buffered chunks, their total size, whether the stream ended, and the reader.
95
+ */
96
+ async function readUpTo(
97
+ body: BodyStream,
98
+ limit: number,
99
+ ): Promise<{
100
+ chunks: Uint8Array[];
101
+ size: number;
102
+ ended: boolean;
103
+ reader: BodyReader;
104
+ }> {
105
+ const reader = body.getReader();
106
+ const chunks: Uint8Array[] = [];
107
+ let size = 0;
108
+
109
+ while (size < limit) {
110
+ const { done, value } = await reader.read();
111
+ if (done) return { chunks, size, ended: true, reader };
112
+ if (value?.byteLength) {
113
+ chunks.push(value);
114
+ size += value.byteLength;
115
+ }
116
+ }
117
+
118
+ return { chunks, size, ended: false, reader };
119
+ }
120
+
121
+ /**
122
+ * Flatten buffered chunks into a single view over a fresh `ArrayBuffer` of exactly `size`
123
+ * bytes — a concrete `ArrayBuffer` rather than `ArrayBufferLike`, so the result is a valid
124
+ * `BodyInit` under both the Bun and DOM lib typings.
125
+ */
126
+ function concatChunks(
127
+ chunks: Uint8Array[],
128
+ size: number,
129
+ ): Uint8Array<ArrayBuffer> {
130
+ const out = new Uint8Array(new ArrayBuffer(size));
131
+ let offset = 0;
132
+ for (const chunk of chunks) {
133
+ out.set(chunk, offset);
134
+ offset += chunk.byteLength;
135
+ }
136
+ return out;
137
+ }
138
+
139
+ /**
140
+ * Rebuild a body stream from the chunks already read plus the rest of the reader, so a
141
+ * partially-consumed body can be piped onward without buffering what remains.
142
+ */
143
+ function restoreStream(
144
+ chunks: Uint8Array[],
145
+ reader: BodyReader,
146
+ ): ReadableStream<Uint8Array> {
147
+ return new ReadableStream<Uint8Array>({
148
+ start(controller) {
149
+ for (const chunk of chunks) controller.enqueue(chunk);
150
+ },
151
+ async pull(controller) {
152
+ const { done, value } = await reader.read();
153
+ if (done) return controller.close();
154
+ if (value) controller.enqueue(value);
155
+ },
156
+ cancel(reason) {
157
+ return reader.cancel(reason);
158
+ },
159
+ });
160
+ }
161
+
74
162
  /**
75
163
  * Conditionally compress an HTTP response based on the client's `Accept-Encoding` header,
76
164
  * the response content type, and the configured compression threshold.
77
165
  *
78
166
  * Uses the Web Streams `CompressionStream` API for async, non-blocking compression.
79
- * Skips compression for empty bodies, already-encoded responses, incompressible content
80
- * types, and responses below the size threshold.
167
+ * Skips compression for empty bodies, streaming responses, already-encoded responses,
168
+ * incompressible content types, and responses below the size threshold.
169
+ *
170
+ * Bodies with no `Content-Length` are measured by reading at most `threshold` bytes, never
171
+ * the whole body — memory stays bounded and a large or slow response keeps flowing.
81
172
  *
82
173
  * @param response The original Response to potentially compress
83
174
  * @param req The incoming Request (used to read Accept-Encoding)
@@ -92,9 +183,10 @@ export async function compressResponse(
92
183
  // No body to compress
93
184
  if (!response.body) return response;
94
185
 
95
- // Never compress SSE streams
96
- if (response.headers.get("Content-Type")?.includes("text/event-stream"))
97
- return response;
186
+ // Never touch a streaming body — SSE, chunked downloads, proxied responses. Compressing
187
+ // one would mean handing it to a CompressionStream that is free to withhold output until
188
+ // it has enough bytes to be worth a gzip block, which defeats incremental delivery.
189
+ if (isStreamingResponse(response)) return response;
98
190
 
99
191
  // Already compressed
100
192
  if (response.headers.get("Content-Encoding")) return response;
@@ -118,18 +210,28 @@ export async function compressResponse(
118
210
  return response;
119
211
  }
120
212
 
121
- // For responses without Content-Length, we need to read the body to check size
122
- // This covers most of our responses (JSON action responses, error responses)
213
+ // Without a Content-Length the size is unknown until the body is read — which covers most
214
+ // of our responses (JSON action responses, error responses). Read only as far as the
215
+ // threshold, which is all it takes to answer "is this worth compressing?", then either
216
+ // return the buffered bytes as-is or stream-compress the buffered prefix plus the rest.
217
+ // Draining the whole body here would hold an arbitrarily large response in memory and
218
+ // stall delivery until the body closed.
123
219
  if (!contentLength) {
124
- const body = await response.arrayBuffer();
125
- if (body.byteLength < config.server.web.compression.threshold) {
126
- return new Response(body, {
220
+ const threshold = config.server.web.compression.threshold;
221
+ const { chunks, size, ended, reader } = await readUpTo(
222
+ response.body,
223
+ threshold,
224
+ );
225
+
226
+ if (ended) {
227
+ // The whole body fit under the threshold, so send exactly those bytes back.
228
+ return new Response(size > 0 ? concatChunks(chunks, size) : null, {
127
229
  status: response.status,
128
230
  headers: response.headers,
129
231
  });
130
232
  }
131
233
 
132
- return compressBody(new Blob([body]).stream(), response);
234
+ return compressBody(restoreStream(chunks, reader), response);
133
235
  }
134
236
 
135
237
  // Content-Length is present and above threshold — stream-compress
@@ -112,6 +112,21 @@ async function readBodyWithLimit(req: Request): Promise<string> {
112
112
  return new TextDecoder().decode(merged);
113
113
  }
114
114
 
115
+ /**
116
+ * Extract the base media type from a request's `Content-Type` header — the
117
+ * `type/subtype` with parameters stripped, trimmed, and lowercased. So
118
+ * `"application/json; charset=utf-8"` and `"Application/JSON"` both yield
119
+ * `"application/json"`.
120
+ *
121
+ * @param req - The incoming HTTP request.
122
+ * @returns The base media type, or `null` when the header is absent.
123
+ */
124
+ export function baseMediaType(req: Request): string | null {
125
+ const header = req.headers.get("content-type");
126
+ if (header === null) return null;
127
+ return header.split(";")[0].trim().toLowerCase();
128
+ }
129
+
115
130
  /**
116
131
  * Merge a value into the params object under `key`, appending to any existing
117
132
  * value rather than replacing it. If `key` is not set, assigns `value` as-is.
@@ -134,6 +149,17 @@ function appendParam(
134
149
  : [params[key], ...incoming];
135
150
  }
136
151
 
152
+ /** Options for {@link parseRequestParams}. */
153
+ export type ParseRequestParamsOptions = {
154
+ /**
155
+ * Skip body parsing entirely, leaving `req.body` unread so the action can
156
+ * consume it itself via `connection.rawRequest`. Path params and query params
157
+ * still populate. Set by the web server when the routed action declares
158
+ * `web.rawBody: true`.
159
+ */
160
+ rawBody?: boolean;
161
+ };
162
+
137
163
  /**
138
164
  * Parse request parameters from path params, request body (JSON or form-data),
139
165
  * and query string into a single plain object.
@@ -141,17 +167,26 @@ function appendParam(
141
167
  * JSON bodies are preserved with full type fidelity (nested objects, arrays,
142
168
  * booleans, numbers). FormData bodies (multipart/form-data and
143
169
  * application/x-www-form-urlencoded) are converted to a plain object where
144
- * repeated keys become arrays and `File` values are preserved.
170
+ * repeated keys become arrays and `File` values are preserved. Content types are
171
+ * matched on the base media type, so parameters like `; charset=utf-8` do not
172
+ * change how a body is handled.
145
173
  *
146
174
  * @param req - The incoming HTTP request.
147
175
  * @param url - The parsed URL (for query string).
148
176
  * @param pathParams - Path parameters extracted by route matching.
177
+ * @param options - Parsing options. Pass `{ rawBody: true }` to leave the body
178
+ * unread — nothing is consumed off `req`, so a later reader (typically the
179
+ * action, via `connection.rawRequest`) still sees the bytes exactly as sent.
149
180
  * @returns A plain object containing all merged parameters.
181
+ * @throws {TypedError} With type {@link ErrorType.CONNECTION_ACTION_RUN} when a
182
+ * JSON body cannot be parsed, or when the body exceeds
183
+ * {@link config.server.web.maxBodySize}.
150
184
  */
151
185
  export async function parseRequestParams(
152
186
  req: Request,
153
187
  url: ReturnType<typeof parse>,
154
188
  pathParams?: Record<string, string>,
189
+ options?: ParseRequestParamsOptions,
155
190
  ): Promise<Record<string, unknown>> {
156
191
  // param load order: path params -> body params -> query params
157
192
  const params: Record<string, unknown> = {};
@@ -163,10 +198,11 @@ export async function parseRequestParams(
163
198
  }
164
199
  }
165
200
 
166
- if (
167
- req.method !== "GET" &&
168
- req.headers.get("content-type") === "application/json"
169
- ) {
201
+ // Raw-body actions own the body — resolve the content type to null so both
202
+ // body-reading branches are skipped and `req.body` is left untouched.
203
+ const contentType = options?.rawBody ? null : baseMediaType(req);
204
+
205
+ if (req.method !== "GET" && contentType === "application/json") {
170
206
  try {
171
207
  // Use streaming reader that aborts early if the body exceeds the
172
208
  // configured limit — never allocates the full oversized payload.
@@ -186,10 +222,8 @@ export async function parseRequestParams(
186
222
  }
187
223
  } else if (
188
224
  req.method !== "GET" &&
189
- (req.headers.get("content-type")?.includes("multipart/form-data") ||
190
- req.headers
191
- .get("content-type")
192
- ?.includes("application/x-www-form-urlencoded"))
225
+ (contentType === "multipart/form-data" ||
226
+ contentType === "application/x-www-form-urlencoded")
193
227
  ) {
194
228
  // For form data without a Content-Length header, stream-read the clone
195
229
  // to enforce the body size limit before handing off to the FormData parser.
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Transport-level bookkeeping for streaming HTTP responses.
3
+ *
4
+ * A `Response` whose body is produced incrementally must not be buffered, compressed,
5
+ * or cut short by an idle timeout. There is no way to detect that from the `Response`
6
+ * itself — every `Response` body is a `ReadableStream`, and a streaming body has no
7
+ * `Content-Length` to distinguish it from a small JSON payload. So the code that
8
+ * *creates* the response marks it here, and the web server reads the mark back when
9
+ * deciding whether to compress and whether to disarm Bun's idle timeout.
10
+ */
11
+
12
+ /**
13
+ * Responses known to be streams. A `WeakSet` keeps this out of the response's own
14
+ * headers (nothing leaks to the client) and lets the entries be collected with the
15
+ * responses themselves.
16
+ */
17
+ const streamingResponses = new WeakSet<Response>();
18
+
19
+ /**
20
+ * Mark a response as a stream so the web server skips compression and disables the
21
+ * idle timeout for it.
22
+ *
23
+ * @param response - The response to mark. Returned as-is for call-site chaining.
24
+ * @returns The same response instance that was passed in.
25
+ */
26
+ export function markStreamingResponse<T extends Response>(response: T): T {
27
+ streamingResponses.add(response);
28
+ return response;
29
+ }
30
+
31
+ /**
32
+ * Check whether a response should be treated as a stream.
33
+ *
34
+ * True for responses explicitly marked by {@link markStreamingResponse} (anything from
35
+ * `StreamingResponse.toResponse()`, plus raw `Response` passthrough from actions that
36
+ * declare `web.streaming`), and for any `text/event-stream` response regardless of
37
+ * origin — SSE is always incremental.
38
+ *
39
+ * @param response - The response to inspect.
40
+ * @returns True when the body must be passed through untouched.
41
+ */
42
+ export function isStreamingResponse(response: Response): boolean {
43
+ if (streamingResponses.has(response)) return true;
44
+ return (
45
+ response.headers.get("Content-Type")?.includes("text/event-stream") ?? false
46
+ );
47
+ }