@thexjs/core 0.1.7 → 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/index.d.ts CHANGED
@@ -234,11 +234,26 @@ interface RateLimitOptions {
234
234
  limit?: number;
235
235
  /** Window size in milliseconds. Default: 60_000 (1 minute). */
236
236
  windowMs?: number;
237
- /** Derives the rate-limit bucket key from a request. Default: client IP from standard headers. */
238
- 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;
239
244
  /** Optional shared store (e.g. Redis) for multi-instance deployments. */
240
245
  store?: RateLimitStore;
241
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;
256
+ }
242
257
  interface RateLimitResult {
243
258
  ok: boolean;
244
259
  limit: number;
@@ -262,7 +277,7 @@ interface Bucket {
262
277
  }
263
278
  /** Creates an independent rate limiter with its own bucket store. */
264
279
  declare function createRateLimiter(options?: RateLimitOptions): {
265
- check: (req: Request) => Promise<RateLimitResult>;
280
+ check: (req: Request, server?: RateLimitServer) => Promise<RateLimitResult>;
266
281
  sweep: () => void;
267
282
  buckets: Map<string, Bucket>;
268
283
  dispose: () => void;
@@ -271,7 +286,7 @@ declare function createRateLimiter(options?: RateLimitOptions): {
271
286
  * Convenience middleware-style handler: returns a 429 Response when the
272
287
  * limit is exceeded, or null when the request should proceed.
273
288
  */
274
- declare function rateLimitMiddleware(limiter: ReturnType<typeof createRateLimiter>, req: Request): Promise<Response | null>;
289
+ declare function rateLimitMiddleware(limiter: ReturnType<typeof createRateLimiter>, req: Request, server?: RateLimitServer): Promise<Response | null>;
275
290
  /**
276
291
  * Shared rate-limit store backed by Redis, so limits are enforced across
277
292
  * multiple server instances. Uses Bun's built-in `bun:redis` (no npm
@@ -501,7 +516,9 @@ declare const logger: Logger;
501
516
  /**
502
517
  * Wraps a fetch handler so every request is logged as one structured JSON
503
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.
504
521
  */
505
- declare function withRequestLogging(handler: (req: Request) => Response | Promise<Response>): (req: Request) => Promise<Response>;
522
+ declare function withRequestLogging<Server = unknown>(handler: (req: Request, server?: Server) => Response | Promise<Response>): (req: Request, server?: Server) => Promise<Response>;
506
523
 
507
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 };
package/dist/index.js CHANGED
@@ -1303,12 +1303,12 @@ var logger = {
1303
1303
  error: (message, fields) => write("error", message, fields)
1304
1304
  };
1305
1305
  function withRequestLogging(handler) {
1306
- return async (req) => {
1306
+ return async (req, server) => {
1307
1307
  const start = performance.now();
1308
1308
  const requestId = req.headers.get("x-request-id") ?? crypto.randomUUID();
1309
1309
  const route = new URL(req.url).pathname;
1310
1310
  try {
1311
- const res = await handler(req);
1311
+ const res = await handler(req, server);
1312
1312
  const isStream = res.headers.get("content-type")?.includes("text/event-stream");
1313
1313
  console.log(
1314
1314
  `[x][request] ${req.method} ${route} -> ${res.status}${isStream ? " (stream opened, not closed)" : ""}`
@@ -1371,11 +1371,14 @@ function applySecurityHeaders(res, options = {}) {
1371
1371
  }
1372
1372
 
1373
1373
  // src/security/rate-limit.ts
1374
- function defaultKeyFn(req) {
1375
- const headers = req.headers;
1376
- const forwarded = headers.get("x-forwarded-for");
1374
+ function defaultKeyFn(req, server) {
1375
+ if (server?.requestIP) {
1376
+ const ip = server.requestIP(req);
1377
+ if (ip) return ip.address;
1378
+ }
1379
+ const forwarded = req.headers.get("x-forwarded-for");
1377
1380
  if (forwarded) return forwarded.split(",")[0]?.trim() ?? "unknown";
1378
- return headers.get("x-real-ip") ?? "unknown";
1381
+ return req.headers.get("x-real-ip") ?? "unknown";
1379
1382
  }
1380
1383
  function createRateLimiter(options = {}) {
1381
1384
  const limit = options.limit ?? 60;
@@ -1383,8 +1386,8 @@ function createRateLimiter(options = {}) {
1383
1386
  const keyFn = options.keyFn ?? defaultKeyFn;
1384
1387
  const store = options.store;
1385
1388
  const buckets = /* @__PURE__ */ new Map();
1386
- async function check(req) {
1387
- const key = keyFn(req);
1389
+ async function check(req, server) {
1390
+ const key = keyFn(req, server);
1388
1391
  if (store) {
1389
1392
  const { count, resetAt } = await store.incr(key, windowMs);
1390
1393
  return { ok: count <= limit, limit, remaining: Math.max(0, limit - count), resetAt };
@@ -1409,13 +1412,14 @@ function createRateLimiter(options = {}) {
1409
1412
  timer.unref?.();
1410
1413
  return { check, sweep, buckets, dispose: () => clearInterval(timer) };
1411
1414
  }
1412
- async function rateLimitMiddleware(limiter, req) {
1413
- const result = await limiter.check(req);
1415
+ async function rateLimitMiddleware(limiter, req, server) {
1416
+ const result = await limiter.check(req, server);
1414
1417
  if (result.ok) return null;
1415
1418
  const retryAfterSeconds = Math.max(1, Math.ceil((result.resetAt - Date.now()) / 1e3));
1416
1419
  return new Response("Too Many Requests", {
1417
1420
  status: 429,
1418
1421
  headers: {
1422
+ "Content-Type": "text/plain; charset=utf-8",
1419
1423
  "Retry-After": String(retryAfterSeconds),
1420
1424
  "X-RateLimit-Limit": String(result.limit),
1421
1425
  "X-RateLimit-Remaining": String(result.remaining)
@@ -1989,12 +1993,12 @@ async function createApp(options) {
1989
1993
  } catch {
1990
1994
  console.warn("[x] file watching not available on this platform");
1991
1995
  }
1992
- const devFetchInner = async (req) => {
1996
+ const devFetchInner = async (req, server) => {
1993
1997
  const url = new URL(req.url).pathname;
1994
1998
  const healthResult = await healthHandler(req);
1995
1999
  if (healthResult !== null) return healthResult;
1996
2000
  if (rateLimiter) {
1997
- const limited = await rateLimitMiddleware(rateLimiter, req);
2001
+ const limited = await rateLimitMiddleware(rateLimiter, req, server);
1998
2002
  if (limited !== null) return limited;
1999
2003
  }
2000
2004
  if (url === "/__x/reload") {
@@ -2055,7 +2059,7 @@ data: ${data}
2055
2059
  }
2056
2060
  return renderNotFound(req);
2057
2061
  };
2058
- const devFetchHardened = async (req) => withResponseHardening(await devFetchInner(req));
2062
+ const devFetchHardened = async (req, server) => withResponseHardening(await devFetchInner(req, server));
2059
2063
  const devFetch = loggingEnabled ? withRequestLogging(devFetchHardened) : devFetchHardened;
2060
2064
  return {
2061
2065
  routes: {},
@@ -2064,12 +2068,12 @@ data: ${data}
2064
2068
  fetch: devFetch
2065
2069
  };
2066
2070
  }
2067
- const prodFetchInner = async (req) => {
2071
+ const prodFetchInner = async (req, server) => {
2068
2072
  const url = new URL(req.url).pathname;
2069
2073
  const healthResult = await healthHandler(req);
2070
2074
  if (healthResult !== null) return healthResult;
2071
2075
  if (rateLimiter) {
2072
- const limited = await rateLimitMiddleware(rateLimiter, req);
2076
+ const limited = await rateLimitMiddleware(rateLimiter, req, server);
2073
2077
  if (limited !== null) return limited;
2074
2078
  }
2075
2079
  const revalidationResult = await handleRevalidation(req);
@@ -2095,7 +2099,7 @@ data: ${data}
2095
2099
  }
2096
2100
  return renderNotFound(req);
2097
2101
  };
2098
- const prodFetchHardened = async (req) => withResponseHardening(await prodFetchInner(req));
2102
+ const prodFetchHardened = async (req, server) => withResponseHardening(await prodFetchInner(req, server));
2099
2103
  const prodFetch = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
2100
2104
  return {
2101
2105
  routes: {},
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thexjs/core",
3
- "version": "0.1.7",
3
+ "version": "1.0.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",