@thexjs/core 1.9.0 → 1.10.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.
package/README.md CHANGED
@@ -40,23 +40,22 @@ Run it via the CLI: `x dev` (or `bun run dev` if that's wired up in your `packag
40
40
 
41
41
  Given a `pagesDir`, `scanPages` walks the directory and maps files to routes:
42
42
 
43
- | File | Route |
44
- |---|---|
45
- | `src/pages/index.tsx` | `/` |
46
- | `src/pages/about.tsx` | `/about` |
47
- | `src/pages/blog/[slug].tsx` | `/blog/:slug` |
48
- | `src/pages/blog/[...rest].tsx` | `/blog/*` (catch-all) |
49
- | `src/pages/_layout.tsx` | Wraps every route in the same directory (and below) |
50
- | `src/pages/_middleware.ts` | Runs before matching routes in the same directory (and below) |
51
- | `src/pages/_404.tsx` | Custom not-found page |
52
- | `src/api/users.ts` | API route at `/api/users` (via `apiDir`) |
43
+ | File | Route |
44
+ | ------------------------------ | ------------------------------------------------------------- |
45
+ | `src/pages/index.tsx` | `/` |
46
+ | `src/pages/about.tsx` | `/about` |
47
+ | `src/pages/blog/[slug].tsx` | `/blog/:slug` |
48
+ | `src/pages/blog/[...rest].tsx` | `/blog/*` (catch-all) |
49
+ | `src/pages/_layout.tsx` | Wraps every route in the same directory (and below) |
50
+ | `src/pages/_middleware.ts` | Runs before matching routes in the same directory (and below) |
51
+ | `src/pages/_404.tsx` | Custom not-found page |
52
+ | `src/api/users.ts` | API route at `/api/users` (via `apiDir`) |
53
53
 
54
54
  Files and directories prefixed with `_` or `.` are never treated as routes.
55
55
 
56
56
  ### Route resolution order
57
57
 
58
58
  When several routes could match one URL, the most specific one wins:
59
-
60
59
  1. **Static (literal) routes beat dynamic ones** — `/users/new` is served by
61
60
  `pages/users/new.tsx`, never by `pages/users/[id].tsx`.
62
61
  2. **Single-segment params beat catch-alls** — `[slug].tsx` matches
@@ -128,7 +127,7 @@ import { Island } from "@thexjs/core";
128
127
 
129
128
  <Island name="LikeButton" client="visible">
130
129
  <LikeButton />
131
- </Island>
130
+ </Island>;
132
131
  ```
133
132
 
134
133
  `client` accepts `"idle" | "visible" | "load"`, controlling when the island hydrates on the client. Everything outside an `<Island>` stays static/server-rendered HTML with no client JS shipped.
@@ -204,6 +203,8 @@ await build({ pagesDir: "./src/pages", outDir: "./.x" });
204
203
 
205
204
  `build()` writes prerendered `static` pages (and copies `public/`) to `<outDir>/client`; that output is a plain static site, deployable anywhere (Vercel, Netlify, any CDN). Any page left in the default `server` mode requires a running Bun process (`x start`) and **is not included in the static output**. It needs a Bun-capable host (Fly.io, a VPS, Docker, etc.), not a static host or a Node-only serverless platform.
206
205
 
206
+ A single Bun process serves every request for a given server-mode app — there's no per-request isolation. `requestTimeoutMs` bounds how long any one request can take before it's given up on (504), so a hung handler can't stall the process forever, but it doesn't free up CPU mid-flight. For real isolation under load, run at least two replicas behind a load balancer in production.
207
+
207
208
  ## Enterprise readiness: security & observability
208
209
 
209
210
  `createApp` accepts optional `security` and `observability` config, all on by sane defaults:
@@ -214,6 +215,12 @@ import { createApp, createSentryReporter } from "@thexjs/core";
214
215
  const app = createApp({
215
216
  pagesDir: "./src/pages",
216
217
  actionsDir: "./src/actions",
218
+ // Opt in once you know your app has no legitimately-long requests (or has
219
+ // raised the budget on those routes specifically): a handler that hangs
220
+ // past this gets a 504 instead of stalling every other request. Unset by
221
+ // default. See "Deployment note" below for the single-process caveat this
222
+ // only partially covers.
223
+ requestTimeoutMs: 30_000,
217
224
  security: {
218
225
  // Origin/Referer verification on /__x/actions/* is always on; add explicit
219
226
  // cross-subdomain origins here, or requireToken for double-submit CSRF cookies.
@@ -241,32 +248,32 @@ Only variables prefixed `THEXJS_PUBLIC_` may reach the browser. `@thexjs/env`'s
241
248
 
242
249
  ## Exports reference
243
250
 
244
- | Export | Purpose |
245
- |---|---|
246
- | `defineConfig`, `createApp`, `CreateAppOptions`, `RouteProps`, `RevalidateOptions` | App setup / dev & runtime server |
247
- | `build`, `BuildOptions`, `RouteMode` | Static/server build step |
248
- | `renderPage`, `renderStaticPage`, `renderStreamingPage`, `LoaderArgs`, `LoaderReturn` | Lower-level render functions |
249
- | `scanRoutes`, `scanPages`, `scanApiDir`, `scanLayouts`, `scanLayoutsDir`, `scanMiddleware`, `scanNotFound`, `findLayoutChain`, `findMiddlewareChain`, `generateManifestSource`, `writeManifest` | Routing internals |
250
- | `Island`, `IslandProvider`, `IslandMode`, `IslandEntry` | Selective hydration |
251
- | `Image`, `ImageProps`, `buildSrcSet`, `SRCSET_WIDTHS`, `setImageRemoteHosts` | Optimized image component & srcset builder |
252
- | `Link`, `LinkProps` | Client-side navigation link component |
253
- | `createImageProxyHandler`, `ImageProxyOptions` | Remote image proxy handler for `_next/image`-style rewriting |
254
- | `scanContent`, `renderMarkdown`, `escapeHtml`, `ContentEntry`, `Frontmatter` | Markdown content collections |
255
- | `composeMiddleware`, `MiddlewareContext`, `MiddlewareFn`, `MiddlewareNext` | Middleware |
256
- | `registerServerFunctions`, `generateServerFunctionClient`, `getServerFunctionHandler`, `resetServerFunctions` | Server functions/actions internals |
257
- | `connectSQLite`, `connectPostgres`, `runSQLiteMigrations`, `runPostgresMigrations` | Data layer |
258
- | `DefaultNotFound`, `renderErrorOverlay`, `CLIENT_NAV_SCRIPT` | Defaults / dev tooling |
259
- | `checkCsrf`, `verifyOrigin`, `verifyCsrfToken`, `generateCsrfToken`, `withCsrfCookie`, `CsrfOptions`, `CsrfResult` | CSRF protection |
260
- | `buildSecurityHeaders`, `applySecurityHeaders`, `SecurityHeadersOptions` | Security response headers (CSP/HSTS/etc.) |
261
- | `createRateLimiter`, `rateLimitMiddleware`, `RateLimitOptions`, `RateLimitResult`, `RateLimitStore`, `createRedisRateLimitStore` | Rate limiting (per-IP fixed window) |
262
- | `findLeakedEnvKeys`, `assertNoEnvLeakage`, `EnvLeakageError`, `PUBLIC_ENV_PREFIX` | Server/client env var isolation |
263
- | `logger`, `withRequestLogging`, `Logger`, `LogFields` | Structured JSON logging |
264
- | `setErrorReporter`, `getErrorReporter`, `reportException`, `createSentryReporter`, `createOtelReporter`, `combineReporters`, `noopReporter`, `ErrorReporter` | Error reporting (Sentry/OpenTelemetry hook) |
265
- | `setTracer`, `getTracer`, `runWithRequestSpan`, `tracePhase`, `tracePhaseSync`, `withRequestTracing`, `traceRequestId`, `dbTraceAttributes`, `TracerLike`, `TraceSpan` | Tracing / OpenTelemetry spans |
266
- | `createInMemoryMetrics`, `createOtlpMetricsReporter`, `withRequestMetrics`, `noopMetrics`, `MetricsReporter`, `CounterSeries`, `HistogramSeries` | Metrics collection (Prometheus/OTLP) |
267
- | `audit`, `setAuditSink`, `clientIpFromRequest`, `requestIdFromRequest`, `AuditSink`, `AuditEntry` | Audit logging |
268
- | `createHealthCheckHandler`, `HealthCheckOptions`, `HealthCheck`, `ReadinessResult` | `/healthz` and `/readyz` |
251
+ | Export | Purpose |
252
+ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- |
253
+ | `defineConfig`, `createApp`, `CreateAppOptions`, `RouteProps`, `RevalidateOptions` | App setup / dev & runtime server |
254
+ | `build`, `BuildOptions`, `RouteMode` | Static/server build step |
255
+ | `renderPage`, `renderStaticPage`, `renderStreamingPage`, `LoaderArgs`, `LoaderReturn` | Lower-level render functions |
256
+ | `scanRoutes`, `scanPages`, `scanApiDir`, `scanLayouts`, `scanLayoutsDir`, `scanMiddleware`, `scanNotFound`, `findLayoutChain`, `findMiddlewareChain`, `generateManifestSource`, `writeManifest` | Routing internals |
257
+ | `Island`, `IslandProvider`, `IslandMode`, `IslandEntry` | Selective hydration |
258
+ | `Image`, `ImageProps`, `buildSrcSet`, `SRCSET_WIDTHS`, `setImageRemoteHosts` | Optimized image component & srcset builder |
259
+ | `Link`, `LinkProps` | Client-side navigation link component |
260
+ | `createImageProxyHandler`, `ImageProxyOptions` | Remote image proxy handler, served at `/_x/image?url=...` |
261
+ | `scanContent`, `renderMarkdown`, `escapeHtml`, `ContentEntry`, `Frontmatter` | Markdown content collections |
262
+ | `composeMiddleware`, `MiddlewareContext`, `MiddlewareFn`, `MiddlewareNext` | Middleware |
263
+ | `registerServerFunctions`, `generateServerFunctionClient`, `getServerFunctionHandler`, `resetServerFunctions` | Server functions/actions internals |
264
+ | `connectSQLite`, `connectPostgres`, `runSQLiteMigrations`, `runPostgresMigrations` | Data layer |
265
+ | `DefaultNotFound`, `renderErrorOverlay`, `CLIENT_NAV_SCRIPT` | Defaults / dev tooling |
266
+ | `checkCsrf`, `verifyOrigin`, `verifyCsrfToken`, `generateCsrfToken`, `withCsrfCookie`, `CsrfOptions`, `CsrfResult` | CSRF protection |
267
+ | `buildSecurityHeaders`, `applySecurityHeaders`, `SecurityHeadersOptions` | Security response headers (CSP/HSTS/etc.) |
268
+ | `createRateLimiter`, `rateLimitMiddleware`, `RateLimitOptions`, `RateLimitResult`, `RateLimitStore`, `createRedisRateLimitStore` | Rate limiting (per-IP fixed window) |
269
+ | `findLeakedEnvKeys`, `assertNoEnvLeakage`, `EnvLeakageError`, `PUBLIC_ENV_PREFIX` | Server/client env var isolation |
270
+ | `logger`, `withRequestLogging`, `Logger`, `LogFields` | Structured JSON logging |
271
+ | `setErrorReporter`, `getErrorReporter`, `reportException`, `createSentryReporter`, `createOtelReporter`, `combineReporters`, `noopReporter`, `ErrorReporter` | Error reporting (Sentry/OpenTelemetry hook) |
272
+ | `setTracer`, `getTracer`, `runWithRequestSpan`, `tracePhase`, `tracePhaseSync`, `withRequestTracing`, `traceRequestId`, `dbTraceAttributes`, `TracerLike`, `TraceSpan` | Tracing / OpenTelemetry spans |
273
+ | `createInMemoryMetrics`, `createOtlpMetricsReporter`, `withRequestMetrics`, `noopMetrics`, `MetricsReporter`, `CounterSeries`, `HistogramSeries` | Metrics collection (Prometheus/OTLP) |
274
+ | `audit`, `setAuditSink`, `clientIpFromRequest`, `requestIdFromRequest`, `AuditSink`, `AuditEntry` | Audit logging |
275
+ | `createHealthCheckHandler`, `HealthCheckOptions`, `HealthCheck`, `ReadinessResult` | `/healthz` and `/readyz` |
269
276
 
270
277
  ## License
271
278
 
272
- MIT
279
+ MIT
package/dist/adapter.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { B as BackpressureOptions } from './backpressure-05lHLY5O.js';
1
+ import { BackpressureOptions } from './index.js';
2
2
 
3
3
  /**
4
4
  * The scratch directory that holds the transient (transpiled module / entry
@@ -170,4 +170,5 @@ declare function allModuleRefs(manifest: BuildManifest): CompiledModuleRef[];
170
170
  */
171
171
  declare function transpileModules(refs: CompiledModuleRef[]): Promise<void>;
172
172
 
173
- export { type AdapterOptions, type BuildManifest, type CompiledModuleRef, ModuleRegistry, type ResolvedAction, type ResolvedRoute, adapterScratchDir, allModuleRefs, bundleRenderFunction, generateAdapterEntry, resolveBuildManifest, serializeRuntimeOptions, transpileModules };
173
+ export { ModuleRegistry, adapterScratchDir, allModuleRefs, bundleRenderFunction, generateAdapterEntry, resolveBuildManifest, serializeRuntimeOptions, transpileModules };
174
+ export type { AdapterOptions, BuildManifest, CompiledModuleRef, ResolvedAction, ResolvedRoute };
@@ -48,4 +48,5 @@ type BackpressureHandler<TServer = unknown> = (req: Request, server?: TServer) =
48
48
  */
49
49
  declare function withBackpressure<TServer = unknown>(handler: BackpressureHandler<TServer>, options: BackpressureOptions): BackpressureHandler<TServer>;
50
50
 
51
- export { type BackpressureOptions as B, type BackpressureController as a, type BackpressureHandler as b, type BackpressureLease as c, BackpressureSaturatedError as d, type BackpressureSnapshot as e, createBackpressureController as f, withBackpressure as w };
51
+ export { BackpressureSaturatedError as d, createBackpressureController as f, withBackpressure as w };
52
+ export type { BackpressureOptions as B, BackpressureController as a, BackpressureHandler as b, BackpressureLease as c, BackpressureSnapshot as e };
package/dist/data.d.ts CHANGED
@@ -80,4 +80,5 @@ interface SQLiteOptions {
80
80
  }
81
81
  declare function connectSQLite(options?: SQLiteOptions): Database;
82
82
 
83
- export { type MigrationOptions, type MigrationResult, type PostgresMigrationResult, type PostgresOptions, type SQLiteOptions, connectPostgres, connectSQLite, runPostgresMigrations, runSQLiteMigrations };
83
+ export { connectPostgres, connectSQLite, runPostgresMigrations, runSQLiteMigrations };
84
+ export type { MigrationOptions, MigrationResult, PostgresMigrationResult, PostgresOptions, SQLiteOptions };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { B as BackpressureOptions } from './backpressure-05lHLY5O.js';
2
- export { a as BackpressureController, b as BackpressureHandler, c as BackpressureLease, d as BackpressureSaturatedError, e as BackpressureSnapshot, f as createBackpressureController, w as withBackpressure } from './backpressure-05lHLY5O.js';
1
+ import { B as BackpressureOptions } from './backpressure-Bf3iE2Fv.js';
2
+ export { a as BackpressureController, b as BackpressureHandler, c as BackpressureLease, d as BackpressureSaturatedError, e as BackpressureSnapshot, f as createBackpressureController, w as withBackpressure } from './backpressure-Bf3iE2Fv.js';
3
3
  import * as react from 'react';
4
4
  import { ComponentType, ReactNode, CSSProperties, AnchorHTMLAttributes } from 'react';
5
5
 
@@ -476,6 +476,20 @@ interface CreateAppOptions$1 {
476
476
  * crossed. Default: 1 MiB.
477
477
  */
478
478
  maxBodySize?: number;
479
+ /**
480
+ * Maximum time, in milliseconds, a single request may take before the
481
+ * server gives up waiting and responds with 504 Gateway Timeout. Enforced
482
+ * around the whole dispatch (routing, loaders, actions, API handlers) — a
483
+ * handler that hangs past this budget can no longer stall every other
484
+ * request in the process indefinitely. The handler keeps running after the
485
+ * timeout fires (JS can't forcibly cancel synchronous work), so this bounds
486
+ * how long a *caller* waits, not CPU usage.
487
+ *
488
+ * Default: unset (no timeout). Opt in deliberately: a timeout that's too
489
+ * low will cut off legitimately slow routes (large SSR pages, streaming
490
+ * responses, long-running server actions) with a hard 504.
491
+ */
492
+ requestTimeoutMs?: number;
479
493
  /**
480
494
  * Maximum entries in the per-route island bundle caches (both the
481
495
  * route→script-list mapping and the URL→bundled-JS file cache). Entries are
@@ -1105,4 +1119,5 @@ declare function resetServerFunctions(): void;
1105
1119
  declare function registerServerFunctions(routePath: string, paramNames: string[], fns: Record<string, (...args: unknown[]) => Promise<unknown>>): void;
1106
1120
  declare function getServerFunctionHandler(csrfOptions?: CsrfOptions): (req: Request) => Promise<Response | null>;
1107
1121
 
1108
- export { type AuditEntry, type AuditEvent, type AuditSink, BackpressureOptions, type BuildOptions, CLIENT_NAV_SCRIPT, type ContentEntry, type CounterSeries, type CreateAppOptions, type CsrfOptions, type CsrfResult, DEFAULT_HISTOGRAM_BUCKETS_MS, DEFAULT_MAX_BODY_SIZE, DefaultNotFound, EnvLeakageError, type ErrorContext, type ErrorReporter, type Frontmatter, type HealthCheck, type HealthCheckOptions, type HistogramSeries, Image, type ImageProps, type ImageProxyOptions, type InMemoryMetricsOptions, type InMemoryMetricsReporter, Island, type IslandEntry, type IslandMode, IslandProvider, type LayoutEntry, Link, type LinkProps, type LoaderArgs, type LoaderReturn, type LogFields, type Logger, type MetricLabels, type MetricsReporter, type MetricsSnapshot, type MiddlewareContext, type MiddlewareEntry, type MiddlewareFn, type MiddlewareNext, type NotFoundEntry, OTEL_ERROR_STATUS_CODE, type OtelMeterLike, type OtelTracerLike, PUBLIC_ENV_PREFIX, type ProcessCrashHandlerOptions, REDACTED, type RateLimitOptions, type RateLimitResult, type RateLimitStore, type ReadinessResult, RequestBodyTooLargeError, type RevalidateOptions, type RouteEntry, type RouteMode, type RouteProps, SRCSET_WIDTHS, type SecurityHeadersOptions, type SentryLike, type TraceSpan, type TracerLike, type TrustedProxyOptions, applySecurityHeaders, assertNoEnvLeakage, audit, auditLoginFailure, auditLoginSuccess, auditLogout, auditPasswordChanged, auditPermissionDenied, auditRoleChanged, auditSessionRevoked, build, buildSecurityHeaders, buildSrcSet, checkCsrf, clientIpFromRequest, combineReporters, composeMiddleware, configureTrustedProxy, createApp, createConsoleAuditSink, createHealthCheckHandler, createImageProxyHandler, createInMemoryMetrics, createOtelReporter, createOtlpMetricsReporter, createRateLimiter, createRedisRateLimitStore, createSentryReporter, dbTraceAttributes, defineConfig, enforceRequestBodySize, escapeHtml, findLayoutChain, findLeakedEnvKeys, findMiddlewareChain, generateCsrfToken, generateManifestSource, generateServerFunctionClient, getAuditSink, getErrorReporter, getServerFunctionHandler, getTracer, installProcessCrashHandlers, isSensitiveKey, isTrustedProxy, logger, noopAuditSink, noopMetrics, noopReporter, rateLimitMiddleware, redactString, redactValue, registerServerFunctions, renderErrorOverlay, renderMarkdown, renderPage, renderStaticPage, renderStreamingPage, reportException, requestIdFromRequest, resetServerFunctions, resetTrustedProxy, runWithRequestSpan, scanApiDir, scanContent, scanLayouts, scanLayoutsDir, scanMiddleware, scanNotFound, scanPages, scanRoutes, setAuditSink, setErrorReporter, setImageRemoteHosts, setTracer, tracePhase, tracePhaseSync, traceRequestId, verifyCsrfToken, verifyOrigin, withCsrfCookie, withRequestLogging, withRequestMetrics, withRequestTracing, writeManifest };
1122
+ export { BackpressureOptions, CLIENT_NAV_SCRIPT, DEFAULT_HISTOGRAM_BUCKETS_MS, DEFAULT_MAX_BODY_SIZE, DefaultNotFound, EnvLeakageError, Image, Island, IslandProvider, Link, OTEL_ERROR_STATUS_CODE, PUBLIC_ENV_PREFIX, REDACTED, RequestBodyTooLargeError, SRCSET_WIDTHS, applySecurityHeaders, assertNoEnvLeakage, audit, auditLoginFailure, auditLoginSuccess, auditLogout, auditPasswordChanged, auditPermissionDenied, auditRoleChanged, auditSessionRevoked, build, buildSecurityHeaders, buildSrcSet, checkCsrf, clientIpFromRequest, combineReporters, composeMiddleware, configureTrustedProxy, createApp, createConsoleAuditSink, createHealthCheckHandler, createImageProxyHandler, createInMemoryMetrics, createOtelReporter, createOtlpMetricsReporter, createRateLimiter, createRedisRateLimitStore, createSentryReporter, dbTraceAttributes, defineConfig, enforceRequestBodySize, escapeHtml, findLayoutChain, findLeakedEnvKeys, findMiddlewareChain, generateCsrfToken, generateManifestSource, generateServerFunctionClient, getAuditSink, getErrorReporter, getServerFunctionHandler, getTracer, installProcessCrashHandlers, isSensitiveKey, isTrustedProxy, logger, noopAuditSink, noopMetrics, noopReporter, rateLimitMiddleware, redactString, redactValue, registerServerFunctions, renderErrorOverlay, renderMarkdown, renderPage, renderStaticPage, renderStreamingPage, reportException, requestIdFromRequest, resetServerFunctions, resetTrustedProxy, runWithRequestSpan, scanApiDir, scanContent, scanLayouts, scanLayoutsDir, scanMiddleware, scanNotFound, scanPages, scanRoutes, setAuditSink, setErrorReporter, setImageRemoteHosts, setTracer, tracePhase, tracePhaseSync, traceRequestId, verifyCsrfToken, verifyOrigin, withCsrfCookie, withRequestLogging, withRequestMetrics, withRequestTracing, writeManifest };
1123
+ export type { AuditEntry, AuditEvent, AuditSink, BuildOptions, ContentEntry, CounterSeries, CreateAppOptions, CsrfOptions, CsrfResult, ErrorContext, ErrorReporter, Frontmatter, HealthCheck, HealthCheckOptions, HistogramSeries, ImageProps, ImageProxyOptions, InMemoryMetricsOptions, InMemoryMetricsReporter, IslandEntry, IslandMode, LayoutEntry, LinkProps, LoaderArgs, LoaderReturn, LogFields, Logger, MetricLabels, MetricsReporter, MetricsSnapshot, MiddlewareContext, MiddlewareEntry, MiddlewareFn, MiddlewareNext, NotFoundEntry, OtelMeterLike, OtelTracerLike, ProcessCrashHandlerOptions, RateLimitOptions, RateLimitResult, RateLimitStore, ReadinessResult, RevalidateOptions, RouteEntry, RouteMode, RouteProps, SecurityHeadersOptions, SentryLike, TraceSpan, TracerLike, TrustedProxyOptions };
package/dist/index.js CHANGED
@@ -1654,7 +1654,7 @@ function createRedisRateLimitStoreFromClient(clientFactory) {
1654
1654
  await c.sendCommand("EXPIRE", redisKey, String(ttlSeconds));
1655
1655
  }
1656
1656
  const pttl = Number(await c.sendCommand("PTTL", redisKey));
1657
- const remainingMs = pttl > 0 ? pttl : 0;
1657
+ const remainingMs = Math.max(pttl, 0);
1658
1658
  return { count, resetAt: Date.now() + remainingMs };
1659
1659
  }
1660
1660
  };
@@ -1801,6 +1801,7 @@ async function createApp(options) {
1801
1801
  const metricsReporter = options.observability?.metrics;
1802
1802
  const rateLimiter = options.security?.rateLimit === false ? null : createRateLimiter(options.security?.rateLimit ?? {});
1803
1803
  const maxBodySize = options.maxBodySize ?? DEFAULT_MAX_BODY_SIZE;
1804
+ const requestTimeoutMs = options.requestTimeoutMs;
1804
1805
  const securityHeadersOptions = options.security?.headers;
1805
1806
  const loggingEnabled = options.observability?.logging ?? true;
1806
1807
  const imageProxyHandler = createImageProxyHandler(options.images);
@@ -2248,6 +2249,31 @@ async function createApp(options) {
2248
2249
  );
2249
2250
  }
2250
2251
  }
2252
+ const withRequestTimeout = (inner) => async (req, server) => {
2253
+ if (!requestTimeoutMs) return inner(req, server);
2254
+ let timer;
2255
+ const timeout = new Promise((resolve2) => {
2256
+ timer = setTimeout(() => {
2257
+ const path = new URL(req.url).pathname;
2258
+ reportException(new Error(`Request timed out after ${requestTimeoutMs}ms`), {
2259
+ phase: "api",
2260
+ route: path
2261
+ });
2262
+ metricsReporter?.incr("x_http_errors_total", 1, { phase: "timeout" });
2263
+ resolve2(
2264
+ new Response("Gateway Timeout", {
2265
+ status: 504,
2266
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
2267
+ })
2268
+ );
2269
+ }, requestTimeoutMs);
2270
+ });
2271
+ try {
2272
+ return await Promise.race([inner(req, server), timeout]);
2273
+ } finally {
2274
+ clearTimeout(timer);
2275
+ }
2276
+ };
2251
2277
  async function handleRevalidation(req) {
2252
2278
  if (new URL(req.url).pathname !== "/__x/revalidate") return null;
2253
2279
  if (req.method !== "POST") return new Response("Method not allowed", { status: 405 });
@@ -2446,7 +2472,9 @@ data: ${data}
2446
2472
  }
2447
2473
  return renderNotFound(req);
2448
2474
  };
2449
- const devFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(withBodySizeLimit(devFetchInner), req, server));
2475
+ const devFetchHardened = async (req, server) => withResponseHardening(
2476
+ await guardFetchErrors(withRequestTimeout(withBodySizeLimit(devFetchInner)), req, server)
2477
+ );
2450
2478
  const devFetchBase = loggingEnabled ? withRequestLogging(devFetchHardened) : devFetchHardened;
2451
2479
  const devFetchTraced = withRequestTracing(devFetchBase);
2452
2480
  const devFetch = metricsReporter ? withRequestMetrics(metricsReporter, devFetchTraced) : devFetchTraced;
@@ -2505,7 +2533,9 @@ data: ${data}
2505
2533
  }
2506
2534
  return renderNotFound(req);
2507
2535
  };
2508
- const prodFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(withBodySizeLimit(prodFetchInner), req, server));
2536
+ const prodFetchHardened = async (req, server) => withResponseHardening(
2537
+ await guardFetchErrors(withRequestTimeout(withBodySizeLimit(prodFetchInner)), req, server)
2538
+ );
2509
2539
  const prodFetchBase = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
2510
2540
  const prodFetchTraced = withRequestTracing(prodFetchBase);
2511
2541
  const prodFetch = metricsReporter ? withRequestMetrics(metricsReporter, prodFetchTraced) : prodFetchTraced;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thexjs/core",
3
- "version": "1.9.0",
3
+ "version": "1.10.0",
4
4
  "description": "Full-stack React framework core (router, SSR/SSG renderer, islands, server functions) for the x framework, built on Bun.",
5
5
  "keywords": [
6
6
  "react",
@@ -52,8 +52,8 @@
52
52
  "react-dom": "^19.0.0"
53
53
  },
54
54
  "devDependencies": {
55
- "@types/react": "^19.0.0",
56
- "@types/react-dom": "^19.2.5",
57
- "tsup": "^8.3.0"
55
+ "@types/react": "^19.3.0",
56
+ "@types/react-dom": "^19.3.0",
57
+ "tsup": "^9.0.0"
58
58
  }
59
59
  }