@thexjs/core 0.1.2 → 0.1.4
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 +42 -0
- package/dist/index.d.ts +265 -4
- package/dist/index.js +562 -121
- package/package.json +3 -7
package/README.md
CHANGED
|
@@ -172,6 +172,41 @@ await build({ pagesDir: "./src/pages", outDir: "./.x" });
|
|
|
172
172
|
|
|
173
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.
|
|
174
174
|
|
|
175
|
+
## Enterprise readiness: security & observability
|
|
176
|
+
|
|
177
|
+
`createApp` accepts optional `security` and `observability` config, all on by sane defaults:
|
|
178
|
+
|
|
179
|
+
```ts
|
|
180
|
+
import { createApp, createSentryReporter } from "@thexjs/core";
|
|
181
|
+
|
|
182
|
+
const app = createApp({
|
|
183
|
+
pagesDir: "./src/pages",
|
|
184
|
+
actionsDir: "./src/actions",
|
|
185
|
+
security: {
|
|
186
|
+
// Origin/Referer verification on /__x/actions/* is always on; add explicit
|
|
187
|
+
// cross-subdomain origins here, or requireToken for double-submit CSRF cookies.
|
|
188
|
+
csrf: { allowedOrigins: ["https://app.example.com"] },
|
|
189
|
+
// CSP, HSTS, X-Frame-Options, etc. Pass `false` to disable entirely, or
|
|
190
|
+
// override individual fields (see SecurityHeadersOptions).
|
|
191
|
+
headers: { contentSecurityPolicy: "default-src 'self'" },
|
|
192
|
+
// In-memory fixed-window limiter, keyed by client IP by default.
|
|
193
|
+
rateLimit: { limit: 100, windowMs: 60_000 },
|
|
194
|
+
},
|
|
195
|
+
observability: {
|
|
196
|
+
// Structured JSON request logs (timestamp, requestId, route, status, durationMs). Default: true.
|
|
197
|
+
logging: true,
|
|
198
|
+
// Forward SSR/action/API exceptions to Sentry, OpenTelemetry, or both — see
|
|
199
|
+
// createSentryReporter / createOtelReporter / combineReporters.
|
|
200
|
+
errorReporter: createSentryReporter(Sentry),
|
|
201
|
+
// /healthz (liveness) and /readyz (readiness) are always served, ahead of all
|
|
202
|
+
// other routing. Add named checks (e.g. a DB ping) for /readyz.
|
|
203
|
+
health: { checks: { database: () => db.ping() } },
|
|
204
|
+
},
|
|
205
|
+
});
|
|
206
|
+
```
|
|
207
|
+
|
|
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.
|
|
209
|
+
|
|
175
210
|
## Exports reference
|
|
176
211
|
|
|
177
212
|
| Export | Purpose |
|
|
@@ -186,6 +221,13 @@ await build({ pagesDir: "./src/pages", outDir: "./.x" });
|
|
|
186
221
|
| `registerServerFunctions`, `generateServerFunctionClient`, `getServerFunctionHandler`, `resetServerFunctions` | Server functions/actions internals |
|
|
187
222
|
| `connectSQLite`, `connectPostgres`, `runSQLiteMigrations`, `runPostgresMigrations` | Data layer |
|
|
188
223
|
| `DefaultNotFound`, `renderErrorOverlay`, `CLIENT_NAV_SCRIPT` | Defaults / dev tooling |
|
|
224
|
+
| `checkCsrf`, `verifyOrigin`, `verifyCsrfToken`, `generateCsrfToken`, `withCsrfCookie`, `CsrfOptions`, `CsrfResult` | CSRF protection |
|
|
225
|
+
| `buildSecurityHeaders`, `applySecurityHeaders`, `SecurityHeadersOptions` | Security response headers (CSP/HSTS/etc.) |
|
|
226
|
+
| `createRateLimiter`, `rateLimitMiddleware`, `RateLimitOptions`, `RateLimitResult` | Rate limiting |
|
|
227
|
+
| `findLeakedEnvKeys`, `assertNoEnvLeakage`, `EnvLeakageError`, `PUBLIC_ENV_PREFIX` | Server/client env var isolation |
|
|
228
|
+
| `logger`, `withRequestLogging`, `Logger`, `LogFields` | Structured JSON logging |
|
|
229
|
+
| `setErrorReporter`, `getErrorReporter`, `reportException`, `createSentryReporter`, `createOtelReporter`, `combineReporters`, `noopReporter`, `ErrorReporter` | Error reporting (Sentry/OpenTelemetry hook) |
|
|
230
|
+
| `createHealthCheckHandler`, `HealthCheckOptions`, `HealthCheck`, `ReadinessResult` | `/healthz` and `/readyz` |
|
|
189
231
|
|
|
190
232
|
## License
|
|
191
233
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
|
-
import { ReactNode } from 'react';
|
|
2
|
+
import { ReactNode, AnchorHTMLAttributes } from 'react';
|
|
3
3
|
import { Database } from 'bun:sqlite';
|
|
4
4
|
|
|
5
5
|
interface RouteEntry {
|
|
@@ -41,6 +41,182 @@ declare function findMiddlewareChain(routeFilePath: string, middleware: Middlewa
|
|
|
41
41
|
declare function generateManifestSource(routes: RouteEntry[]): string;
|
|
42
42
|
declare function writeManifest(routes: RouteEntry[], routesDir: string): string;
|
|
43
43
|
|
|
44
|
+
/**
|
|
45
|
+
* Built-in `/healthz` and `/readyz` endpoints for container orchestrators
|
|
46
|
+
* (Kubernetes, Docker Swarm, Railway, Fly.io) to probe process health and
|
|
47
|
+
* downstream readiness (e.g. database connectivity) before routing traffic.
|
|
48
|
+
*/
|
|
49
|
+
type HealthCheck = () => Promise<boolean> | boolean;
|
|
50
|
+
interface HealthCheckOptions {
|
|
51
|
+
/** Named readiness checks, e.g. { database: () => pingDb() }. All must pass for /readyz to return 200. */
|
|
52
|
+
checks?: Record<string, HealthCheck>;
|
|
53
|
+
}
|
|
54
|
+
interface ReadinessResult {
|
|
55
|
+
status: "ok" | "error";
|
|
56
|
+
checks: Record<string, "ok" | "error">;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Returns a request handler that answers `/healthz` (liveness — the Bun
|
|
60
|
+
* process is up and serving) and `/readyz` (readiness — all configured
|
|
61
|
+
* checks pass, e.g. DB connectivity). Returns null for any other path so it
|
|
62
|
+
* can be composed ahead of normal routing.
|
|
63
|
+
*/
|
|
64
|
+
declare function createHealthCheckHandler(options?: HealthCheckOptions): (req: Request) => Promise<Response | null>;
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Plugin hook for capturing unhandled exceptions during SSR and server
|
|
68
|
+
* action execution, and exporting them to an APM provider. `@thexjs/core`
|
|
69
|
+
* has no hard dependency on Sentry or OpenTelemetry — apps opt in by
|
|
70
|
+
* installing the relevant package and constructing a reporter; everything
|
|
71
|
+
* here degrades to a no-op if nothing is configured.
|
|
72
|
+
*/
|
|
73
|
+
interface ErrorContext {
|
|
74
|
+
route?: string;
|
|
75
|
+
requestId?: string;
|
|
76
|
+
phase: "ssr" | "action" | "api" | "loader";
|
|
77
|
+
}
|
|
78
|
+
interface ErrorReporter {
|
|
79
|
+
captureException(error: unknown, context: ErrorContext): void;
|
|
80
|
+
/** Optional: flush buffered events, e.g. on graceful shutdown. */
|
|
81
|
+
flush?(): Promise<void>;
|
|
82
|
+
}
|
|
83
|
+
/** No-op reporter used when no APM integration is configured. */
|
|
84
|
+
declare const noopReporter: ErrorReporter;
|
|
85
|
+
declare function setErrorReporter(reporter: ErrorReporter): void;
|
|
86
|
+
declare function getErrorReporter(): ErrorReporter;
|
|
87
|
+
declare function reportException(error: unknown, context: ErrorContext): void;
|
|
88
|
+
/**
|
|
89
|
+
* Minimal shape of the Sentry Node/Bun SDK surface this integration needs.
|
|
90
|
+
* Avoids a hard dependency on `@sentry/*` — pass in the SDK's `Sentry` object
|
|
91
|
+
* after calling `Sentry.init(...)` yourself.
|
|
92
|
+
*/
|
|
93
|
+
interface SentryLike {
|
|
94
|
+
captureException(error: unknown, hint?: {
|
|
95
|
+
extra?: Record<string, unknown>;
|
|
96
|
+
}): string;
|
|
97
|
+
flush?(timeoutMs?: number): Promise<boolean>;
|
|
98
|
+
}
|
|
99
|
+
declare function createSentryReporter(sentry: SentryLike): ErrorReporter;
|
|
100
|
+
/**
|
|
101
|
+
* Minimal shape of an OpenTelemetry tracer's span-recording surface this
|
|
102
|
+
* integration needs. Pass in a tracer obtained from your own OTel SDK setup
|
|
103
|
+
* (`trace.getTracer(...)`) — `@thexjs/core` never initializes OTel itself.
|
|
104
|
+
*/
|
|
105
|
+
interface OtelSpanLike {
|
|
106
|
+
recordException(error: unknown): void;
|
|
107
|
+
setStatus(status: {
|
|
108
|
+
code: number;
|
|
109
|
+
message?: string;
|
|
110
|
+
}): void;
|
|
111
|
+
end(): void;
|
|
112
|
+
}
|
|
113
|
+
interface OtelTracerLike {
|
|
114
|
+
startSpan(name: string): OtelSpanLike;
|
|
115
|
+
}
|
|
116
|
+
declare function createOtelReporter(tracer: OtelTracerLike): ErrorReporter;
|
|
117
|
+
/** Combines multiple reporters — useful for sending to Sentry and OTel at once. */
|
|
118
|
+
declare function combineReporters(...reporters: ErrorReporter[]): ErrorReporter;
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* CSRF protection for server actions (`/__x/actions/*`) and other mutating
|
|
122
|
+
* endpoints. Two independent checks are provided and both run by default:
|
|
123
|
+
*
|
|
124
|
+
* 1. Origin/Referer verification — rejects cross-site `POST` requests whose
|
|
125
|
+
* `Origin` (or, failing that, `Referer`) header doesn't match one of the
|
|
126
|
+
* app's own origins. This alone stops the vast majority of CSRF attempts
|
|
127
|
+
* from a browser, with zero setup required.
|
|
128
|
+
* 2. Double-submit CSRF token — for apps that want defense in depth, a
|
|
129
|
+
* random token is issued in a cookie and must be echoed back in the
|
|
130
|
+
* `x-csrf-token` request header on mutating requests.
|
|
131
|
+
*/
|
|
132
|
+
interface CsrfOptions {
|
|
133
|
+
/** Origins considered same-site, e.g. ["https://example.com"]. */
|
|
134
|
+
allowedOrigins?: string[];
|
|
135
|
+
/** Require the double-submit token header in addition to origin checks. Default: false. */
|
|
136
|
+
requireToken?: boolean;
|
|
137
|
+
/** Skip CSRF checks entirely. Only use for local tooling/tests. Default: false. */
|
|
138
|
+
disabled?: boolean;
|
|
139
|
+
}
|
|
140
|
+
interface CsrfResult {
|
|
141
|
+
ok: boolean;
|
|
142
|
+
reason?: string;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Verifies the Origin/Referer of a mutating request against the app's own
|
|
146
|
+
* origin plus any explicitly allowed origins. Requests with no Origin or
|
|
147
|
+
* Referer header at all (same-origin requests from older browsers, curl,
|
|
148
|
+
* server-to-server calls with an explicit bypass) are rejected unless the
|
|
149
|
+
* method is safe.
|
|
150
|
+
*/
|
|
151
|
+
declare function verifyOrigin(req: Request, allowedOrigins?: string[]): CsrfResult;
|
|
152
|
+
declare function generateCsrfToken(): string;
|
|
153
|
+
/** Double-submit check: the cookie value and the request header must match and be non-empty. */
|
|
154
|
+
declare function verifyCsrfToken(req: Request): CsrfResult;
|
|
155
|
+
/** Sets the double-submit CSRF cookie on a response if it isn't already present on the request. */
|
|
156
|
+
declare function withCsrfCookie(req: Request, res: Response): Response;
|
|
157
|
+
/** Runs the configured CSRF checks against a request. Returns ok:true when disabled. */
|
|
158
|
+
declare function checkCsrf(req: Request, options?: CsrfOptions): CsrfResult;
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Security headers helper. Applies sane, overridable defaults for
|
|
162
|
+
* Content-Security-Policy, Strict-Transport-Security and X-Frame-Options
|
|
163
|
+
* (plus a couple of low-risk extras) to every response.
|
|
164
|
+
*/
|
|
165
|
+
interface SecurityHeadersOptions {
|
|
166
|
+
/** Full CSP value, or false to disable. Default: a conservative same-origin policy. */
|
|
167
|
+
contentSecurityPolicy?: string | false;
|
|
168
|
+
/** HSTS max-age in seconds, or false to disable. Default: 15552000 (180 days). */
|
|
169
|
+
hstsMaxAge?: number | false;
|
|
170
|
+
/** Include subdomains in HSTS. Default: true. */
|
|
171
|
+
hstsIncludeSubDomains?: boolean;
|
|
172
|
+
/** X-Frame-Options value, or false to disable. Default: "DENY". */
|
|
173
|
+
frameOptions?: string | false;
|
|
174
|
+
/** X-Content-Type-Options. Default: "nosniff". Set false to disable. */
|
|
175
|
+
contentTypeOptions?: string | false;
|
|
176
|
+
/** Referrer-Policy. Default: "strict-origin-when-cross-origin". Set false to disable. */
|
|
177
|
+
referrerPolicy?: string | false;
|
|
178
|
+
}
|
|
179
|
+
declare function buildSecurityHeaders(options?: SecurityHeadersOptions): Headers;
|
|
180
|
+
/** Returns a new Response with security headers merged onto the original response's headers. */
|
|
181
|
+
declare function applySecurityHeaders(res: Response, options?: SecurityHeadersOptions): Response;
|
|
182
|
+
|
|
183
|
+
/**
|
|
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.
|
|
189
|
+
*/
|
|
190
|
+
interface RateLimitOptions {
|
|
191
|
+
/** Max requests allowed per window per key. Default: 60. */
|
|
192
|
+
limit?: number;
|
|
193
|
+
/** Window size in milliseconds. Default: 60_000 (1 minute). */
|
|
194
|
+
windowMs?: number;
|
|
195
|
+
/** Derives the rate-limit bucket key from a request. Default: client IP from standard headers. */
|
|
196
|
+
keyFn?: (req: Request) => string;
|
|
197
|
+
}
|
|
198
|
+
interface RateLimitResult {
|
|
199
|
+
ok: boolean;
|
|
200
|
+
limit: number;
|
|
201
|
+
remaining: number;
|
|
202
|
+
resetAt: number;
|
|
203
|
+
}
|
|
204
|
+
interface Bucket {
|
|
205
|
+
count: number;
|
|
206
|
+
resetAt: number;
|
|
207
|
+
}
|
|
208
|
+
/** Creates an independent rate limiter with its own bucket store. */
|
|
209
|
+
declare function createRateLimiter(options?: RateLimitOptions): {
|
|
210
|
+
check: (req: Request) => RateLimitResult;
|
|
211
|
+
sweep: () => void;
|
|
212
|
+
buckets: Map<string, Bucket>;
|
|
213
|
+
};
|
|
214
|
+
/**
|
|
215
|
+
* Convenience middleware-style handler: returns a 429 Response when the
|
|
216
|
+
* limit is exceeded, or null when the request should proceed.
|
|
217
|
+
*/
|
|
218
|
+
declare function rateLimitMiddleware(limiter: ReturnType<typeof createRateLimiter>, req: Request): Response | null;
|
|
219
|
+
|
|
44
220
|
interface RouteProps {
|
|
45
221
|
params: Record<string, string>;
|
|
46
222
|
loaderData?: Record<string, unknown>;
|
|
@@ -58,6 +234,22 @@ interface CreateAppOptions {
|
|
|
58
234
|
actionsDir?: string;
|
|
59
235
|
port?: number;
|
|
60
236
|
development?: boolean;
|
|
237
|
+
security?: {
|
|
238
|
+
/** CSRF protection for /__x/actions/* requests. Origin/Referer verification is always on unless disabled. */
|
|
239
|
+
csrf?: CsrfOptions;
|
|
240
|
+
/** Security response headers (CSP, HSTS, X-Frame-Options, ...). Pass false to disable entirely. */
|
|
241
|
+
headers?: SecurityHeadersOptions | false;
|
|
242
|
+
/** Rate limiting applied ahead of all routing. Pass false to disable entirely. */
|
|
243
|
+
rateLimit?: RateLimitOptions | false;
|
|
244
|
+
};
|
|
245
|
+
observability?: {
|
|
246
|
+
/** Structured JSON request logging. Default: true. */
|
|
247
|
+
logging?: boolean;
|
|
248
|
+
/** Plugin hook for exceptions during SSR/actions/API — see createSentryReporter/createOtelReporter. */
|
|
249
|
+
errorReporter?: ErrorReporter;
|
|
250
|
+
/** /healthz and /readyz endpoints, served ahead of all other routing. */
|
|
251
|
+
health?: HealthCheckOptions;
|
|
252
|
+
};
|
|
61
253
|
}
|
|
62
254
|
interface AppServeOptions {
|
|
63
255
|
routes: Record<string, (req: Request) => Promise<Response> | Response>;
|
|
@@ -100,8 +292,12 @@ declare function renderStreamingPage(node: ReactNode, options?: RenderOptions):
|
|
|
100
292
|
* Intercepts same-origin <a> clicks, fetches the destination page, and swaps
|
|
101
293
|
* the #root element's content in place. Includes hover-prefetch and popstate
|
|
102
294
|
* (back/forward) support.
|
|
295
|
+
*
|
|
296
|
+
* Opt-out attributes on <a> / <Link />:
|
|
297
|
+
* - data-no-nav — skip client navigation (full page load)
|
|
298
|
+
* - data-no-prefetch — skip hover prefetch (navigation still works)
|
|
103
299
|
*/
|
|
104
|
-
declare const CLIENT_NAV_SCRIPT
|
|
300
|
+
declare const CLIENT_NAV_SCRIPT: string;
|
|
105
301
|
|
|
106
302
|
type RouteMode = "static" | "server";
|
|
107
303
|
interface BuildOptions {
|
|
@@ -112,6 +308,14 @@ interface BuildOptions {
|
|
|
112
308
|
actionsDir?: string;
|
|
113
309
|
contentDir?: string;
|
|
114
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;
|
|
115
319
|
}
|
|
116
320
|
declare function build(options: BuildOptions): Promise<void>;
|
|
117
321
|
|
|
@@ -147,6 +351,20 @@ declare function Island({ name, client, children, }: {
|
|
|
147
351
|
children: ReactNode;
|
|
148
352
|
}): react.JSX.Element;
|
|
149
353
|
|
|
354
|
+
interface LinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href"> {
|
|
355
|
+
href: string;
|
|
356
|
+
children: ReactNode;
|
|
357
|
+
/** Use client-side navigation instead of a full page load (default: true). */
|
|
358
|
+
clientNav?: boolean;
|
|
359
|
+
/** Prefetch the destination on hover/focus (default: true). Requires client nav. */
|
|
360
|
+
prefetch?: boolean;
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* Framework `<Link />` — renders an anchor wired for the inline client nav script
|
|
364
|
+
* (SPA transitions + hover prefetch). Opt out with `clientNav={false}` or `prefetch={false}`.
|
|
365
|
+
*/
|
|
366
|
+
declare function Link({ href, children, clientNav, prefetch, ...rest }: LinkProps): react.JSX.Element;
|
|
367
|
+
|
|
150
368
|
interface MiddlewareContext {
|
|
151
369
|
params: Record<string, string>;
|
|
152
370
|
request: Request;
|
|
@@ -158,10 +376,53 @@ declare function composeMiddleware(fns: MiddlewareFn[], handler: (ctx: Middlewar
|
|
|
158
376
|
declare function generateServerFunctionClient(routeFilePath: string, fnNames: string[], endpointBase: string): string;
|
|
159
377
|
declare function resetServerFunctions(): void;
|
|
160
378
|
declare function registerServerFunctions(routePath: string, paramNames: string[], fns: Record<string, (...args: unknown[]) => Promise<unknown>>): void;
|
|
161
|
-
declare function getServerFunctionHandler(): (req: Request) => Promise<Response | null>;
|
|
379
|
+
declare function getServerFunctionHandler(csrfOptions?: CsrfOptions): (req: Request) => Promise<Response | null>;
|
|
162
380
|
|
|
163
381
|
declare function renderErrorOverlay(error: unknown): string;
|
|
164
382
|
|
|
383
|
+
/**
|
|
384
|
+
* Compiler boundary between server-only environment variables and the
|
|
385
|
+
* client bundle. Convention: only variables prefixed with `THEXJS_PUBLIC_`
|
|
386
|
+
* may ever reach browser code. Anything else read via `process.env.*`,
|
|
387
|
+
* `Bun.env.*`, or `import.meta.env.*` inside a file that ends up in a client
|
|
388
|
+
* bundle is a build error, not a warning — secrets like `STRIPE_SECRET_KEY`
|
|
389
|
+
* or `DATABASE_URL` must never round-trip through the bundler into
|
|
390
|
+
* browser-shipped JS.
|
|
391
|
+
*/
|
|
392
|
+
declare const PUBLIC_ENV_PREFIX = "THEXJS_PUBLIC_";
|
|
393
|
+
/**
|
|
394
|
+
* Scans bundled JS/TS source for references to environment variables that
|
|
395
|
+
* are not public (`THEXJS_PUBLIC_`-prefixed). Returns the offending variable
|
|
396
|
+
* names, deduplicated. An empty array means the code is clean.
|
|
397
|
+
*/
|
|
398
|
+
declare function findLeakedEnvKeys(code: string): string[];
|
|
399
|
+
declare class EnvLeakageError extends Error {
|
|
400
|
+
readonly file: string;
|
|
401
|
+
readonly keys: string[];
|
|
402
|
+
constructor(file: string, keys: string[]);
|
|
403
|
+
}
|
|
404
|
+
/** Throws EnvLeakageError if the given bundle source references non-public env vars. */
|
|
405
|
+
declare function assertNoEnvLeakage(code: string, file: string): void;
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* Structured JSON logging. Replaces ad-hoc `console.log` with one JSON
|
|
409
|
+
* object per line — easy to ingest into Datadog, Grafana Loki, Kibana, etc.
|
|
410
|
+
*/
|
|
411
|
+
interface LogFields {
|
|
412
|
+
[key: string]: unknown;
|
|
413
|
+
}
|
|
414
|
+
interface Logger {
|
|
415
|
+
info(message: string, fields?: LogFields): void;
|
|
416
|
+
warn(message: string, fields?: LogFields): void;
|
|
417
|
+
error(message: string, fields?: LogFields): void;
|
|
418
|
+
}
|
|
419
|
+
declare const logger: Logger;
|
|
420
|
+
/**
|
|
421
|
+
* Wraps a fetch handler so every request is logged as one structured JSON
|
|
422
|
+
* line with `timestamp`, `requestId`, `route`, `status`, and `durationMs`.
|
|
423
|
+
*/
|
|
424
|
+
declare function withRequestLogging(handler: (req: Request) => Response | Promise<Response>): (req: Request) => Promise<Response>;
|
|
425
|
+
|
|
165
426
|
interface SQLiteOptions {
|
|
166
427
|
path?: string;
|
|
167
428
|
wal?: boolean;
|
|
@@ -189,4 +450,4 @@ interface PostgresMigrationResult {
|
|
|
189
450
|
}
|
|
190
451
|
declare function runPostgresMigrations(client: PostgresClient, migrationsDir: string): Promise<PostgresMigrationResult>;
|
|
191
452
|
|
|
192
|
-
export { type BuildOptions, CLIENT_NAV_SCRIPT, type ContentEntry, type CreateAppOptions, DefaultNotFound, type Frontmatter, Island, type IslandEntry, type IslandMode, IslandProvider, type LayoutEntry, type LoaderArgs, type LoaderReturn, type MiddlewareContext, type MiddlewareEntry, type MiddlewareFn, type MiddlewareNext, type NotFoundEntry, type RevalidateOptions, type RouteEntry, type RouteMode, type RouteProps, build, composeMiddleware, connectPostgres, connectSQLite, createApp, defineConfig, escapeHtml, findLayoutChain, findMiddlewareChain, generateManifestSource, generateServerFunctionClient, getServerFunctionHandler, registerServerFunctions, renderErrorOverlay, renderMarkdown, renderPage, renderStaticPage, renderStreamingPage, resetServerFunctions, runPostgresMigrations, runSQLiteMigrations, scanApiDir, scanContent, scanLayouts, scanLayoutsDir, scanMiddleware, scanNotFound, scanPages, scanRoutes, writeManifest };
|
|
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 };
|
package/dist/index.js
CHANGED
|
@@ -234,111 +234,119 @@ function DefaultNotFound(_props) {
|
|
|
234
234
|
import { renderToReadableStream, renderToStaticMarkup, renderToString } from "react-dom/server";
|
|
235
235
|
|
|
236
236
|
// src/client-nav.ts
|
|
237
|
-
var CLIENT_NAV_SCRIPT = `
|
|
237
|
+
var CLIENT_NAV_SCRIPT = `
|
|
238
|
+
(function () {
|
|
238
239
|
if (window.__xNav) return;
|
|
239
240
|
window.__xNav = true;
|
|
240
241
|
|
|
241
242
|
var cache = new Map();
|
|
242
|
-
var CACHE_LIMIT = 30;
|
|
243
243
|
|
|
244
|
-
function
|
|
245
|
-
if (
|
|
246
|
-
if (
|
|
247
|
-
|
|
248
|
-
if (
|
|
249
|
-
|
|
244
|
+
document.addEventListener("click", function (ev) {
|
|
245
|
+
if (ev.defaultPrevented || ev.button !== 0) return;
|
|
246
|
+
if (ev.metaKey || ev.ctrlKey || ev.shiftKey || ev.altKey) return;
|
|
247
|
+
var anchor = resolveLink(ev.target && ev.target.closest ? ev.target.closest("a[href]") : null);
|
|
248
|
+
if (!anchor) return;
|
|
249
|
+
ev.preventDefault();
|
|
250
|
+
if (anchor.href !== location.href) navigate(anchor, true);
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
document.addEventListener(
|
|
254
|
+
"mouseover",
|
|
255
|
+
function (ev) {
|
|
256
|
+
var anchor = resolveLink(ev.target && ev.target.closest ? ev.target.closest("a[href]") : null);
|
|
257
|
+
if (!anchor || anchor.hasAttribute("data-no-prefetch")) return;
|
|
258
|
+
prefetch(anchor);
|
|
259
|
+
},
|
|
260
|
+
{ passive: true },
|
|
261
|
+
);
|
|
262
|
+
|
|
263
|
+
document.addEventListener(
|
|
264
|
+
"focusin",
|
|
265
|
+
function (ev) {
|
|
266
|
+
var anchor = resolveLink(ev.target && ev.target.closest ? ev.target.closest("a[href]") : null);
|
|
267
|
+
if (!anchor || anchor.hasAttribute("data-no-prefetch")) return;
|
|
268
|
+
prefetch(anchor);
|
|
269
|
+
},
|
|
270
|
+
{ passive: true },
|
|
271
|
+
);
|
|
272
|
+
|
|
273
|
+
window.addEventListener("popstate", function () {
|
|
274
|
+
navigate(new URL(location.href), false);
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
var style = document.createElement("style");
|
|
278
|
+
style.textContent = [
|
|
279
|
+
".x-nav-loading{cursor:progress}",
|
|
280
|
+
".x-nav-loading::after{content:'';position:fixed;top:0;left:0;height:2px;width:100%;",
|
|
281
|
+
"background:var(--x-accent,#6ab0ff);z-index:9999;animation:x-nav-progress .8s ease-in-out infinite}",
|
|
282
|
+
"@keyframes x-nav-progress{0%{transform:translateX(-100%)}50%{transform:translateX(0)}100%{transform:translateX(100%)}}",
|
|
283
|
+
].join("");
|
|
284
|
+
document.head.appendChild(style);
|
|
285
|
+
|
|
286
|
+
function resolveLink(anchor) {
|
|
287
|
+
if (!anchor) return null;
|
|
288
|
+
if (anchor.hasAttribute("data-no-nav")) return null;
|
|
289
|
+
if (anchor.target && anchor.target !== "_self") return null;
|
|
290
|
+
if (anchor.hasAttribute("download")) return null;
|
|
291
|
+
var href = anchor.getAttribute("href");
|
|
250
292
|
if (!href) return null;
|
|
251
293
|
if (/^(#|mailto:|tel:|javascript:)/i.test(href)) return null;
|
|
252
|
-
|
|
253
294
|
var url;
|
|
254
295
|
try {
|
|
255
296
|
url = new URL(href, location.href);
|
|
256
|
-
} catch (
|
|
297
|
+
} catch (_) {
|
|
257
298
|
return null;
|
|
258
299
|
}
|
|
259
300
|
if (url.origin !== location.origin) return null;
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
var samePage = url.pathname === current.pathname && url.search === current.search;
|
|
263
|
-
if (samePage && url.hash) return null;
|
|
264
|
-
|
|
301
|
+
var here = new URL(location.href);
|
|
302
|
+
if (url.pathname === here.pathname && url.search === here.search && url.hash) return null;
|
|
265
303
|
return url;
|
|
266
304
|
}
|
|
267
305
|
|
|
268
|
-
function setLoading(
|
|
269
|
-
document.documentElement.classList.toggle("x-nav-loading",
|
|
306
|
+
function setLoading(on) {
|
|
307
|
+
document.documentElement.classList.toggle("x-nav-loading", on);
|
|
270
308
|
}
|
|
271
309
|
|
|
272
|
-
function
|
|
273
|
-
|
|
274
|
-
for (var i = 0; i < scripts.length; i++) {
|
|
275
|
-
var old = scripts[i];
|
|
276
|
-
var fresh = document.createElement("script");
|
|
277
|
-
for (var j = 0; j < old.attributes.length; j++) {
|
|
278
|
-
var attr = old.attributes[j];
|
|
279
|
-
fresh.setAttribute(attr.name, attr.value);
|
|
280
|
-
}
|
|
281
|
-
fresh.textContent = old.textContent;
|
|
282
|
-
old.replaceWith(fresh);
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
function evictIfFull() {
|
|
287
|
-
if (cache.size < CACHE_LIMIT) return;
|
|
288
|
-
var oldest = cache.keys().next().value;
|
|
289
|
-
if (oldest !== undefined) cache.delete(oldest);
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
function fetchPage(url) {
|
|
293
|
-
var key = url.href;
|
|
294
|
-
if (cache.has(key)) return cache.get(key);
|
|
310
|
+
function prefetch(url) {
|
|
311
|
+
if (cache.has(url.href)) return cache.get(url.href);
|
|
295
312
|
var promise = fetch(url.href, { headers: { "X-X-Nav": "1" } })
|
|
296
313
|
.then(function (res) {
|
|
297
314
|
return res.text().then(function (html) {
|
|
298
|
-
var
|
|
299
|
-
return {
|
|
300
|
-
html: html,
|
|
301
|
-
ok: res.ok,
|
|
302
|
-
finalUrl: res.url || url.href,
|
|
303
|
-
isHtml: contentType.indexOf("text/html") !== -1,
|
|
304
|
-
};
|
|
315
|
+
var ct = res.headers.get("content-type") || "";
|
|
316
|
+
return { html: html, ok: res.ok, finalUrl: res.url || url.href, isHtml: ct.indexOf("text/html") !== -1 };
|
|
305
317
|
});
|
|
306
318
|
})
|
|
307
319
|
.catch(function (err) {
|
|
308
|
-
cache.delete(
|
|
320
|
+
cache.delete(url.href);
|
|
309
321
|
throw err;
|
|
310
322
|
});
|
|
311
|
-
|
|
312
|
-
|
|
323
|
+
if (cache.size >= 30) {
|
|
324
|
+
var first = cache.keys().next().value;
|
|
325
|
+
if (first !== undefined) cache.delete(first);
|
|
326
|
+
}
|
|
327
|
+
cache.set(url.href, promise);
|
|
313
328
|
return promise;
|
|
314
329
|
}
|
|
315
330
|
|
|
316
|
-
function prefetch(url) {
|
|
317
|
-
if (cache.has(url.href)) return;
|
|
318
|
-
fetchPage(url).catch(function () {});
|
|
319
|
-
}
|
|
320
|
-
|
|
321
331
|
function navigate(url, push) {
|
|
322
332
|
setLoading(true);
|
|
323
|
-
|
|
324
|
-
.then(function (
|
|
325
|
-
if (!
|
|
333
|
+
prefetch(url)
|
|
334
|
+
.then(function (payload) {
|
|
335
|
+
if (!payload.isHtml) {
|
|
326
336
|
location.href = url.href;
|
|
327
337
|
return;
|
|
328
338
|
}
|
|
329
|
-
var doc = new DOMParser().parseFromString(
|
|
330
|
-
var
|
|
331
|
-
var
|
|
332
|
-
if (!
|
|
339
|
+
var doc = new DOMParser().parseFromString(payload.html, "text/html");
|
|
340
|
+
var next = doc.getElementById("root");
|
|
341
|
+
var root = document.getElementById("root");
|
|
342
|
+
if (!next || !root) {
|
|
333
343
|
location.href = url.href;
|
|
334
344
|
return;
|
|
335
345
|
}
|
|
336
|
-
|
|
337
|
-
if (push) history.pushState({ xNav: true }, "", entry.finalUrl);
|
|
346
|
+
if (push) history.pushState({ xNav: true }, "", payload.finalUrl);
|
|
338
347
|
if (doc.title) document.title = doc.title;
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
348
|
+
root.innerHTML = next.innerHTML;
|
|
349
|
+
reexecuteScripts(root);
|
|
342
350
|
if (url.hash) {
|
|
343
351
|
var target = document.getElementById(url.hash.slice(1));
|
|
344
352
|
if (target) {
|
|
@@ -356,47 +364,45 @@ var CLIENT_NAV_SCRIPT = `(function () {
|
|
|
356
364
|
});
|
|
357
365
|
}
|
|
358
366
|
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
document.addEventListener(
|
|
373
|
-
"mouseover",
|
|
374
|
-
function (event) {
|
|
375
|
-
var link = event.target && event.target.closest ? event.target.closest("a[href]") : null;
|
|
376
|
-
var url = isEligibleLink(link);
|
|
377
|
-
if (url) prefetch(url);
|
|
378
|
-
},
|
|
379
|
-
{ passive: true },
|
|
380
|
-
);
|
|
367
|
+
function reexecuteScripts(root) {
|
|
368
|
+
var scripts = root.querySelectorAll("script");
|
|
369
|
+
for (var i = 0; i < scripts.length; i++) {
|
|
370
|
+
var old = scripts[i];
|
|
371
|
+
var el = document.createElement("script");
|
|
372
|
+
for (var j = 0; j < old.attributes.length; j++) {
|
|
373
|
+
var attr = old.attributes[j];
|
|
374
|
+
el.setAttribute(attr.name, attr.value);
|
|
375
|
+
}
|
|
376
|
+
el.textContent = old.textContent;
|
|
377
|
+
old.replaceWith(el);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
381
380
|
|
|
382
|
-
|
|
381
|
+
/** Soft reload current page without a full document reload (used by dev live-reload). */
|
|
382
|
+
window.__xSoftReload = function () {
|
|
383
383
|
navigate(new URL(location.href), false);
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
style.textContent = [
|
|
388
|
-
".x-nav-loading{cursor:progress}",
|
|
389
|
-
".x-nav-loading::after{content:'';position:fixed;top:0;left:0;height:2px;width:100%;",
|
|
390
|
-
"background:var(--x-accent,#6ab0ff);z-index:9999;animation:x-nav-progress .8s ease-in-out infinite}",
|
|
391
|
-
"@keyframes x-nav-progress{0%{transform:translateX(-100%)}50%{transform:translateX(0)}100%{transform:translateX(100%)}}",
|
|
392
|
-
].join("");
|
|
393
|
-
document.head.appendChild(style);
|
|
394
|
-
})();`;
|
|
384
|
+
};
|
|
385
|
+
})();
|
|
386
|
+
`.trim();
|
|
395
387
|
|
|
396
388
|
// src/live-reload.ts
|
|
397
389
|
var LIVE_RELOAD_SCRIPT = `
|
|
398
|
-
(function()
|
|
399
|
-
|
|
390
|
+
(function () {
|
|
391
|
+
var es = new EventSource("/__x/reload");
|
|
392
|
+
es.addEventListener("reload", function () {
|
|
393
|
+
es.close();
|
|
394
|
+
if (typeof window.__xSoftReload === "function") {
|
|
395
|
+
window.__xSoftReload();
|
|
396
|
+
} else {
|
|
397
|
+
window.location.reload();
|
|
398
|
+
}
|
|
399
|
+
});
|
|
400
|
+
es.addEventListener("hb", function () {});
|
|
401
|
+
es.onerror = function () {
|
|
402
|
+
es.close();
|
|
403
|
+
};
|
|
404
|
+
})();
|
|
405
|
+
`.trim();
|
|
400
406
|
|
|
401
407
|
// src/render.ts
|
|
402
408
|
function escapeHtml(s) {
|
|
@@ -764,9 +770,309 @@ function composeMiddleware(fns, handler) {
|
|
|
764
770
|
};
|
|
765
771
|
}
|
|
766
772
|
|
|
773
|
+
// src/observability/health.ts
|
|
774
|
+
async function runChecks(checks) {
|
|
775
|
+
const results = {};
|
|
776
|
+
let allOk = true;
|
|
777
|
+
await Promise.all(
|
|
778
|
+
Object.entries(checks).map(async ([name, check]) => {
|
|
779
|
+
try {
|
|
780
|
+
const ok = await check();
|
|
781
|
+
results[name] = ok ? "ok" : "error";
|
|
782
|
+
if (!ok) allOk = false;
|
|
783
|
+
} catch {
|
|
784
|
+
results[name] = "error";
|
|
785
|
+
allOk = false;
|
|
786
|
+
}
|
|
787
|
+
})
|
|
788
|
+
);
|
|
789
|
+
return { status: allOk ? "ok" : "error", checks: results };
|
|
790
|
+
}
|
|
791
|
+
function createHealthCheckHandler(options = {}) {
|
|
792
|
+
const checks = options.checks ?? {};
|
|
793
|
+
return async (req) => {
|
|
794
|
+
const pathname = new URL(req.url).pathname;
|
|
795
|
+
if (pathname === "/healthz") {
|
|
796
|
+
return Response.json({ status: "ok" }, { status: 200 });
|
|
797
|
+
}
|
|
798
|
+
if (pathname === "/readyz") {
|
|
799
|
+
const result = await runChecks(checks);
|
|
800
|
+
return Response.json(result, { status: result.status === "ok" ? 200 : 503 });
|
|
801
|
+
}
|
|
802
|
+
return null;
|
|
803
|
+
};
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
// src/observability/logger.ts
|
|
807
|
+
function write(level, message, fields) {
|
|
808
|
+
const entry = {
|
|
809
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
810
|
+
level,
|
|
811
|
+
message,
|
|
812
|
+
...fields
|
|
813
|
+
};
|
|
814
|
+
const line = JSON.stringify(entry);
|
|
815
|
+
if (level === "error") {
|
|
816
|
+
console.error(line);
|
|
817
|
+
} else if (level === "warn") {
|
|
818
|
+
console.warn(line);
|
|
819
|
+
} else {
|
|
820
|
+
console.log(line);
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
var logger = {
|
|
824
|
+
info: (message, fields) => write("info", message, fields),
|
|
825
|
+
warn: (message, fields) => write("warn", message, fields),
|
|
826
|
+
error: (message, fields) => write("error", message, fields)
|
|
827
|
+
};
|
|
828
|
+
function withRequestLogging(handler) {
|
|
829
|
+
return async (req) => {
|
|
830
|
+
const start = performance.now();
|
|
831
|
+
const requestId = req.headers.get("x-request-id") ?? crypto.randomUUID();
|
|
832
|
+
const route = new URL(req.url).pathname;
|
|
833
|
+
try {
|
|
834
|
+
const res = await handler(req);
|
|
835
|
+
write("info", "request completed", {
|
|
836
|
+
requestId,
|
|
837
|
+
route,
|
|
838
|
+
method: req.method,
|
|
839
|
+
status: res.status,
|
|
840
|
+
durationMs: Math.round(performance.now() - start)
|
|
841
|
+
});
|
|
842
|
+
if (!res.headers.has("x-request-id")) {
|
|
843
|
+
const headers = new Headers(res.headers);
|
|
844
|
+
headers.set("x-request-id", requestId);
|
|
845
|
+
return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
|
|
846
|
+
}
|
|
847
|
+
return res;
|
|
848
|
+
} catch (err) {
|
|
849
|
+
write("error", "request failed", {
|
|
850
|
+
requestId,
|
|
851
|
+
route,
|
|
852
|
+
method: req.method,
|
|
853
|
+
status: 500,
|
|
854
|
+
durationMs: Math.round(performance.now() - start),
|
|
855
|
+
error: err instanceof Error ? err.message : String(err)
|
|
856
|
+
});
|
|
857
|
+
throw err;
|
|
858
|
+
}
|
|
859
|
+
};
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
// src/observability/monitoring.ts
|
|
863
|
+
var noopReporter = {
|
|
864
|
+
captureException: () => {
|
|
865
|
+
}
|
|
866
|
+
};
|
|
867
|
+
var activeReporter = noopReporter;
|
|
868
|
+
function setErrorReporter(reporter) {
|
|
869
|
+
activeReporter = reporter;
|
|
870
|
+
}
|
|
871
|
+
function getErrorReporter() {
|
|
872
|
+
return activeReporter;
|
|
873
|
+
}
|
|
874
|
+
function reportException(error, context) {
|
|
875
|
+
try {
|
|
876
|
+
activeReporter.captureException(error, context);
|
|
877
|
+
} catch (reportingError) {
|
|
878
|
+
console.error("[x] error reporter threw while handling an exception:", reportingError);
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
function createSentryReporter(sentry) {
|
|
882
|
+
return {
|
|
883
|
+
captureException(error, context) {
|
|
884
|
+
sentry.captureException(error, { extra: { ...context } });
|
|
885
|
+
},
|
|
886
|
+
async flush() {
|
|
887
|
+
await sentry.flush?.(2e3);
|
|
888
|
+
}
|
|
889
|
+
};
|
|
890
|
+
}
|
|
891
|
+
var OTEL_ERROR_STATUS_CODE = 2;
|
|
892
|
+
function createOtelReporter(tracer) {
|
|
893
|
+
return {
|
|
894
|
+
captureException(error, context) {
|
|
895
|
+
const span = tracer.startSpan(`x.${context.phase}.error`);
|
|
896
|
+
span.recordException(error);
|
|
897
|
+
span.setStatus({
|
|
898
|
+
code: OTEL_ERROR_STATUS_CODE,
|
|
899
|
+
message: error instanceof Error ? error.message : String(error)
|
|
900
|
+
});
|
|
901
|
+
span.end();
|
|
902
|
+
}
|
|
903
|
+
};
|
|
904
|
+
}
|
|
905
|
+
function combineReporters(...reporters) {
|
|
906
|
+
return {
|
|
907
|
+
captureException(error, context) {
|
|
908
|
+
for (const reporter of reporters) {
|
|
909
|
+
try {
|
|
910
|
+
reporter.captureException(error, context);
|
|
911
|
+
} catch (err) {
|
|
912
|
+
console.error("[x] error reporter threw while handling an exception:", err);
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
},
|
|
916
|
+
async flush() {
|
|
917
|
+
await Promise.all(reporters.map((r) => r.flush?.()));
|
|
918
|
+
}
|
|
919
|
+
};
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
// src/security/headers.ts
|
|
923
|
+
var DEFAULT_CSP = "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'";
|
|
924
|
+
function buildSecurityHeaders(options = {}) {
|
|
925
|
+
const headers = new Headers();
|
|
926
|
+
const csp = options.contentSecurityPolicy ?? DEFAULT_CSP;
|
|
927
|
+
if (csp !== false) headers.set("Content-Security-Policy", csp);
|
|
928
|
+
const hstsMaxAge = options.hstsMaxAge ?? 15552e3;
|
|
929
|
+
if (hstsMaxAge !== false) {
|
|
930
|
+
const includeSub = options.hstsIncludeSubDomains ?? true;
|
|
931
|
+
headers.set(
|
|
932
|
+
"Strict-Transport-Security",
|
|
933
|
+
`max-age=${hstsMaxAge}${includeSub ? "; includeSubDomains" : ""}`
|
|
934
|
+
);
|
|
935
|
+
}
|
|
936
|
+
const frameOptions = options.frameOptions ?? "DENY";
|
|
937
|
+
if (frameOptions !== false) headers.set("X-Frame-Options", frameOptions);
|
|
938
|
+
const contentTypeOptions = options.contentTypeOptions ?? "nosniff";
|
|
939
|
+
if (contentTypeOptions !== false) headers.set("X-Content-Type-Options", contentTypeOptions);
|
|
940
|
+
const referrerPolicy = options.referrerPolicy ?? "strict-origin-when-cross-origin";
|
|
941
|
+
if (referrerPolicy !== false) headers.set("Referrer-Policy", referrerPolicy);
|
|
942
|
+
return headers;
|
|
943
|
+
}
|
|
944
|
+
function applySecurityHeaders(res, options = {}) {
|
|
945
|
+
const extra = buildSecurityHeaders(options);
|
|
946
|
+
const headers = new Headers(res.headers);
|
|
947
|
+
for (const [key, value] of extra.entries()) {
|
|
948
|
+
if (!headers.has(key)) headers.set(key, value);
|
|
949
|
+
}
|
|
950
|
+
return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
// src/security/rate-limit.ts
|
|
954
|
+
function defaultKeyFn(req) {
|
|
955
|
+
const headers = req.headers;
|
|
956
|
+
const forwarded = headers.get("x-forwarded-for");
|
|
957
|
+
if (forwarded) return forwarded.split(",")[0]?.trim() ?? "unknown";
|
|
958
|
+
return headers.get("x-real-ip") ?? "unknown";
|
|
959
|
+
}
|
|
960
|
+
function createRateLimiter(options = {}) {
|
|
961
|
+
const limit = options.limit ?? 60;
|
|
962
|
+
const windowMs = options.windowMs ?? 6e4;
|
|
963
|
+
const keyFn = options.keyFn ?? defaultKeyFn;
|
|
964
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
965
|
+
function check(req) {
|
|
966
|
+
const key = keyFn(req);
|
|
967
|
+
const now = Date.now();
|
|
968
|
+
let bucket = buckets.get(key);
|
|
969
|
+
if (!bucket || bucket.resetAt <= now) {
|
|
970
|
+
bucket = { count: 0, resetAt: now + windowMs };
|
|
971
|
+
buckets.set(key, bucket);
|
|
972
|
+
}
|
|
973
|
+
bucket.count += 1;
|
|
974
|
+
const ok = bucket.count <= limit;
|
|
975
|
+
return { ok, limit, remaining: Math.max(0, limit - bucket.count), resetAt: bucket.resetAt };
|
|
976
|
+
}
|
|
977
|
+
function sweep() {
|
|
978
|
+
const now = Date.now();
|
|
979
|
+
for (const [key, bucket] of buckets) {
|
|
980
|
+
if (bucket.resetAt <= now) buckets.delete(key);
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
return { check, sweep, buckets };
|
|
984
|
+
}
|
|
985
|
+
function rateLimitMiddleware(limiter, req) {
|
|
986
|
+
const result = limiter.check(req);
|
|
987
|
+
if (result.ok) return null;
|
|
988
|
+
const retryAfterSeconds = Math.max(1, Math.ceil((result.resetAt - Date.now()) / 1e3));
|
|
989
|
+
return new Response("Too Many Requests", {
|
|
990
|
+
status: 429,
|
|
991
|
+
headers: {
|
|
992
|
+
"Retry-After": String(retryAfterSeconds),
|
|
993
|
+
"X-RateLimit-Limit": String(result.limit),
|
|
994
|
+
"X-RateLimit-Remaining": String(result.remaining)
|
|
995
|
+
}
|
|
996
|
+
});
|
|
997
|
+
}
|
|
998
|
+
|
|
767
999
|
// src/server-functions.ts
|
|
768
1000
|
import { writeFileSync as writeFileSync2 } from "fs";
|
|
769
1001
|
import { join as join3 } from "path";
|
|
1002
|
+
|
|
1003
|
+
// src/security/csrf.ts
|
|
1004
|
+
var CSRF_COOKIE_NAME = "x_csrf_token";
|
|
1005
|
+
var CSRF_HEADER_NAME = "x-csrf-token";
|
|
1006
|
+
var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
|
|
1007
|
+
function originFromHeader(value) {
|
|
1008
|
+
if (!value) return null;
|
|
1009
|
+
try {
|
|
1010
|
+
return new URL(value).origin;
|
|
1011
|
+
} catch {
|
|
1012
|
+
return null;
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
function requestOrigin(req) {
|
|
1016
|
+
const url = new URL(req.url);
|
|
1017
|
+
return `${url.protocol}//${url.host}`;
|
|
1018
|
+
}
|
|
1019
|
+
function verifyOrigin(req, allowedOrigins = []) {
|
|
1020
|
+
if (SAFE_METHODS.has(req.method)) return { ok: true };
|
|
1021
|
+
const selfOrigin = requestOrigin(req);
|
|
1022
|
+
const allowed = new Set([selfOrigin, ...allowedOrigins].filter(Boolean));
|
|
1023
|
+
const origin = originFromHeader(req.headers.get("origin"));
|
|
1024
|
+
if (origin) {
|
|
1025
|
+
return allowed.has(origin) ? { ok: true } : { ok: false, reason: `origin "${origin}" is not an allowed origin` };
|
|
1026
|
+
}
|
|
1027
|
+
const referer = originFromHeader(req.headers.get("referer"));
|
|
1028
|
+
if (referer) {
|
|
1029
|
+
return allowed.has(referer) ? { ok: true } : { ok: false, reason: `referer origin "${referer}" is not an allowed origin` };
|
|
1030
|
+
}
|
|
1031
|
+
return { ok: false, reason: "missing Origin and Referer headers on a mutating request" };
|
|
1032
|
+
}
|
|
1033
|
+
function generateCsrfToken() {
|
|
1034
|
+
return crypto.randomUUID().replace(/-/g, "") + crypto.randomUUID().replace(/-/g, "");
|
|
1035
|
+
}
|
|
1036
|
+
function readCookie(req, name) {
|
|
1037
|
+
const header = req.headers.get("cookie");
|
|
1038
|
+
if (!header) return null;
|
|
1039
|
+
for (const part of header.split(";")) {
|
|
1040
|
+
const [key, ...rest] = part.trim().split("=");
|
|
1041
|
+
if (key === name) return rest.join("=");
|
|
1042
|
+
}
|
|
1043
|
+
return null;
|
|
1044
|
+
}
|
|
1045
|
+
function verifyCsrfToken(req) {
|
|
1046
|
+
if (SAFE_METHODS.has(req.method)) return { ok: true };
|
|
1047
|
+
const cookieToken = readCookie(req, CSRF_COOKIE_NAME);
|
|
1048
|
+
const headerToken = req.headers.get(CSRF_HEADER_NAME);
|
|
1049
|
+
if (!cookieToken || !headerToken) {
|
|
1050
|
+
return { ok: false, reason: `missing CSRF cookie or "${CSRF_HEADER_NAME}" header` };
|
|
1051
|
+
}
|
|
1052
|
+
if (cookieToken !== headerToken) {
|
|
1053
|
+
return { ok: false, reason: "CSRF token mismatch" };
|
|
1054
|
+
}
|
|
1055
|
+
return { ok: true };
|
|
1056
|
+
}
|
|
1057
|
+
function withCsrfCookie(req, res) {
|
|
1058
|
+
if (readCookie(req, CSRF_COOKIE_NAME)) return res;
|
|
1059
|
+
const token = generateCsrfToken();
|
|
1060
|
+
const headers = new Headers(res.headers);
|
|
1061
|
+
headers.append("Set-Cookie", `${CSRF_COOKIE_NAME}=${token}; Path=/; SameSite=Lax`);
|
|
1062
|
+
return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
|
|
1063
|
+
}
|
|
1064
|
+
function checkCsrf(req, options = {}) {
|
|
1065
|
+
if (options.disabled) return { ok: true };
|
|
1066
|
+
const originResult = verifyOrigin(req, options.allowedOrigins ?? []);
|
|
1067
|
+
if (!originResult.ok) return originResult;
|
|
1068
|
+
if (options.requireToken) {
|
|
1069
|
+
const tokenResult = verifyCsrfToken(req);
|
|
1070
|
+
if (!tokenResult.ok) return tokenResult;
|
|
1071
|
+
}
|
|
1072
|
+
return { ok: true };
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
// src/server-functions.ts
|
|
770
1076
|
function generateServerFunctionClient(routeFilePath, fnNames, endpointBase) {
|
|
771
1077
|
const fnCalls = fnNames.map(
|
|
772
1078
|
(name) => `
|
|
@@ -801,11 +1107,15 @@ function registerServerFunctions(routePath, paramNames, fns) {
|
|
|
801
1107
|
ACTION_ROUTES.push({ routePath, paramNames, fns: fnMap });
|
|
802
1108
|
}
|
|
803
1109
|
}
|
|
804
|
-
function getServerFunctionHandler() {
|
|
1110
|
+
function getServerFunctionHandler(csrfOptions) {
|
|
805
1111
|
return async (req) => {
|
|
806
1112
|
if (req.method !== "POST") return null;
|
|
807
1113
|
const url = new URL(req.url);
|
|
808
1114
|
if (!url.pathname.startsWith("/__x/actions/")) return null;
|
|
1115
|
+
const csrfResult = checkCsrf(req, csrfOptions);
|
|
1116
|
+
if (!csrfResult.ok) {
|
|
1117
|
+
return new Response(`Forbidden: ${csrfResult.reason}`, { status: 403 });
|
|
1118
|
+
}
|
|
809
1119
|
const parts = url.pathname.replace("/__x/actions/", "").split("/");
|
|
810
1120
|
if (parts.length < 2) return null;
|
|
811
1121
|
const actionName = parts.pop();
|
|
@@ -827,6 +1137,7 @@ function getServerFunctionHandler() {
|
|
|
827
1137
|
const result = await fn(...args);
|
|
828
1138
|
return Response.json(result);
|
|
829
1139
|
} catch (err) {
|
|
1140
|
+
reportException(err, { route: concretePath, phase: "action" });
|
|
830
1141
|
const message = err instanceof Error ? err.message : "Internal error";
|
|
831
1142
|
return new Response(message, { status: 500 });
|
|
832
1143
|
}
|
|
@@ -917,8 +1228,18 @@ async function createApp(options) {
|
|
|
917
1228
|
let stylesheetHref;
|
|
918
1229
|
let notFoundComponent = DefaultNotFound;
|
|
919
1230
|
let notFoundLayout;
|
|
920
|
-
const serverFnHandler = getServerFunctionHandler();
|
|
1231
|
+
const serverFnHandler = getServerFunctionHandler(options.security?.csrf);
|
|
921
1232
|
const staticCache = /* @__PURE__ */ new Map();
|
|
1233
|
+
if (options.observability?.errorReporter) {
|
|
1234
|
+
setErrorReporter(options.observability.errorReporter);
|
|
1235
|
+
}
|
|
1236
|
+
const healthHandler = createHealthCheckHandler(options.observability?.health ?? {});
|
|
1237
|
+
const rateLimiter = options.security?.rateLimit === false ? null : createRateLimiter(options.security?.rateLimit ?? {});
|
|
1238
|
+
const securityHeadersOptions = options.security?.headers;
|
|
1239
|
+
const loggingEnabled = options.observability?.logging ?? true;
|
|
1240
|
+
function withResponseHardening(res) {
|
|
1241
|
+
return securityHeadersOptions === false ? res : applySecurityHeaders(res, securityHeadersOptions);
|
|
1242
|
+
}
|
|
922
1243
|
async function renderNotFound(req) {
|
|
923
1244
|
const content = notFoundLayout ? createElement(notFoundLayout, null, createElement(notFoundComponent, { params: {} })) : createElement(notFoundComponent, { params: {} });
|
|
924
1245
|
const html = renderPage(content, {
|
|
@@ -1023,6 +1344,7 @@ async function createApp(options) {
|
|
|
1023
1344
|
}
|
|
1024
1345
|
return new Response(`Method ${method} not allowed`, { status: 405 });
|
|
1025
1346
|
} catch (err) {
|
|
1347
|
+
reportException(err, { route: route.routePath, phase: "api" });
|
|
1026
1348
|
console.error("[x] API handler error:", err);
|
|
1027
1349
|
if (options.development) {
|
|
1028
1350
|
return new Response(renderErrorOverlay(err), {
|
|
@@ -1125,6 +1447,7 @@ async function createApp(options) {
|
|
|
1125
1447
|
}
|
|
1126
1448
|
return baseHandler({ params, request: req });
|
|
1127
1449
|
} catch (err) {
|
|
1450
|
+
reportException(err, { route: route.routePath, phase: "ssr" });
|
|
1128
1451
|
console.error("[x] route handler error:", err);
|
|
1129
1452
|
if (options.development) {
|
|
1130
1453
|
return new Response(renderErrorOverlay(err), {
|
|
@@ -1226,8 +1549,14 @@ async function createApp(options) {
|
|
|
1226
1549
|
} catch {
|
|
1227
1550
|
console.warn("[x] file watching not available on this platform");
|
|
1228
1551
|
}
|
|
1229
|
-
const
|
|
1552
|
+
const devFetchInner = async (req) => {
|
|
1230
1553
|
const url = new URL(req.url).pathname;
|
|
1554
|
+
const healthResult = await healthHandler(req);
|
|
1555
|
+
if (healthResult !== null) return healthResult;
|
|
1556
|
+
if (rateLimiter) {
|
|
1557
|
+
const limited = rateLimitMiddleware(rateLimiter, req);
|
|
1558
|
+
if (limited !== null) return limited;
|
|
1559
|
+
}
|
|
1231
1560
|
if (url === "/__x/reload") {
|
|
1232
1561
|
const body = new ReadableStream({
|
|
1233
1562
|
start(controller) {
|
|
@@ -1270,6 +1599,8 @@ data: ${data}
|
|
|
1270
1599
|
}
|
|
1271
1600
|
return renderNotFound(req);
|
|
1272
1601
|
};
|
|
1602
|
+
const devFetchHardened = async (req) => withResponseHardening(await devFetchInner(req));
|
|
1603
|
+
const devFetch = loggingEnabled ? withRequestLogging(devFetchHardened) : devFetchHardened;
|
|
1273
1604
|
return {
|
|
1274
1605
|
routes: {},
|
|
1275
1606
|
development: true,
|
|
@@ -1277,8 +1608,14 @@ data: ${data}
|
|
|
1277
1608
|
fetch: devFetch
|
|
1278
1609
|
};
|
|
1279
1610
|
}
|
|
1280
|
-
const
|
|
1611
|
+
const prodFetchInner = async (req) => {
|
|
1281
1612
|
const url = new URL(req.url).pathname;
|
|
1613
|
+
const healthResult = await healthHandler(req);
|
|
1614
|
+
if (healthResult !== null) return healthResult;
|
|
1615
|
+
if (rateLimiter) {
|
|
1616
|
+
const limited = rateLimitMiddleware(rateLimiter, req);
|
|
1617
|
+
if (limited !== null) return limited;
|
|
1618
|
+
}
|
|
1282
1619
|
const revalidationResult = await handleRevalidation(req);
|
|
1283
1620
|
if (revalidationResult !== null) return revalidationResult;
|
|
1284
1621
|
const serverFnResult = await serverFnHandler(req);
|
|
@@ -1298,6 +1635,8 @@ data: ${data}
|
|
|
1298
1635
|
}
|
|
1299
1636
|
return renderNotFound(req);
|
|
1300
1637
|
};
|
|
1638
|
+
const prodFetchHardened = async (req) => withResponseHardening(await prodFetchInner(req));
|
|
1639
|
+
const prodFetch = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
|
|
1301
1640
|
return {
|
|
1302
1641
|
routes: {},
|
|
1303
1642
|
development: false,
|
|
@@ -1307,7 +1646,7 @@ data: ${data}
|
|
|
1307
1646
|
}
|
|
1308
1647
|
|
|
1309
1648
|
// src/build.ts
|
|
1310
|
-
import { cpSync, existsSync as existsSync2, mkdirSync, writeFileSync as writeFileSync3 } from "fs";
|
|
1649
|
+
import { cpSync, existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync as writeFileSync3 } from "fs";
|
|
1311
1650
|
import { basename, join as join5, relative as relative3 } from "path";
|
|
1312
1651
|
import { createElement as createElement2 } from "react";
|
|
1313
1652
|
|
|
@@ -1338,6 +1677,46 @@ function Island({
|
|
|
1338
1677
|
return /* @__PURE__ */ jsx2("div", { "data-island": name, "data-island-id": id, "data-island-client": client, children });
|
|
1339
1678
|
}
|
|
1340
1679
|
|
|
1680
|
+
// src/security/env-isolation.ts
|
|
1681
|
+
var PUBLIC_ENV_PREFIX = "THEXJS_PUBLIC_";
|
|
1682
|
+
var ENV_ACCESS_PATTERNS = [
|
|
1683
|
+
/\bprocess\.env\.([A-Za-z_][A-Za-z0-9_]*)/g,
|
|
1684
|
+
/\bprocess\.env\[["']([A-Za-z_][A-Za-z0-9_]*)["']\]/g,
|
|
1685
|
+
/\bBun\.env\.([A-Za-z_][A-Za-z0-9_]*)/g,
|
|
1686
|
+
/\bBun\.env\[["']([A-Za-z_][A-Za-z0-9_]*)["']\]/g,
|
|
1687
|
+
/\bimport\.meta\.env\.([A-Za-z_][A-Za-z0-9_]*)/g
|
|
1688
|
+
];
|
|
1689
|
+
function findLeakedEnvKeys(code) {
|
|
1690
|
+
const found = /* @__PURE__ */ new Set();
|
|
1691
|
+
for (const pattern of ENV_ACCESS_PATTERNS) {
|
|
1692
|
+
for (const match of code.matchAll(pattern)) {
|
|
1693
|
+
const key = match[1];
|
|
1694
|
+
if (key && !key.startsWith(PUBLIC_ENV_PREFIX)) {
|
|
1695
|
+
found.add(key);
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
}
|
|
1699
|
+
return [...found];
|
|
1700
|
+
}
|
|
1701
|
+
var EnvLeakageError = class extends Error {
|
|
1702
|
+
constructor(file, keys) {
|
|
1703
|
+
super(
|
|
1704
|
+
`[x] server-only environment variable(s) leaked into client bundle "${file}": ${keys.join(", ")}. Only "${PUBLIC_ENV_PREFIX}*" variables may be referenced in client-shipped code \u2014 move this access into a loader, server function, or API route.`
|
|
1705
|
+
);
|
|
1706
|
+
this.file = file;
|
|
1707
|
+
this.keys = keys;
|
|
1708
|
+
this.name = "EnvLeakageError";
|
|
1709
|
+
}
|
|
1710
|
+
file;
|
|
1711
|
+
keys;
|
|
1712
|
+
};
|
|
1713
|
+
function assertNoEnvLeakage(code, file) {
|
|
1714
|
+
const leaked = findLeakedEnvKeys(code);
|
|
1715
|
+
if (leaked.length > 0) {
|
|
1716
|
+
throw new EnvLeakageError(file, leaked);
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
|
|
1341
1720
|
// src/build.ts
|
|
1342
1721
|
async function build(options) {
|
|
1343
1722
|
const outDir = options.outDir ?? join5(process.cwd(), ".x");
|
|
@@ -1484,8 +1863,10 @@ async function build(options) {
|
|
|
1484
1863
|
if (options.layoutsDir) srvOpts.layoutsDir = options.layoutsDir;
|
|
1485
1864
|
if (options.actionsDir) srvOpts.actionsDir = options.actionsDir;
|
|
1486
1865
|
if (options.contentDir) srvOpts.contentDir = options.contentDir;
|
|
1866
|
+
const configImportPath = options.configPath ? relativeImportPath(serverDir, options.configPath) : void 0;
|
|
1487
1867
|
const serverEntry = buildServerEntry(
|
|
1488
|
-
srvOpts
|
|
1868
|
+
srvOpts,
|
|
1869
|
+
configImportPath
|
|
1489
1870
|
);
|
|
1490
1871
|
const serverEntryPath = join5(serverDir, "index.ts");
|
|
1491
1872
|
writeFileSync3(serverEntryPath, serverEntry, "utf-8");
|
|
@@ -1517,20 +1898,23 @@ async function bundleRouteIslands(routeFilePath, islandNames, islandsDir) {
|
|
|
1517
1898
|
entryPath
|
|
1518
1899
|
]);
|
|
1519
1900
|
if (result.success) {
|
|
1901
|
+
assertNoEnvLeakage(readFileSync2(bundlePath, "utf-8"), bundlePath);
|
|
1520
1902
|
return [`/_islands/${entryId}/${entryId}.js`];
|
|
1521
1903
|
}
|
|
1522
1904
|
writeFileSync3(bundlePath, generateFallbackHydration(islandNames), "utf-8");
|
|
1523
1905
|
return [`/_islands/${entryId}/${entryId}.js`];
|
|
1524
1906
|
}
|
|
1525
|
-
function generateHydrateEntry(routeRelPath,
|
|
1526
|
-
return `import
|
|
1907
|
+
function generateHydrateEntry(routeRelPath, _islandNames) {
|
|
1908
|
+
return `import React from "react";
|
|
1909
|
+
import { hydrateRoot } from "react-dom/client";
|
|
1910
|
+
import * as Route from "${routeRelPath}";
|
|
1527
1911
|
|
|
1528
1912
|
document.querySelectorAll("[data-island]").forEach((el) => {
|
|
1529
1913
|
const name = el.getAttribute("data-island");
|
|
1530
1914
|
if (!name) return;
|
|
1531
1915
|
const Component = Route.islands?.[name];
|
|
1532
1916
|
if (!Component) return;
|
|
1533
|
-
|
|
1917
|
+
hydrateRoot(el, React.createElement(Component));
|
|
1534
1918
|
});
|
|
1535
1919
|
`;
|
|
1536
1920
|
}
|
|
@@ -1562,21 +1946,35 @@ function StaticContentPage({
|
|
|
1562
1946
|
})
|
|
1563
1947
|
);
|
|
1564
1948
|
}
|
|
1565
|
-
function buildServerEntry(opts) {
|
|
1949
|
+
function buildServerEntry(opts, configImportPath) {
|
|
1566
1950
|
const dirKeys = ["pagesDir", "apiDir", "layoutsDir", "actionsDir", "contentDir"];
|
|
1567
1951
|
const lines = [
|
|
1568
1952
|
"// Auto-generated by @thexjs/core build",
|
|
1569
|
-
'import { createApp } from "@thexjs/core";'
|
|
1570
|
-
"",
|
|
1571
|
-
"const app = await createApp({"
|
|
1953
|
+
'import { createApp } from "@thexjs/core";'
|
|
1572
1954
|
];
|
|
1955
|
+
if (configImportPath) {
|
|
1956
|
+
lines.push("", "let userConfig = {};", "try {");
|
|
1957
|
+
lines.push(` const mod = await import(${JSON.stringify(configImportPath)});`);
|
|
1958
|
+
lines.push(" userConfig = mod.default ?? {};");
|
|
1959
|
+
lines.push("} catch (err) {");
|
|
1960
|
+
lines.push(
|
|
1961
|
+
' console.warn("[x] failed to load x.config for security/observability options:", err);'
|
|
1962
|
+
);
|
|
1963
|
+
lines.push("}");
|
|
1964
|
+
}
|
|
1965
|
+
lines.push("", "const app = await createApp({");
|
|
1573
1966
|
for (const key of dirKeys) {
|
|
1574
1967
|
const val = opts[key];
|
|
1575
1968
|
if (val) lines.push(` ${key}: ${JSON.stringify(val)},`);
|
|
1576
1969
|
}
|
|
1970
|
+
lines.push(' port: parseInt(process.env.PORT || "3000", 10),', " development: false,");
|
|
1971
|
+
if (configImportPath) {
|
|
1972
|
+
lines.push(" ...(userConfig.security ? { security: userConfig.security } : {}),");
|
|
1973
|
+
lines.push(
|
|
1974
|
+
" ...(userConfig.observability ? { observability: userConfig.observability } : {}),"
|
|
1975
|
+
);
|
|
1976
|
+
}
|
|
1577
1977
|
lines.push(
|
|
1578
|
-
' port: parseInt(process.env.PORT || "3000", 10),',
|
|
1579
|
-
" development: false,",
|
|
1580
1978
|
"});",
|
|
1581
1979
|
"",
|
|
1582
1980
|
"const server = Bun.serve(app);",
|
|
@@ -1585,6 +1983,10 @@ function buildServerEntry(opts) {
|
|
|
1585
1983
|
);
|
|
1586
1984
|
return lines.join("\n");
|
|
1587
1985
|
}
|
|
1986
|
+
function relativeImportPath(fromDir, toFile) {
|
|
1987
|
+
const rel = relative3(fromDir, toFile).replace(/\\/g, "/").replace(/\.(ts|js|mjs)$/, "");
|
|
1988
|
+
return rel.startsWith(".") ? rel : `./${rel}`;
|
|
1989
|
+
}
|
|
1588
1990
|
function hash(str) {
|
|
1589
1991
|
let h = 0;
|
|
1590
1992
|
for (let i = 0; i < str.length; i++) {
|
|
@@ -1593,6 +1995,21 @@ function hash(str) {
|
|
|
1593
1995
|
return Math.abs(h).toString(36);
|
|
1594
1996
|
}
|
|
1595
1997
|
|
|
1998
|
+
// src/link.tsx
|
|
1999
|
+
import { jsx as jsx3 } from "react/jsx-runtime";
|
|
2000
|
+
function Link({ href, children, clientNav = true, prefetch = true, ...rest }) {
|
|
2001
|
+
return /* @__PURE__ */ jsx3(
|
|
2002
|
+
"a",
|
|
2003
|
+
{
|
|
2004
|
+
href,
|
|
2005
|
+
...rest,
|
|
2006
|
+
...!clientNav ? { "data-no-nav": "" } : {},
|
|
2007
|
+
...!prefetch ? { "data-no-prefetch": "" } : {},
|
|
2008
|
+
children
|
|
2009
|
+
}
|
|
2010
|
+
);
|
|
2011
|
+
}
|
|
2012
|
+
|
|
1596
2013
|
// src/data/sqlite.ts
|
|
1597
2014
|
import { Database } from "bun:sqlite";
|
|
1598
2015
|
function connectSQLite(options) {
|
|
@@ -1618,7 +2035,7 @@ function connectPostgres(options) {
|
|
|
1618
2035
|
}
|
|
1619
2036
|
|
|
1620
2037
|
// src/data/migrate.ts
|
|
1621
|
-
import { readFileSync as
|
|
2038
|
+
import { readFileSync as readFileSync3, readdirSync as readdirSync3 } from "fs";
|
|
1622
2039
|
import { join as join6 } from "path";
|
|
1623
2040
|
function runSQLiteMigrations(db, migrationsDir) {
|
|
1624
2041
|
db.run(`CREATE TABLE IF NOT EXISTS _x_migrations (
|
|
@@ -1639,7 +2056,7 @@ function runSQLiteMigrations(db, migrationsDir) {
|
|
|
1639
2056
|
result.skipped.push(file);
|
|
1640
2057
|
continue;
|
|
1641
2058
|
}
|
|
1642
|
-
const sql =
|
|
2059
|
+
const sql = readFileSync3(join6(migrationsDir, file), "utf-8");
|
|
1643
2060
|
db.run(sql);
|
|
1644
2061
|
db.run("INSERT INTO _x_migrations (name) VALUES (?1)", [file]);
|
|
1645
2062
|
console.log(`[x] migration applied: ${file}`);
|
|
@@ -1666,7 +2083,7 @@ async function runPostgresMigrations(client, migrationsDir) {
|
|
|
1666
2083
|
result.skipped.push(file);
|
|
1667
2084
|
continue;
|
|
1668
2085
|
}
|
|
1669
|
-
const raw =
|
|
2086
|
+
const raw = readFileSync3(join6(migrationsDir, file), "utf-8");
|
|
1670
2087
|
await client.unsafe(raw);
|
|
1671
2088
|
await client.unsafe(`INSERT INTO _x_migrations (name) VALUES ('${file}')`);
|
|
1672
2089
|
console.log(`[x] migration applied: ${file}`);
|
|
@@ -1677,26 +2094,45 @@ async function runPostgresMigrations(client, migrationsDir) {
|
|
|
1677
2094
|
export {
|
|
1678
2095
|
CLIENT_NAV_SCRIPT,
|
|
1679
2096
|
DefaultNotFound,
|
|
2097
|
+
EnvLeakageError,
|
|
1680
2098
|
Island,
|
|
1681
2099
|
IslandProvider,
|
|
2100
|
+
Link,
|
|
2101
|
+
PUBLIC_ENV_PREFIX,
|
|
2102
|
+
applySecurityHeaders,
|
|
2103
|
+
assertNoEnvLeakage,
|
|
1682
2104
|
build,
|
|
2105
|
+
buildSecurityHeaders,
|
|
2106
|
+
checkCsrf,
|
|
2107
|
+
combineReporters,
|
|
1683
2108
|
composeMiddleware,
|
|
1684
2109
|
connectPostgres,
|
|
1685
2110
|
connectSQLite,
|
|
1686
2111
|
createApp,
|
|
2112
|
+
createHealthCheckHandler,
|
|
2113
|
+
createOtelReporter,
|
|
2114
|
+
createRateLimiter,
|
|
2115
|
+
createSentryReporter,
|
|
1687
2116
|
defineConfig,
|
|
1688
2117
|
escapeHtml2 as escapeHtml,
|
|
1689
2118
|
findLayoutChain,
|
|
2119
|
+
findLeakedEnvKeys,
|
|
1690
2120
|
findMiddlewareChain,
|
|
2121
|
+
generateCsrfToken,
|
|
1691
2122
|
generateManifestSource,
|
|
1692
2123
|
generateServerFunctionClient,
|
|
2124
|
+
getErrorReporter,
|
|
1693
2125
|
getServerFunctionHandler,
|
|
2126
|
+
logger,
|
|
2127
|
+
noopReporter,
|
|
2128
|
+
rateLimitMiddleware,
|
|
1694
2129
|
registerServerFunctions,
|
|
1695
2130
|
renderErrorOverlay,
|
|
1696
2131
|
renderMarkdown,
|
|
1697
2132
|
renderPage,
|
|
1698
2133
|
renderStaticPage,
|
|
1699
2134
|
renderStreamingPage,
|
|
2135
|
+
reportException,
|
|
1700
2136
|
resetServerFunctions,
|
|
1701
2137
|
runPostgresMigrations,
|
|
1702
2138
|
runSQLiteMigrations,
|
|
@@ -1708,5 +2144,10 @@ export {
|
|
|
1708
2144
|
scanNotFound,
|
|
1709
2145
|
scanPages,
|
|
1710
2146
|
scanRoutes,
|
|
2147
|
+
setErrorReporter,
|
|
2148
|
+
verifyCsrfToken,
|
|
2149
|
+
verifyOrigin,
|
|
2150
|
+
withCsrfCookie,
|
|
2151
|
+
withRequestLogging,
|
|
1711
2152
|
writeManifest
|
|
1712
2153
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@thexjs/core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.4",
|
|
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",
|
|
@@ -27,16 +27,12 @@
|
|
|
27
27
|
"import": "./dist/index.js"
|
|
28
28
|
}
|
|
29
29
|
},
|
|
30
|
-
"files": [
|
|
31
|
-
"dist",
|
|
32
|
-
"README.md",
|
|
33
|
-
"LICENSE"
|
|
34
|
-
],
|
|
30
|
+
"files": ["dist", "README.md", "LICENSE"],
|
|
35
31
|
"publishConfig": {
|
|
36
32
|
"access": "public"
|
|
37
33
|
},
|
|
38
34
|
"scripts": {
|
|
39
|
-
"build": "tsup src/index.ts --format esm --dts --clean --target node18 --external bun:sqlite",
|
|
35
|
+
"build": "tsup src/index.ts --format esm --dts --clean --target node18 --external bun:sqlite --external react --external react-dom --external react/jsx-runtime",
|
|
40
36
|
"prepublishOnly": "bun run build"
|
|
41
37
|
},
|
|
42
38
|
"peerDependencies": {
|