@thexjs/core 1.2.2 → 1.2.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/dist/data.js CHANGED
@@ -1,24 +1,72 @@
1
- // src/data/sqlite.ts
2
- var require2 = import.meta.require;
3
- function loadBunSQLite() {
1
+ // src/data/migrate.ts
2
+ import { readdirSync, readFileSync } from "fs";
3
+ import { join } from "path";
4
+ function compareMigrationNames(a, b) {
5
+ const numA = /^(\d+)/.exec(a)?.[1];
6
+ const numB = /^(\d+)/.exec(b)?.[1];
7
+ if (numA !== void 0 && numB !== void 0) {
8
+ const diff = Number(numA) - Number(numB);
9
+ if (diff !== 0) return diff;
10
+ }
11
+ return a < b ? -1 : a > b ? 1 : 0;
12
+ }
13
+ function runSQLiteMigrations(db, migrationsDir) {
14
+ db.run(`CREATE TABLE IF NOT EXISTS _x_migrations (
15
+ name TEXT PRIMARY KEY,
16
+ applied_at TEXT DEFAULT (datetime('now'))
17
+ )`);
18
+ const stmt = db.prepare("SELECT name FROM _x_migrations");
19
+ const applied = new Set(stmt.all().map((r) => r.name));
20
+ let files;
4
21
  try {
5
- return require2("bun:sqlite");
22
+ files = readdirSync(migrationsDir).filter((f) => f.endsWith(".sql")).sort(compareMigrationNames);
6
23
  } catch {
7
- throw new Error(
8
- "connectSQLite requires the Bun runtime (bun:sqlite). Use connectPostgres on non-Bun runtimes like Vercel."
9
- );
24
+ return { applied: [], skipped: [] };
10
25
  }
26
+ const result = { applied: [], skipped: [] };
27
+ for (const file of files) {
28
+ if (applied.has(file)) {
29
+ result.skipped.push(file);
30
+ continue;
31
+ }
32
+ const sql = readFileSync(join(migrationsDir, file), "utf-8");
33
+ db.transaction(() => {
34
+ db.run(sql);
35
+ db.run("INSERT INTO _x_migrations (name) VALUES (?1)", [file]);
36
+ })();
37
+ console.log(`[x] migration applied: ${file}`);
38
+ result.applied.push(file);
39
+ }
40
+ return result;
11
41
  }
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");
42
+ async function runPostgresMigrations(client, migrationsDir) {
43
+ await client.unsafe(`CREATE TABLE IF NOT EXISTS _x_migrations (
44
+ name TEXT PRIMARY KEY,
45
+ applied_at TIMESTAMP DEFAULT NOW()
46
+ )`);
47
+ const rows = await client.unsafe("SELECT name FROM _x_migrations");
48
+ const applied = new Set(rows.map((r) => r.name));
49
+ let files;
50
+ try {
51
+ files = readdirSync(migrationsDir).filter((f) => f.endsWith(".sql")).sort(compareMigrationNames);
52
+ } catch {
53
+ return { applied: [], skipped: [] };
17
54
  }
18
- if (options?.foreignKeys !== false) {
19
- db.run("PRAGMA foreign_keys = ON");
55
+ const result = { applied: [], skipped: [] };
56
+ for (const file of files) {
57
+ if (applied.has(file)) {
58
+ result.skipped.push(file);
59
+ continue;
60
+ }
61
+ const raw = readFileSync(join(migrationsDir, file), "utf-8");
62
+ await client.begin(async (tx) => {
63
+ await tx.unsafe(raw);
64
+ await tx.unsafe("INSERT INTO _x_migrations (name) VALUES ($1)", [file]);
65
+ });
66
+ console.log(`[x] migration applied: ${file}`);
67
+ result.applied.push(file);
20
68
  }
21
- return db;
69
+ return result;
22
70
  }
23
71
 
24
72
  // src/data/postgres.ts
@@ -78,7 +126,12 @@ function connectPostgres(options = {}) {
78
126
  return primed;
79
127
  };
80
128
  const run = async (work) => {
81
- await prime();
129
+ try {
130
+ await prime();
131
+ } catch (error) {
132
+ primed = null;
133
+ throw error;
134
+ }
82
135
  return work();
83
136
  };
84
137
  return new Proxy(sql, {
@@ -99,66 +152,27 @@ function connectPostgres(options = {}) {
99
152
  });
100
153
  }
101
154
 
102
- // src/data/migrate.ts
103
- import { readFileSync, readdirSync } from "fs";
104
- import { join } from "path";
105
- function runSQLiteMigrations(db, migrationsDir) {
106
- db.run(`CREATE TABLE IF NOT EXISTS _x_migrations (
107
- name TEXT PRIMARY KEY,
108
- applied_at TEXT DEFAULT (datetime('now'))
109
- )`);
110
- const stmt = db.prepare("SELECT name FROM _x_migrations");
111
- const applied = new Set(stmt.all().map((r) => r.name));
112
- let files;
155
+ // src/data/sqlite.ts
156
+ var require2 = import.meta.require;
157
+ function loadBunSQLite() {
113
158
  try {
114
- files = readdirSync(migrationsDir).filter((f) => f.endsWith(".sql")).sort();
159
+ return require2("bun:sqlite");
115
160
  } catch {
116
- return { applied: [], skipped: [] };
117
- }
118
- const result = { applied: [], skipped: [] };
119
- for (const file of files) {
120
- if (applied.has(file)) {
121
- result.skipped.push(file);
122
- continue;
123
- }
124
- const sql = readFileSync(join(migrationsDir, file), "utf-8");
125
- db.transaction(() => {
126
- db.run(sql);
127
- db.run("INSERT INTO _x_migrations (name) VALUES (?1)", [file]);
128
- })();
129
- console.log(`[x] migration applied: ${file}`);
130
- result.applied.push(file);
161
+ throw new Error(
162
+ "connectSQLite requires the Bun runtime (bun:sqlite). Use connectPostgres on non-Bun runtimes like Vercel."
163
+ );
131
164
  }
132
- return result;
133
165
  }
134
- async function runPostgresMigrations(client, migrationsDir) {
135
- await client.unsafe(`CREATE TABLE IF NOT EXISTS _x_migrations (
136
- name TEXT PRIMARY KEY,
137
- applied_at TIMESTAMP DEFAULT NOW()
138
- )`);
139
- const rows = await client.unsafe("SELECT name FROM _x_migrations");
140
- const applied = new Set(rows.map((r) => r.name));
141
- let files;
142
- try {
143
- files = readdirSync(migrationsDir).filter((f) => f.endsWith(".sql")).sort();
144
- } catch {
145
- return { applied: [], skipped: [] };
166
+ function connectSQLite(options) {
167
+ const { Database: DB } = loadBunSQLite();
168
+ const db = new DB(options?.path ?? "data/dev.db");
169
+ if (options?.wal !== false) {
170
+ db.run("PRAGMA journal_mode = WAL");
146
171
  }
147
- const result = { applied: [], skipped: [] };
148
- for (const file of files) {
149
- if (applied.has(file)) {
150
- result.skipped.push(file);
151
- continue;
152
- }
153
- const raw = readFileSync(join(migrationsDir, file), "utf-8");
154
- await client.begin(async (tx) => {
155
- await tx.unsafe(raw);
156
- await tx.unsafe("INSERT INTO _x_migrations (name) VALUES ($1)", [file]);
157
- });
158
- console.log(`[x] migration applied: ${file}`);
159
- result.applied.push(file);
172
+ if (options?.foreignKeys !== false) {
173
+ db.run("PRAGMA foreign_keys = ON");
160
174
  }
161
- return result;
175
+ return db;
162
176
  }
163
177
  export {
164
178
  connectPostgres,
package/dist/index.d.ts CHANGED
@@ -1,45 +1,6 @@
1
1
  import * as react from 'react';
2
2
  import { ComponentType, ReactNode, AnchorHTMLAttributes } from 'react';
3
3
 
4
- interface RouteEntry {
5
- filePath: string;
6
- routePath: string;
7
- paramNames: string[];
8
- isApi: boolean;
9
- }
10
- interface MiddlewareEntry {
11
- filePath: string;
12
- dirPath: string;
13
- }
14
- /** Scan page routes — same as scanRoutes but never marks anything as api. */
15
- declare function scanPages(rootDir: string): RouteEntry[];
16
- /** Scan API routes from a separate directory (not nested under pages/routes).
17
- * Route paths are prefixed with /api so they match requests to /api/…. */
18
- declare function scanApiDir(rootDir: string): RouteEntry[];
19
- declare function scanRoutes(rootDir: string): RouteEntry[];
20
- interface LayoutEntry {
21
- filePath: string;
22
- dirPath: string;
23
- }
24
- declare function scanLayouts(rootDir: string): LayoutEntry[];
25
- /**
26
- * Scan a dedicated layouts directory. Every layout file found is registered
27
- * as a root-level layout. The file name becomes the layout key (e.g.
28
- * main.tsx -> "main"), and it covers the root path "/" so it wraps every page.
29
- * Nested _layout.tsx files inside pages/ still work for directory-level
30
- * nesting — this is additive, not exclusive.
31
- */
32
- declare function scanLayoutsDir(layoutsDir: string): LayoutEntry[];
33
- declare function findLayoutChain(routeFilePath: string, layouts: LayoutEntry[], routesDir: string): LayoutEntry[];
34
- interface NotFoundEntry {
35
- filePath: string;
36
- }
37
- declare function scanNotFound(rootDir: string): NotFoundEntry | null;
38
- declare function scanMiddleware(rootDir: string): MiddlewareEntry[];
39
- declare function findMiddlewareChain(routeFilePath: string, middleware: MiddlewareEntry[], routesDir: string): MiddlewareEntry[];
40
- declare function generateManifestSource(routes: RouteEntry[]): string;
41
- declare function writeManifest(routes: RouteEntry[], routesDir: string): string;
42
-
43
4
  type RouteMode = "static" | "server";
44
5
  interface BuildOptions {
45
6
  routesDir?: string;
@@ -60,6 +21,35 @@ interface BuildOptions {
60
21
  }
61
22
  declare function build(options: BuildOptions): Promise<void>;
62
23
 
24
+ /**
25
+ * Inline client-side navigation script.
26
+ *
27
+ * Embedded directly into every rendered page as a <script> tag (see render.ts).
28
+ * Intercepts same-origin <a> clicks, fetches the destination page, and swaps
29
+ * the #root element's content in place. Includes hover-prefetch and popstate
30
+ * (back/forward) support.
31
+ *
32
+ * Opt-out attributes on <a> / <Link />:
33
+ * - data-no-nav — skip client navigation (full page load)
34
+ * - data-no-prefetch — skip hover prefetch (navigation still works)
35
+ */
36
+ declare const CLIENT_NAV_SCRIPT: string;
37
+
38
+ interface Frontmatter {
39
+ title?: string;
40
+ [key: string]: unknown;
41
+ }
42
+ interface ContentEntry {
43
+ filePath: string;
44
+ routePath: string;
45
+ slug: string;
46
+ frontmatter: Frontmatter;
47
+ body: string;
48
+ }
49
+ declare function scanContent(rootDir: string): ContentEntry[];
50
+ declare function escapeHtml(s: string): string;
51
+ declare function renderMarkdown(md: string): string;
52
+
63
53
  /**
64
54
  * Minimal remote-image proxy. Fetches an allow-listed remote image
65
55
  * server-side and streams it back from your own origin at /_x/image, so the
@@ -254,6 +244,45 @@ declare function createOtelReporter(tracer: OtelTracerLike): ErrorReporter;
254
244
  /** Combines multiple reporters — useful for sending to Sentry and OTel at once. */
255
245
  declare function combineReporters(...reporters: ErrorReporter[]): ErrorReporter;
256
246
 
247
+ interface RouteEntry {
248
+ filePath: string;
249
+ routePath: string;
250
+ paramNames: string[];
251
+ isApi: boolean;
252
+ }
253
+ interface MiddlewareEntry {
254
+ filePath: string;
255
+ dirPath: string;
256
+ }
257
+ /** Scan page routes — same as scanRoutes but never marks anything as api. */
258
+ declare function scanPages(rootDir: string): RouteEntry[];
259
+ /** Scan API routes from a separate directory (not nested under pages/routes).
260
+ * Route paths are prefixed with /api so they match requests to /api/…. */
261
+ declare function scanApiDir(rootDir: string): RouteEntry[];
262
+ declare function scanRoutes(rootDir: string): RouteEntry[];
263
+ interface LayoutEntry {
264
+ filePath: string;
265
+ dirPath: string;
266
+ }
267
+ declare function scanLayouts(rootDir: string): LayoutEntry[];
268
+ /**
269
+ * Scan a dedicated layouts directory. Every layout file found is registered
270
+ * as a root-level layout. The file name becomes the layout key (e.g.
271
+ * main.tsx -> "main"), and it covers the root path "/" so it wraps every page.
272
+ * Nested _layout.tsx files inside pages/ still work for directory-level
273
+ * nesting — this is additive, not exclusive.
274
+ */
275
+ declare function scanLayoutsDir(layoutsDir: string): LayoutEntry[];
276
+ declare function findLayoutChain(routeFilePath: string, layouts: LayoutEntry[], routesDir: string): LayoutEntry[];
277
+ interface NotFoundEntry {
278
+ filePath: string;
279
+ }
280
+ declare function scanNotFound(rootDir: string): NotFoundEntry | null;
281
+ declare function scanMiddleware(rootDir: string): MiddlewareEntry[];
282
+ declare function findMiddlewareChain(routeFilePath: string, middleware: MiddlewareEntry[], routesDir: string): MiddlewareEntry[];
283
+ declare function generateManifestSource(routes: RouteEntry[]): string;
284
+ declare function writeManifest(routes: RouteEntry[], routesDir: string): string;
285
+
257
286
  /**
258
287
  * CSRF protection for server actions (`/__x/actions/*`) and other mutating
259
288
  * endpoints. Two independent checks are provided and both run by default:
@@ -492,56 +521,7 @@ interface RevalidateOptions {
492
521
  declare function defineConfig(config: CreateAppOptions): CreateAppOptions;
493
522
  declare function createApp(options: CreateAppOptions): Promise<AppServeOptions>;
494
523
 
495
- declare function DefaultNotFound(_props: RouteProps): react.JSX.Element;
496
-
497
- interface RenderOptions {
498
- title?: string;
499
- islandScripts?: string[];
500
- islandProps?: Record<string, string>;
501
- /** Path to a stylesheet to <link> in <head>, e.g. "/styles.css". */
502
- stylesheet?: string | undefined;
503
- /** Set to false to omit the client-side navigation script. Defaults to true. */
504
- clientNav?: boolean;
505
- /** Inject live-reload script (development mode). */
506
- liveReload?: boolean;
507
- }
508
- interface LoaderArgs {
509
- params: Record<string, string>;
510
- request: Request;
511
- }
512
- type LoaderReturn = Record<string, unknown> | Response;
513
- declare function renderPage(node: ReactNode, options?: RenderOptions): string;
514
- declare function renderStaticPage(node: ReactNode, options?: RenderOptions): string;
515
- declare function renderStreamingPage(node: ReactNode, options?: RenderOptions): Promise<ReadableStream<Uint8Array>>;
516
-
517
- /**
518
- * Inline client-side navigation script.
519
- *
520
- * Embedded directly into every rendered page as a <script> tag (see render.ts).
521
- * Intercepts same-origin <a> clicks, fetches the destination page, and swaps
522
- * the #root element's content in place. Includes hover-prefetch and popstate
523
- * (back/forward) support.
524
- *
525
- * Opt-out attributes on <a> / <Link />:
526
- * - data-no-nav — skip client navigation (full page load)
527
- * - data-no-prefetch — skip hover prefetch (navigation still works)
528
- */
529
- declare const CLIENT_NAV_SCRIPT: string;
530
-
531
- interface Frontmatter {
532
- title?: string;
533
- [key: string]: unknown;
534
- }
535
- interface ContentEntry {
536
- filePath: string;
537
- routePath: string;
538
- slug: string;
539
- frontmatter: Frontmatter;
540
- body: string;
541
- }
542
- declare function scanContent(rootDir: string): ContentEntry[];
543
- declare function escapeHtml(s: string): string;
544
- declare function renderMarkdown(md: string): string;
524
+ declare function renderErrorOverlay(error: unknown): string;
545
525
 
546
526
  type IslandMode = "idle" | "visible" | "load";
547
527
  interface IslandEntry {
@@ -574,12 +554,48 @@ interface LinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href"
574
554
  */
575
555
  declare function Link({ href, children, clientNav, prefetch, ...rest }: LinkProps): react.JSX.Element;
576
556
 
577
- declare function generateServerFunctionClient(routeFilePath: string, fnNames: string[], endpointBase: string): string;
578
- declare function resetServerFunctions(): void;
579
- declare function registerServerFunctions(routePath: string, paramNames: string[], fns: Record<string, (...args: unknown[]) => Promise<unknown>>): void;
580
- declare function getServerFunctionHandler(csrfOptions?: CsrfOptions): (req: Request) => Promise<Response | null>;
557
+ declare function DefaultNotFound(_props: RouteProps): react.JSX.Element;
581
558
 
582
- declare function renderErrorOverlay(error: unknown): string;
559
+ /**
560
+ * Structured JSON logging. Replaces ad-hoc `console.log` with one JSON
561
+ * object per line — easy to ingest into Datadog, Grafana Loki, Kibana, etc.
562
+ */
563
+ interface LogFields {
564
+ [key: string]: unknown;
565
+ }
566
+ interface Logger {
567
+ info(message: string, fields?: LogFields): void;
568
+ warn(message: string, fields?: LogFields): void;
569
+ error(message: string, fields?: LogFields): void;
570
+ }
571
+ declare const logger: Logger;
572
+ /**
573
+ * Wraps a fetch handler so every request is logged as one structured JSON
574
+ * line with `timestamp`, `requestId`, `route`, `status`, and `durationMs`.
575
+ * A second argument (Bun.serve's `server` handle) is forwarded untouched so
576
+ * downstream middleware like the rate limiter can resolve the client IP.
577
+ */
578
+ declare function withRequestLogging<Server = unknown>(handler: (req: Request, server?: Server) => Response | Promise<Response>): (req: Request, server?: Server) => Promise<Response>;
579
+
580
+ interface RenderOptions {
581
+ title?: string;
582
+ islandScripts?: string[];
583
+ islandProps?: Record<string, string>;
584
+ /** Path to a stylesheet to <link> in <head>, e.g. "/styles.css". */
585
+ stylesheet?: string | undefined;
586
+ /** Set to false to omit the client-side navigation script. Defaults to true. */
587
+ clientNav?: boolean;
588
+ /** Inject live-reload script (development mode). */
589
+ liveReload?: boolean;
590
+ }
591
+ interface LoaderArgs {
592
+ params: Record<string, string>;
593
+ request: Request;
594
+ }
595
+ type LoaderReturn = Record<string, unknown> | Response;
596
+ declare function renderPage(node: ReactNode, options?: RenderOptions): string;
597
+ declare function renderStaticPage(node: ReactNode, options?: RenderOptions): string;
598
+ declare function renderStreamingPage(node: ReactNode, options?: RenderOptions): Promise<ReadableStream<Uint8Array>>;
583
599
 
584
600
  /**
585
601
  * Compiler boundary between server-only environment variables and the
@@ -605,25 +621,9 @@ declare class EnvLeakageError extends Error {
605
621
  /** Throws EnvLeakageError if the given bundle source references non-public env vars. */
606
622
  declare function assertNoEnvLeakage(code: string, file: string): void;
607
623
 
608
- /**
609
- * Structured JSON logging. Replaces ad-hoc `console.log` with one JSON
610
- * object per line — easy to ingest into Datadog, Grafana Loki, Kibana, etc.
611
- */
612
- interface LogFields {
613
- [key: string]: unknown;
614
- }
615
- interface Logger {
616
- info(message: string, fields?: LogFields): void;
617
- warn(message: string, fields?: LogFields): void;
618
- error(message: string, fields?: LogFields): void;
619
- }
620
- declare const logger: Logger;
621
- /**
622
- * Wraps a fetch handler so every request is logged as one structured JSON
623
- * line with `timestamp`, `requestId`, `route`, `status`, and `durationMs`.
624
- * A second argument (Bun.serve's `server` handle) is forwarded untouched so
625
- * downstream middleware like the rate limiter can resolve the client IP.
626
- */
627
- declare function withRequestLogging<Server = unknown>(handler: (req: Request, server?: Server) => Response | Promise<Response>): (req: Request, server?: Server) => Promise<Response>;
624
+ declare function generateServerFunctionClient(routeFilePath: string, fnNames: string[], endpointBase: string): string;
625
+ declare function resetServerFunctions(): void;
626
+ declare function registerServerFunctions(routePath: string, paramNames: string[], fns: Record<string, (...args: unknown[]) => Promise<unknown>>): void;
627
+ declare function getServerFunctionHandler(csrfOptions?: CsrfOptions): (req: Request) => Promise<Response | null>;
628
628
 
629
629
  export { type BuildOptions, CLIENT_NAV_SCRIPT, type ContentEntry, type CounterSeries, type CreateAppOptions, type CsrfOptions, type CsrfResult, DEFAULT_HISTOGRAM_BUCKETS_MS, DefaultNotFound, EnvLeakageError, type ErrorContext, type ErrorReporter, type Frontmatter, type HealthCheck, type HealthCheckOptions, type HistogramSeries, type ImageProxyOptions, type InMemoryMetricsOptions, type InMemoryMetricsReporter, Island, type IslandEntry, type IslandMode, IslandProvider, type LayoutEntry, Link, type LinkProps, type LoaderArgs, type LoaderReturn, type LogFields, type Logger, type MetricLabels, type MetricsReporter, type MetricsSnapshot, type MiddlewareContext, type MiddlewareEntry, type MiddlewareFn, type MiddlewareNext, type NotFoundEntry, type OtelMeterLike, 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, createInMemoryMetrics, createOtelReporter, createOtlpMetricsReporter, createRateLimiter, createRedisRateLimitStore, createSentryReporter, defineConfig, escapeHtml, findLayoutChain, findLeakedEnvKeys, findMiddlewareChain, generateCsrfToken, generateManifestSource, generateServerFunctionClient, getErrorReporter, getServerFunctionHandler, logger, noopMetrics, noopReporter, rateLimitMiddleware, registerServerFunctions, renderErrorOverlay, renderMarkdown, renderPage, renderStaticPage, renderStreamingPage, reportException, resetServerFunctions, scanApiDir, scanContent, scanLayouts, scanLayoutsDir, scanMiddleware, scanNotFound, scanPages, scanRoutes, setErrorReporter, verifyCsrfToken, verifyOrigin, withCsrfCookie, withRequestLogging, withRequestMetrics, writeManifest };