@thexjs/core 0.1.5 → 1.0.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
@@ -1,14 +1,14 @@
1
1
  # @thexjs/core
2
2
 
3
- The rendering/routing engine behind **x** — a full-stack React framework built on [Bun](https://bun.sh). This package provides file-based routing, SSR/SSG rendering, islands, server functions, a content layer, and a lightweight data layer (SQLite/Postgres).
3
+ The rendering/routing engine behind **x**, a full-stack React framework built on [Bun](https://bun.sh). This package provides file-based routing, SSR/SSG rendering, islands, server functions, a content layer, and a lightweight data layer (SQLite/Postgres).
4
4
 
5
- You typically don't install this directly — [`@thexjs/cli`](https://www.npmjs.com/package/@thexjs/cli) depends on it and drives `x dev` / `x build` / `x start` for you. Install it explicitly only if you're calling the APIs below directly (e.g. a custom server entry).
5
+ You typically don't install this directly. [`@thexjs/cli`](https://www.npmjs.com/package/@thexjs/cli) depends on it and drives `x dev` / `x build` / `x start` for you. Install it explicitly only if you're calling the APIs below directly (e.g. a custom server entry).
6
6
 
7
7
  ```sh
8
8
  bun add @thexjs/core
9
9
  ```
10
10
 
11
- > Requires the Bun runtime — this package uses `Bun.serve`, `Bun.file`, `bun:sqlite`, and `Bun.sql` internally.
11
+ > Requires the Bun runtime. This package uses `Bun.serve`, `Bun.file`, `bun:sqlite`, and `Bun.sql` internally.
12
12
 
13
13
  ## Quick start
14
14
 
@@ -45,10 +45,11 @@ Given a `pagesDir`, `scanPages` walks the directory and maps files to routes:
45
45
  | `src/pages/index.tsx` | `/` |
46
46
  | `src/pages/about.tsx` | `/about` |
47
47
  | `src/pages/blog/[slug].tsx` | `/blog/:slug` |
48
- | `src/pages/api/users.ts` | API route at `/api/users` |
48
+ | `src/pages/blog/[...rest].tsx` | `/blog/*` (catch-all) |
49
49
  | `src/pages/_layout.tsx` | Wraps every route in the same directory (and below) |
50
50
  | `src/pages/_middleware.ts` | Runs before matching routes in the same directory (and below) |
51
51
  | `src/pages/_404.tsx` | Custom not-found page |
52
+ | `src/api/users.ts` | API route at `/api/users` (via `apiDir`) |
52
53
 
53
54
  Files and directories prefixed with `_` or `.` are never treated as routes.
54
55
 
@@ -62,8 +63,8 @@ Every page defaults to **server-rendered (SSR)**. Opt into build-time prerenderi
62
63
  export const mode: "static" | "server" = "static";
63
64
  ```
64
65
 
65
- - **`static`** — rendered once at `x build` time to a `.html` file. Best for marketing pages, docs, blog posts — anything that doesn't need per-request data. No page in your app defaults to this; you must set it explicitly, or the build step will silently ship an empty/server-only route with no prerendered HTML.
66
- - **`server`** (default) — rendered per-request via `renderPage` / `renderStreamingPage` when running under `x start` (or `x dev`). Requires a live Bun server; **not deployable to static hosts** (see Deployment below).
66
+ - **`static`**: rendered once at `x build` time to a `.html` file. Best for marketing pages, docs, blog posts, anything that doesn't need per-request data. No page in your app defaults to this; you must set it explicitly, or the build step will silently ship an empty/server-only route with no prerendered HTML.
67
+ - **`server`** (default): rendered per-request via `renderPage` / `renderStreamingPage` when running under `x start` (or `x dev`). Requires a live Bun server; **not deployable to static hosts** (see Deployment below).
67
68
 
68
69
  ## Loaders
69
70
 
@@ -76,8 +77,9 @@ export async function loader({ params }: { params: Record<string, string> }) {
76
77
  return { user: await getUser(params.id) };
77
78
  }
78
79
 
79
- export default function UserPage({ loaderData }: RouteProps<typeof loader>) {
80
- return <p>{loaderData.user.name}</p>;
80
+ export default function UserPage({ loaderData }: RouteProps) {
81
+ const { user } = loaderData as { user: { name: string } };
82
+ return <p>{user.name}</p>;
81
83
  }
82
84
  ```
83
85
 
@@ -85,16 +87,20 @@ export default function UserPage({ loaderData }: RouteProps<typeof loader>) {
85
87
 
86
88
  ## Server functions / actions
87
89
 
88
- Files under an `actionsDir` (or a page's colocated `actions` export) register callable server functions:
90
+ Files under an `actionsDir` register callable server functions. Each named export (or an `export const actions = { ... }` map) becomes a function callable from a client island:
89
91
 
90
92
  ```ts
91
- // src/pages/contact/_actions.ts
93
+ // src/actions/contact.ts
92
94
  export async function submitContact(data: { email: string; message: string }) {
93
95
  // runs on the server, callable from a client island
94
96
  }
97
+
98
+ export const actions = {
99
+ ping: async () => ({ pong: true }),
100
+ };
95
101
  ```
96
102
 
97
- `registerServerFunctions`, `generateServerFunctionClient`, and `getServerFunctionHandler` are the lower-level primitives the router wires up automatically — most apps won't call these directly.
103
+ `registerServerFunctions`, `generateServerFunctionClient`, and `getServerFunctionHandler` are the lower-level primitives the router wires up automatically. Most apps won't call these directly.
98
104
 
99
105
  ## Islands (selective hydration)
100
106
 
@@ -103,7 +109,7 @@ Wrap any interactive piece of a static/server-rendered page in `<Island>` to shi
103
109
  ```tsx
104
110
  import { Island } from "@thexjs/core";
105
111
 
106
- <Island name="like-button" client="visible">
112
+ <Island name="LikeButton" client="visible">
107
113
  <LikeButton />
108
114
  </Island>
109
115
  ```
@@ -123,17 +129,17 @@ const html = renderMarkdown(posts[0].body);
123
129
 
124
130
  ## Data layer
125
131
 
126
- Thin, typed wrappers over Bun's built-in SQLite and Postgres clients, plus a minimal migration runner:
132
+ Thin, typed wrappers over Bun's built-in SQLite and Postgres clients, plus a minimal migration runner. Import from the `@thexjs/core/data` subpath:
127
133
 
128
134
  ```ts
129
- import { connectSQLite, runSQLiteMigrations } from "@thexjs/core";
135
+ import { connectSQLite, runSQLiteMigrations } from "@thexjs/core/data";
130
136
 
131
- const db = connectSQLite({ filename: "./data/dev.db" });
137
+ const db = connectSQLite({ path: "./data/dev.db" });
132
138
  await runSQLiteMigrations(db, "./data/migrations");
133
139
  ```
134
140
 
135
141
  ```ts
136
- import { connectPostgres, runPostgresMigrations } from "@thexjs/core";
142
+ import { connectPostgres, runPostgresMigrations } from "@thexjs/core/data";
137
143
 
138
144
  const sql = connectPostgres({ url: process.env.DATABASE_URL! });
139
145
  await runPostgresMigrations(sql, "./data/migrations");
@@ -143,12 +149,14 @@ await runPostgresMigrations(sql, "./data/migrations");
143
149
 
144
150
  ```ts
145
151
  // src/pages/dashboard/_middleware.ts
146
- import type { MiddlewareFn } from "@thexjs/core";
152
+ import type { MiddlewareContext, MiddlewareNext } from "@thexjs/core";
147
153
 
148
- export const middleware: MiddlewareFn = async (ctx, next) => {
149
- if (!ctx.session) return new Response("Unauthorized", { status: 401 });
154
+ export async function middleware(ctx: MiddlewareContext, next: MiddlewareNext) {
155
+ if (!ctx.request.headers.get("authorization")) {
156
+ return new Response("Unauthorized", { status: 401 });
157
+ }
150
158
  return next();
151
- };
159
+ }
152
160
  ```
153
161
 
154
162
  `composeMiddleware` chains multiple middleware functions together; `findMiddlewareChain` resolves which ones apply to a given route based on directory nesting.
@@ -170,7 +178,7 @@ await build({ pagesDir: "./src/pages", outDir: "./.x" });
170
178
 
171
179
  ## Deployment note
172
180
 
173
- `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.
181
+ `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.
174
182
 
175
183
  ## Enterprise readiness: security & observability
176
184
 
@@ -205,7 +213,7 @@ const app = createApp({
205
213
  });
206
214
  ```
207
215
 
208
- Only variables prefixed `THEXJS_PUBLIC_` may reach the browser — `@thexjs/env`'s `createEnv` defaults `clientPrefix` to that, and the build step throws an `EnvLeakageError` if any client bundle references a server-only `process.env`/`Bun.env`/`import.meta.env` variable, so a secret like `STRIPE_SECRET_KEY` can never round-trip into shipped JS.
216
+ Only variables prefixed `THEXJS_PUBLIC_` may reach the browser. `@thexjs/env`'s `createEnv` defaults `clientPrefix` to that, and the build step throws an `EnvLeakageError` if any client bundle references a server-only `process.env`/`Bun.env`/`import.meta.env` variable, so a secret like `STRIPE_SECRET_KEY` can never round-trip into shipped JS.
209
217
 
210
218
  ## Exports reference
211
219
 
@@ -223,7 +231,7 @@ Only variables prefixed `THEXJS_PUBLIC_` may reach the browser — `@thexjs/env`
223
231
  | `DefaultNotFound`, `renderErrorOverlay`, `CLIENT_NAV_SCRIPT` | Defaults / dev tooling |
224
232
  | `checkCsrf`, `verifyOrigin`, `verifyCsrfToken`, `generateCsrfToken`, `withCsrfCookie`, `CsrfOptions`, `CsrfResult` | CSRF protection |
225
233
  | `buildSecurityHeaders`, `applySecurityHeaders`, `SecurityHeadersOptions` | Security response headers (CSP/HSTS/etc.) |
226
- | `createRateLimiter`, `rateLimitMiddleware`, `RateLimitOptions`, `RateLimitResult` | Rate limiting |
234
+ | `createRateLimiter`, `rateLimitMiddleware`, `RateLimitOptions`, `RateLimitResult`, `RateLimitServer`, `createRedisRateLimitStore` | Rate limiting (per-IP fixed window) |
227
235
  | `findLeakedEnvKeys`, `assertNoEnvLeakage`, `EnvLeakageError`, `PUBLIC_ENV_PREFIX` | Server/client env var isolation |
228
236
  | `logger`, `withRequestLogging`, `Logger`, `LogFields` | Structured JSON logging |
229
237
  | `setErrorReporter`, `getErrorReporter`, `reportException`, `createSentryReporter`, `createOtelReporter`, `combineReporters`, `noopReporter`, `ErrorReporter` | Error reporting (Sentry/OpenTelemetry hook) |
package/dist/data.d.ts ADDED
@@ -0,0 +1,56 @@
1
+ import { Database } from 'bun:sqlite';
2
+
3
+ interface SQLiteOptions {
4
+ path?: string;
5
+ wal?: boolean;
6
+ foreignKeys?: boolean;
7
+ }
8
+ declare function connectSQLite(options?: SQLiteOptions): Database;
9
+
10
+ interface PostgresClient {
11
+ unsafe(query: string): Promise<unknown>;
12
+ (strings: TemplateStringsArray, ...values: unknown[]): Promise<unknown>;
13
+ }
14
+ type PostgresSslMode = "disable" | "prefer" | "require" | "verify-ca" | "verify-full";
15
+ interface PostgresOptions {
16
+ url?: string;
17
+ /** Max connections in the pool. Default: 10. */
18
+ max?: number;
19
+ /**
20
+ * TLS policy. Defaults to `"require"` when NODE_ENV=production and
21
+ * `"disable"` otherwise (so local dev against a plain Postgres keeps
22
+ * working). Pass `false` to force-disable in production, or one of the
23
+ * Postgres SSL modes. `"no-verify"` is an alias for `"require"`.
24
+ */
25
+ ssl?: boolean | "no-verify" | PostgresSslMode;
26
+ /** PEM-encoded CA certificate, used with `verify-ca` / `verify-full`. */
27
+ ca?: string;
28
+ /**
29
+ * How many connection attempts to make (with exponential backoff) before
30
+ * the first query rejects. Handles the case where the database is still
31
+ * coming up when the app boots. Default: 3. Set to 0 to connect without
32
+ * retrying.
33
+ */
34
+ retryAttempts?: number;
35
+ /**
36
+ * Base delay (ms) between connection attempts, doubled each retry.
37
+ * Default: 250.
38
+ */
39
+ retryDelayMs?: number;
40
+ /** Called before each retry attempt (e.g. to log). */
41
+ onRetry?: (attempt: number, error: unknown) => void;
42
+ }
43
+ declare function connectPostgres(options?: PostgresOptions): PostgresClient;
44
+
45
+ interface MigrationResult {
46
+ applied: string[];
47
+ skipped: string[];
48
+ }
49
+ declare function runSQLiteMigrations(db: Database, migrationsDir: string): MigrationResult;
50
+ interface PostgresMigrationResult {
51
+ applied: string[];
52
+ skipped: string[];
53
+ }
54
+ declare function runPostgresMigrations(client: PostgresClient, migrationsDir: string): Promise<PostgresMigrationResult>;
55
+
56
+ export { type MigrationResult, type PostgresMigrationResult, type PostgresOptions, type SQLiteOptions, connectPostgres, connectSQLite, runPostgresMigrations, runSQLiteMigrations };
package/dist/data.js ADDED
@@ -0,0 +1,161 @@
1
+ // src/data/sqlite.ts
2
+ var require2 = import.meta.require;
3
+ function loadBunSQLite() {
4
+ try {
5
+ return require2("bun:sqlite");
6
+ } catch {
7
+ throw new Error(
8
+ "connectSQLite requires the Bun runtime (bun:sqlite). Use connectPostgres on non-Bun runtimes like Vercel."
9
+ );
10
+ }
11
+ }
12
+ function connectSQLite(options) {
13
+ const { Database: DB } = loadBunSQLite();
14
+ const db = new DB(options?.path ?? "data/dev.db");
15
+ if (options?.wal !== false) {
16
+ db.run("PRAGMA journal_mode = WAL");
17
+ }
18
+ if (options?.foreignKeys !== false) {
19
+ db.run("PRAGMA foreign_keys = ON");
20
+ }
21
+ return db;
22
+ }
23
+
24
+ // src/data/postgres.ts
25
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
26
+ async function probeWithRetry(sql, attempts, baseDelay, onRetry) {
27
+ for (let attempt = 1; ; attempt++) {
28
+ try {
29
+ await sql.unsafe("SELECT 1");
30
+ return;
31
+ } catch (error) {
32
+ if (attempt >= attempts) throw error;
33
+ onRetry?.(attempt, error);
34
+ await sleep(baseDelay * 2 ** (attempt - 1));
35
+ }
36
+ }
37
+ }
38
+ function connectPostgres(options = {}) {
39
+ const url = options.url ?? process.env.DATABASE_URL;
40
+ if (!url) {
41
+ throw new Error(
42
+ "DATABASE_URL is required \u2014 set it via options.url or the DATABASE_URL environment variable"
43
+ );
44
+ }
45
+ const isProd = process.env.NODE_ENV === "production";
46
+ let sslMode;
47
+ if (options.ssl === false) {
48
+ sslMode = "disable";
49
+ } else if (options.ssl === true) {
50
+ sslMode = "require";
51
+ } else if (options.ssl === "no-verify") {
52
+ sslMode = "require";
53
+ } else if (typeof options.ssl === "string") {
54
+ sslMode = options.ssl;
55
+ } else {
56
+ sslMode = isProd ? "require" : "disable";
57
+ }
58
+ const connectionUrl = new URL(url);
59
+ if (sslMode !== "disable") {
60
+ connectionUrl.searchParams.set("sslmode", sslMode);
61
+ }
62
+ const client = new Bun.SQL({
63
+ url: connectionUrl,
64
+ max: options.max ?? 10,
65
+ // Providing a CA also turns on certificate verification (Bun escalates a
66
+ // `ca`-bearing tls object to verify-full), so only attach it when a
67
+ // verified mode is in effect.
68
+ ...options.ca && sslMode !== "disable" ? { tls: { ca: options.ca } } : {}
69
+ });
70
+ const attempts = options.retryAttempts ?? 3;
71
+ if (attempts <= 0) {
72
+ return client;
73
+ }
74
+ const sql = client;
75
+ let primed = null;
76
+ const prime = () => {
77
+ primed ??= probeWithRetry(client, attempts, options.retryDelayMs ?? 250, options.onRetry);
78
+ return primed;
79
+ };
80
+ const run = async (work) => {
81
+ await prime();
82
+ return work();
83
+ };
84
+ return new Proxy(sql, {
85
+ get(target, prop, receiver) {
86
+ if (prop === "unsafe") {
87
+ return (query) => run(() => client.unsafe(query));
88
+ }
89
+ const value = Reflect.get(target, prop, receiver);
90
+ return typeof value === "function" ? value.bind(target) : value;
91
+ },
92
+ apply(_target, _thisArg, args) {
93
+ const [strings, ...values] = args;
94
+ return run(() => client(strings, ...values));
95
+ }
96
+ });
97
+ }
98
+
99
+ // src/data/migrate.ts
100
+ import { readFileSync, readdirSync } from "fs";
101
+ import { join } from "path";
102
+ function runSQLiteMigrations(db, migrationsDir) {
103
+ db.run(`CREATE TABLE IF NOT EXISTS _x_migrations (
104
+ name TEXT PRIMARY KEY,
105
+ applied_at TEXT DEFAULT (datetime('now'))
106
+ )`);
107
+ const stmt = db.prepare("SELECT name FROM _x_migrations");
108
+ const applied = new Set(stmt.all().map((r) => r.name));
109
+ let files;
110
+ try {
111
+ files = readdirSync(migrationsDir).filter((f) => f.endsWith(".sql")).sort();
112
+ } catch {
113
+ return { applied: [], skipped: [] };
114
+ }
115
+ const result = { applied: [], skipped: [] };
116
+ for (const file of files) {
117
+ if (applied.has(file)) {
118
+ result.skipped.push(file);
119
+ continue;
120
+ }
121
+ const sql = readFileSync(join(migrationsDir, file), "utf-8");
122
+ db.run(sql);
123
+ db.run("INSERT INTO _x_migrations (name) VALUES (?1)", [file]);
124
+ console.log(`[x] migration applied: ${file}`);
125
+ result.applied.push(file);
126
+ }
127
+ return result;
128
+ }
129
+ async function runPostgresMigrations(client, migrationsDir) {
130
+ await client.unsafe(`CREATE TABLE IF NOT EXISTS _x_migrations (
131
+ name TEXT PRIMARY KEY,
132
+ applied_at TIMESTAMP DEFAULT NOW()
133
+ )`);
134
+ const rows = await client.unsafe("SELECT name FROM _x_migrations");
135
+ const applied = new Set(rows.map((r) => r.name));
136
+ let files;
137
+ try {
138
+ files = readdirSync(migrationsDir).filter((f) => f.endsWith(".sql")).sort();
139
+ } catch {
140
+ return { applied: [], skipped: [] };
141
+ }
142
+ const result = { applied: [], skipped: [] };
143
+ for (const file of files) {
144
+ if (applied.has(file)) {
145
+ result.skipped.push(file);
146
+ continue;
147
+ }
148
+ const raw = readFileSync(join(migrationsDir, file), "utf-8");
149
+ await client.unsafe(raw);
150
+ await client.unsafe(`INSERT INTO _x_migrations (name) VALUES ('${file}')`);
151
+ console.log(`[x] migration applied: ${file}`);
152
+ result.applied.push(file);
153
+ }
154
+ return result;
155
+ }
156
+ export {
157
+ connectPostgres,
158
+ connectSQLite,
159
+ runPostgresMigrations,
160
+ runSQLiteMigrations
161
+ };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import * as react from 'react';
2
- import { ReactNode, AnchorHTMLAttributes } from 'react';
3
- import { Database } from 'bun:sqlite';
2
+ import { ComponentType, ReactNode, AnchorHTMLAttributes } from 'react';
4
3
 
5
4
  interface RouteEntry {
6
5
  filePath: string;
@@ -41,6 +40,47 @@ declare function findMiddlewareChain(routeFilePath: string, middleware: Middlewa
41
40
  declare function generateManifestSource(routes: RouteEntry[]): string;
42
41
  declare function writeManifest(routes: RouteEntry[], routesDir: string): string;
43
42
 
43
+ type RouteMode = "static" | "server";
44
+ interface BuildOptions {
45
+ routesDir?: string;
46
+ pagesDir?: string;
47
+ apiDir?: string;
48
+ layoutsDir?: string;
49
+ actionsDir?: string;
50
+ contentDir?: string;
51
+ outDir?: string;
52
+ /**
53
+ * Absolute path to the project's x.config.ts/js/mjs, if any. When set, the
54
+ * generated production server entry re-imports it at startup and forwards
55
+ * its `security`/`observability` fields into `createApp()` — those fields
56
+ * can hold live values (rate-limit key functions, error reporters, health
57
+ * checks) that can't be serialized into the generated file directly.
58
+ */
59
+ configPath?: string;
60
+ }
61
+ declare function build(options: BuildOptions): Promise<void>;
62
+
63
+ /**
64
+ * Minimal remote-image proxy. Fetches an allow-listed remote image
65
+ * server-side and streams it back from your own origin at /_x/image, so the
66
+ * browser never makes a cross-origin request and CSP img-src can stay
67
+ * 'self'-only. No resizing/optimization — just proxy + cache headers.
68
+ */
69
+ interface ImageProxyOptions {
70
+ /** Hostnames allowed to be proxied, e.g. ["stardance.hackclub.com"]. Required — an empty/missing list disables the route (404). */
71
+ remoteHosts?: string[];
72
+ }
73
+ /** Returns a handler for GET /_x/image?url=<encoded remote url>, or null if the request doesn't match. */
74
+ declare function createImageProxyHandler(options?: ImageProxyOptions): (req: Request) => Promise<Response | null>;
75
+
76
+ interface MiddlewareContext {
77
+ params: Record<string, string>;
78
+ request: Request;
79
+ }
80
+ type MiddlewareNext = () => Promise<Response>;
81
+ type MiddlewareFn = (ctx: MiddlewareContext, next: MiddlewareNext) => Promise<Response>;
82
+ declare function composeMiddleware(fns: MiddlewareFn[], handler: (ctx: MiddlewareContext) => Promise<Response>): MiddlewareFn;
83
+
44
84
  /**
45
85
  * Built-in `/healthz` and `/readyz` endpoints for container orchestrators
46
86
  * (Kubernetes, Docker Swarm, Railway, Fly.io) to probe process health and
@@ -181,19 +221,38 @@ declare function buildSecurityHeaders(options?: SecurityHeadersOptions): Headers
181
221
  declare function applySecurityHeaders(res: Response, options?: SecurityHeadersOptions): Response;
182
222
 
183
223
  /**
184
- * Lightweight in-memory rate limiter. Fixed-window counter keyed by client
185
- * IP by default. Good enough for a single-process Bun deployment or as a
186
- * first line of defense in front of brute-force/DDoS traffic; for multi-instance
187
- * deployments, front this with a shared store (Redis, etc.) via a custom `keyFn`
188
- * and store — this implementation intentionally has no external dependencies.
224
+ * Lightweight fixed-window rate limiter. In-memory by default, keyed by client
225
+ * IP — good enough for a single-process Bun deployment or as a first line of
226
+ * defense in front of brute-force/DDoS traffic. For multi-instance deployments
227
+ * (K8s, multiple replicas) pass a shared `store` (see `createRedisRateLimitStore`)
228
+ * so limits are enforced across processes. This implementation has no external
229
+ * dependencies: the Redis store lazy-imports Bun's built-in `bun:redis` only
230
+ * when it's actually used.
189
231
  */
190
232
  interface RateLimitOptions {
191
233
  /** Max requests allowed per window per key. Default: 60. */
192
234
  limit?: number;
193
235
  /** Window size in milliseconds. Default: 60_000 (1 minute). */
194
236
  windowMs?: number;
195
- /** Derives the rate-limit bucket key from a request. Default: client IP from standard headers. */
196
- keyFn?: (req: Request) => string;
237
+ /**
238
+ * Derives the rate-limit bucket key from a request. Default: the client IP
239
+ * from the underlying socket (Bun `server.requestIP`), falling back to the
240
+ * `x-forwarded-for` / `x-real-ip` headers. `server` is provided when the
241
+ * limiter is wired into `Bun.serve`.
242
+ */
243
+ keyFn?: (req: Request, server?: RateLimitServer) => string;
244
+ /** Optional shared store (e.g. Redis) for multi-instance deployments. */
245
+ store?: RateLimitStore;
246
+ }
247
+ /**
248
+ * The subset of Bun's `Bun.serve` server handle the rate limiter needs to
249
+ * resolve the real client IP from the socket. Passed through from
250
+ * `Bun.serve`'s `fetch(request, server)` second argument.
251
+ */
252
+ interface RateLimitServer {
253
+ requestIP?: (req: Request) => {
254
+ address: string;
255
+ } | null;
197
256
  }
198
257
  interface RateLimitResult {
199
258
  ok: boolean;
@@ -201,21 +260,42 @@ interface RateLimitResult {
201
260
  remaining: number;
202
261
  resetAt: number;
203
262
  }
263
+ /**
264
+ * A shared backend for rate-limit counters. Implementations must atomically
265
+ * increment the counter for `key` (creating a fresh window of `windowMs`
266
+ * when the key is new) and return the new count plus when the window resets.
267
+ */
268
+ interface RateLimitStore {
269
+ incr(key: string, windowMs: number): Promise<{
270
+ count: number;
271
+ resetAt: number;
272
+ }>;
273
+ }
204
274
  interface Bucket {
205
275
  count: number;
206
276
  resetAt: number;
207
277
  }
208
278
  /** Creates an independent rate limiter with its own bucket store. */
209
279
  declare function createRateLimiter(options?: RateLimitOptions): {
210
- check: (req: Request) => RateLimitResult;
280
+ check: (req: Request, server?: RateLimitServer) => Promise<RateLimitResult>;
211
281
  sweep: () => void;
212
282
  buckets: Map<string, Bucket>;
283
+ dispose: () => void;
213
284
  };
214
285
  /**
215
286
  * Convenience middleware-style handler: returns a 429 Response when the
216
287
  * limit is exceeded, or null when the request should proceed.
217
288
  */
218
- declare function rateLimitMiddleware(limiter: ReturnType<typeof createRateLimiter>, req: Request): Response | null;
289
+ declare function rateLimitMiddleware(limiter: ReturnType<typeof createRateLimiter>, req: Request, server?: RateLimitServer): Promise<Response | null>;
290
+ /**
291
+ * Shared rate-limit store backed by Redis, so limits are enforced across
292
+ * multiple server instances. Uses Bun's built-in `bun:redis` (no npm
293
+ * dependency) and connects lazily on first use. Pass the result as
294
+ * `store` in `createRateLimiter`/`security.rateLimit`.
295
+ */
296
+ declare function createRedisRateLimitStore(options?: {
297
+ url?: string;
298
+ }): RateLimitStore;
219
299
 
220
300
  interface RouteProps {
221
301
  params: Record<string, string>;
@@ -234,6 +314,14 @@ interface CreateAppOptions {
234
314
  actionsDir?: string;
235
315
  port?: number;
236
316
  development?: boolean;
317
+ /**
318
+ * Resolved stylesheet <link> href (e.g. "/styles.css"), precomputed by the
319
+ * build. Runtimes that can't check the filesystem at request time (Vercel's
320
+ * Node.js functions) rely on this so server-rendered pages still emit the
321
+ * stylesheet tag. When unset, createApp falls back to a runtime probe of
322
+ * `public/styles.css`.
323
+ */
324
+ stylesheetHref?: string;
237
325
  security?: {
238
326
  /** CSRF protection for /__x/actions/* requests. Origin/Referer verification is always on unless disabled. */
239
327
  csrf?: CsrfOptions;
@@ -250,6 +338,42 @@ interface CreateAppOptions {
250
338
  /** /healthz and /readyz endpoints, served ahead of all other routing. */
251
339
  health?: HealthCheckOptions;
252
340
  };
341
+ /** Remote-image proxy at /_x/image?url=... — see ImageProxyOptions. Unset/empty remoteHosts means the route 404s. */
342
+ images?: ImageProxyOptions;
343
+ /**
344
+ * Pre-resolved routes/actions for runtimes that can't scan the filesystem
345
+ * or dynamically `import()` a `.tsx` file at request time (e.g. Vercel's
346
+ * Node.js functions). When set, `createApp` skips all scanning and dynamic
347
+ * imports and builds its handlers straight from this manifest — exactly
348
+ * the same request pipeline (health, rate limit, revalidation, server
349
+ * actions, static assets, islands, image proxy, routing, 404, security
350
+ * headers) as a normally-scanned app.
351
+ */
352
+ preloaded?: PreloadedAppManifest;
353
+ }
354
+ interface PreloadedRoute {
355
+ /** Route metadata (path, param names, api flag). */
356
+ entry: RouteEntry;
357
+ mode: RouteMode;
358
+ /** ISR revalidate seconds for static-mode pages. */
359
+ revalidate?: number;
360
+ /** The route's module namespace (default, loader, middleware, actions, GET/POST...). */
361
+ module: Record<string, unknown>;
362
+ layoutModules: ComponentType<{
363
+ children: ReactNode;
364
+ }>[];
365
+ middlewareModules: MiddlewareFn[];
366
+ /** Layout source file paths, used as the island-bundle cache key on Bun. */
367
+ layoutFilePaths?: string[];
368
+ /** Pre-resolved island <script> URLs for server-mode pages. When omitted, islands are discovered/bundled at request time (Bun only). */
369
+ islandScripts?: string[];
370
+ }
371
+ interface PreloadedAppManifest {
372
+ routes: PreloadedRoute[];
373
+ notFoundComponent?: ComponentType<RouteProps>;
374
+ notFoundLayout?: ComponentType<{
375
+ children: ReactNode;
376
+ }>;
253
377
  }
254
378
  interface AppServeOptions {
255
379
  routes: Record<string, (req: Request) => Promise<Response> | Response>;
@@ -299,26 +423,6 @@ declare function renderStreamingPage(node: ReactNode, options?: RenderOptions):
299
423
  */
300
424
  declare const CLIENT_NAV_SCRIPT: string;
301
425
 
302
- type RouteMode = "static" | "server";
303
- interface BuildOptions {
304
- routesDir?: string;
305
- pagesDir?: string;
306
- apiDir?: string;
307
- layoutsDir?: string;
308
- actionsDir?: string;
309
- contentDir?: string;
310
- outDir?: string;
311
- /**
312
- * Absolute path to the project's x.config.ts/js/mjs, if any. When set, the
313
- * generated production server entry re-imports it at startup and forwards
314
- * its `security`/`observability` fields into `createApp()` — those fields
315
- * can hold live values (rate-limit key functions, error reporters, health
316
- * checks) that can't be serialized into the generated file directly.
317
- */
318
- configPath?: string;
319
- }
320
- declare function build(options: BuildOptions): Promise<void>;
321
-
322
426
  interface Frontmatter {
323
427
  title?: string;
324
428
  [key: string]: unknown;
@@ -353,7 +457,7 @@ declare function Island({ name, client, children, }: {
353
457
 
354
458
  interface LinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href"> {
355
459
  href: string;
356
- children: ReactNode;
460
+ children?: ReactNode;
357
461
  /** Use client-side navigation instead of a full page load (default: true). */
358
462
  clientNav?: boolean;
359
463
  /** Prefetch the destination on hover/focus (default: true). Requires client nav. */
@@ -365,14 +469,6 @@ interface LinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href"
365
469
  */
366
470
  declare function Link({ href, children, clientNav, prefetch, ...rest }: LinkProps): react.JSX.Element;
367
471
 
368
- interface MiddlewareContext {
369
- params: Record<string, string>;
370
- request: Request;
371
- }
372
- type MiddlewareNext = () => Promise<Response>;
373
- type MiddlewareFn = (ctx: MiddlewareContext, next: MiddlewareNext) => Promise<Response>;
374
- declare function composeMiddleware(fns: MiddlewareFn[], handler: (ctx: MiddlewareContext) => Promise<Response>): MiddlewareFn;
375
-
376
472
  declare function generateServerFunctionClient(routeFilePath: string, fnNames: string[], endpointBase: string): string;
377
473
  declare function resetServerFunctions(): void;
378
474
  declare function registerServerFunctions(routePath: string, paramNames: string[], fns: Record<string, (...args: unknown[]) => Promise<unknown>>): void;
@@ -420,34 +516,9 @@ declare const logger: Logger;
420
516
  /**
421
517
  * Wraps a fetch handler so every request is logged as one structured JSON
422
518
  * line with `timestamp`, `requestId`, `route`, `status`, and `durationMs`.
519
+ * A second argument (Bun.serve's `server` handle) is forwarded untouched so
520
+ * downstream middleware like the rate limiter can resolve the client IP.
423
521
  */
424
- declare function withRequestLogging(handler: (req: Request) => Response | Promise<Response>): (req: Request) => Promise<Response>;
425
-
426
- interface SQLiteOptions {
427
- path?: string;
428
- wal?: boolean;
429
- foreignKeys?: boolean;
430
- }
431
- declare function connectSQLite(options?: SQLiteOptions): Database;
432
-
433
- interface PostgresClient {
434
- unsafe(query: string): Promise<unknown>;
435
- (strings: TemplateStringsArray, ...values: unknown[]): Promise<unknown>;
436
- }
437
- interface PostgresOptions {
438
- url?: string;
439
- }
440
- declare function connectPostgres(options?: PostgresOptions): PostgresClient;
441
-
442
- interface MigrationResult {
443
- applied: string[];
444
- skipped: string[];
445
- }
446
- declare function runSQLiteMigrations(db: Database, migrationsDir: string): MigrationResult;
447
- interface PostgresMigrationResult {
448
- applied: string[];
449
- skipped: string[];
450
- }
451
- declare function runPostgresMigrations(client: PostgresClient, migrationsDir: string): Promise<PostgresMigrationResult>;
522
+ declare function withRequestLogging<Server = unknown>(handler: (req: Request, server?: Server) => Response | Promise<Response>): (req: Request, server?: Server) => Promise<Response>;
452
523
 
453
- export { type BuildOptions, CLIENT_NAV_SCRIPT, type ContentEntry, type CreateAppOptions, type CsrfOptions, type CsrfResult, DefaultNotFound, EnvLeakageError, type ErrorContext, type ErrorReporter, type Frontmatter, type HealthCheck, type HealthCheckOptions, Island, type IslandEntry, type IslandMode, IslandProvider, type LayoutEntry, Link, type LinkProps, type LoaderArgs, type LoaderReturn, type LogFields, type Logger, type MiddlewareContext, type MiddlewareEntry, type MiddlewareFn, type MiddlewareNext, type NotFoundEntry, type OtelTracerLike, PUBLIC_ENV_PREFIX, type RateLimitOptions, type RateLimitResult, type ReadinessResult, type RevalidateOptions, type RouteEntry, type RouteMode, type RouteProps, type SecurityHeadersOptions, type SentryLike, applySecurityHeaders, assertNoEnvLeakage, build, buildSecurityHeaders, checkCsrf, combineReporters, composeMiddleware, connectPostgres, connectSQLite, createApp, createHealthCheckHandler, createOtelReporter, createRateLimiter, createSentryReporter, defineConfig, escapeHtml, findLayoutChain, findLeakedEnvKeys, findMiddlewareChain, generateCsrfToken, generateManifestSource, generateServerFunctionClient, getErrorReporter, getServerFunctionHandler, logger, noopReporter, rateLimitMiddleware, registerServerFunctions, renderErrorOverlay, renderMarkdown, renderPage, renderStaticPage, renderStreamingPage, reportException, resetServerFunctions, runPostgresMigrations, runSQLiteMigrations, scanApiDir, scanContent, scanLayouts, scanLayoutsDir, scanMiddleware, scanNotFound, scanPages, scanRoutes, setErrorReporter, verifyCsrfToken, verifyOrigin, withCsrfCookie, withRequestLogging, writeManifest };
524
+ export { type BuildOptions, CLIENT_NAV_SCRIPT, type ContentEntry, type CreateAppOptions, type CsrfOptions, type CsrfResult, DefaultNotFound, EnvLeakageError, type ErrorContext, type ErrorReporter, type Frontmatter, type HealthCheck, type HealthCheckOptions, type ImageProxyOptions, Island, type IslandEntry, type IslandMode, IslandProvider, type LayoutEntry, Link, type LinkProps, type LoaderArgs, type LoaderReturn, type LogFields, type Logger, type MiddlewareContext, type MiddlewareEntry, type MiddlewareFn, type MiddlewareNext, type NotFoundEntry, type OtelTracerLike, PUBLIC_ENV_PREFIX, type RateLimitOptions, type RateLimitResult, type RateLimitStore, type ReadinessResult, type RevalidateOptions, type RouteEntry, type RouteMode, type RouteProps, type SecurityHeadersOptions, type SentryLike, applySecurityHeaders, assertNoEnvLeakage, build, buildSecurityHeaders, checkCsrf, combineReporters, composeMiddleware, createApp, createHealthCheckHandler, createImageProxyHandler, createOtelReporter, createRateLimiter, createRedisRateLimitStore, createSentryReporter, defineConfig, escapeHtml, findLayoutChain, findLeakedEnvKeys, findMiddlewareChain, generateCsrfToken, generateManifestSource, generateServerFunctionClient, getErrorReporter, getServerFunctionHandler, logger, noopReporter, rateLimitMiddleware, registerServerFunctions, renderErrorOverlay, renderMarkdown, renderPage, renderStaticPage, renderStreamingPage, reportException, resetServerFunctions, scanApiDir, scanContent, scanLayouts, scanLayoutsDir, scanMiddleware, scanNotFound, scanPages, scanRoutes, setErrorReporter, verifyCsrfToken, verifyOrigin, withCsrfCookie, withRequestLogging, writeManifest };