@thexjs/core 1.5.0 → 1.6.1

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
@@ -144,6 +144,13 @@ const posts = scanContent("./src/content/blog");
144
144
  const html = renderMarkdown(posts[0].body);
145
145
  ```
146
146
 
147
+ Frontmatter is parsed as **YAML** (via Bun's native parser): nested mappings, block
148
+ scalars (`|`, `>`), `- item` sequences, and scalar type coercion
149
+ (`draft: true` → boolean, `priority: 10` → number) work as expected. A value
150
+ containing `: ` (colon + space) must be quoted. Malformed YAML or a
151
+ non-mapping top-level value throws a build-time error naming the offending
152
+ file instead of being silently dropped.
153
+
147
154
  ## Data layer
148
155
 
149
156
  Thin, typed wrappers over Bun's built-in SQLite and Postgres clients, plus a minimal migration runner. Import from the `@thexjs/core/data` subpath:
@@ -241,6 +248,9 @@ Only variables prefixed `THEXJS_PUBLIC_` may reach the browser. `@thexjs/env`'s
241
248
  | `renderPage`, `renderStaticPage`, `renderStreamingPage`, `LoaderArgs`, `LoaderReturn` | Lower-level render functions |
242
249
  | `scanRoutes`, `scanPages`, `scanApiDir`, `scanLayouts`, `scanLayoutsDir`, `scanMiddleware`, `scanNotFound`, `findLayoutChain`, `findMiddlewareChain`, `generateManifestSource`, `writeManifest` | Routing internals |
243
250
  | `Island`, `IslandProvider`, `IslandMode`, `IslandEntry` | Selective hydration |
251
+ | `Image`, `ImageProps`, `buildSrcSet`, `SRCSET_WIDTHS`, `setImageRemoteHosts` | Optimized image component & srcset builder |
252
+ | `Link`, `LinkProps` | Client-side navigation link component |
253
+ | `createImageProxyHandler`, `ImageProxyOptions` | Remote image proxy handler for `_next/image`-style rewriting |
244
254
  | `scanContent`, `renderMarkdown`, `escapeHtml`, `ContentEntry`, `Frontmatter` | Markdown content collections |
245
255
  | `composeMiddleware`, `MiddlewareContext`, `MiddlewareFn`, `MiddlewareNext` | Middleware |
246
256
  | `registerServerFunctions`, `generateServerFunctionClient`, `getServerFunctionHandler`, `resetServerFunctions` | Server functions/actions internals |
@@ -248,10 +258,13 @@ Only variables prefixed `THEXJS_PUBLIC_` may reach the browser. `@thexjs/env`'s
248
258
  | `DefaultNotFound`, `renderErrorOverlay`, `CLIENT_NAV_SCRIPT` | Defaults / dev tooling |
249
259
  | `checkCsrf`, `verifyOrigin`, `verifyCsrfToken`, `generateCsrfToken`, `withCsrfCookie`, `CsrfOptions`, `CsrfResult` | CSRF protection |
250
260
  | `buildSecurityHeaders`, `applySecurityHeaders`, `SecurityHeadersOptions` | Security response headers (CSP/HSTS/etc.) |
251
- | `createRateLimiter`, `rateLimitMiddleware`, `RateLimitOptions`, `RateLimitResult`, `RateLimitServer`, `createRedisRateLimitStore` | Rate limiting (per-IP fixed window) |
261
+ | `createRateLimiter`, `rateLimitMiddleware`, `RateLimitOptions`, `RateLimitResult`, `RateLimitStore`, `createRedisRateLimitStore` | Rate limiting (per-IP fixed window) |
252
262
  | `findLeakedEnvKeys`, `assertNoEnvLeakage`, `EnvLeakageError`, `PUBLIC_ENV_PREFIX` | Server/client env var isolation |
253
263
  | `logger`, `withRequestLogging`, `Logger`, `LogFields` | Structured JSON logging |
254
264
  | `setErrorReporter`, `getErrorReporter`, `reportException`, `createSentryReporter`, `createOtelReporter`, `combineReporters`, `noopReporter`, `ErrorReporter` | Error reporting (Sentry/OpenTelemetry hook) |
265
+ | `setTracer`, `getTracer`, `runWithRequestSpan`, `tracePhase`, `tracePhaseSync`, `withRequestTracing`, `traceRequestId`, `dbTraceAttributes`, `TracerLike`, `TraceSpan` | Tracing / OpenTelemetry spans |
266
+ | `createInMemoryMetrics`, `createOtlpMetricsReporter`, `withRequestMetrics`, `noopMetrics`, `MetricsReporter`, `CounterSeries`, `HistogramSeries` | Metrics collection (Prometheus/OTLP) |
267
+ | `audit`, `setAuditSink`, `clientIpFromRequest`, `requestIdFromRequest`, `AuditSink`, `AuditEntry` | Audit logging |
255
268
  | `createHealthCheckHandler`, `HealthCheckOptions`, `HealthCheck`, `ReadinessResult` | `/healthz` and `/readyz` |
256
269
 
257
270
  ## License
package/dist/adapter.d.ts CHANGED
@@ -73,6 +73,11 @@ interface ResolvedAction {
73
73
  parentPath: string;
74
74
  paramNames: string[];
75
75
  module: CompiledModuleRef;
76
+ /** Client-visible function names for this action module — the names the
77
+ * island-bundle stub generator emits fetch() calls for. Includes each key
78
+ * of a batched `export const actions = {...}` plus individually-exported
79
+ * functions. */
80
+ fnNames?: string[];
76
81
  }
77
82
  interface BuildManifest {
78
83
  /** The project root the build ran from (used to relativize emitted paths). */
package/dist/adapter.js CHANGED
@@ -9,8 +9,8 @@ import {
9
9
  scanNotFound,
10
10
  scanPages,
11
11
  scanRoutes
12
- } from "./chunk-VC5XI6HX.js";
13
- import "./chunk-VIXLBKMC.js";
12
+ } from "./chunk-KKWPKTJ6.js";
13
+ import "./chunk-OIPCIXYR.js";
14
14
 
15
15
  // src/adapter/bundle.ts
16
16
  import { mkdirSync, rmSync, writeFileSync } from "fs";
@@ -216,15 +216,22 @@ async function resolveBuildManifest(options, scratchDir) {
216
216
  const segments = actionFile.routePath.split("/").filter(Boolean);
217
217
  const fileName = segments[segments.length - 1] ?? "";
218
218
  const parentPath = fileName === "index" || !fileName ? actionFile.routePath : `/${segments.slice(0, -1).join("/")}`;
219
+ const actionMod = await import(actionFile.filePath);
220
+ const fnNames = [];
221
+ const batched = actionMod.actions;
222
+ if (batched) fnNames.push(...Object.keys(batched));
223
+ for (const [key, value] of Object.entries(actionMod)) {
224
+ if (key === "default" || key === "actions" || typeof value !== "function") continue;
225
+ fnNames.push(key);
226
+ }
227
+ if (fnNames.length > 0) {
228
+ actionModules.set(actionFile.filePath, { parentPath, fnNames });
229
+ }
219
230
  actions.push({
220
231
  parentPath,
221
232
  paramNames: actionFile.paramNames,
222
- module: registry.ref(actionFile.filePath, "action")
223
- });
224
- const actionMod = await import(actionFile.filePath);
225
- actionModules.set(actionFile.filePath, {
226
- parentPath,
227
- fnNames: Object.keys(actionMod).filter((k) => k !== "default")
233
+ module: registry.ref(actionFile.filePath, "action"),
234
+ ...fnNames.length > 0 ? { fnNames } : {}
228
235
  });
229
236
  }
230
237
  }
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  OTEL_ERROR_STATUS_CODE,
3
3
  tracePhase
4
- } from "./chunk-VIXLBKMC.js";
4
+ } from "./chunk-OIPCIXYR.js";
5
5
 
6
6
  // src/security/env-isolation.ts
7
7
  var PUBLIC_ENV_PREFIX = "THEXJS_PUBLIC_";
@@ -5,7 +5,7 @@ function isSensitiveKey(key) {
5
5
  return SENSITIVE_KEY_RE.test(key);
6
6
  }
7
7
  function redactString(input) {
8
- return input.replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=:-]+/gi, "$1 " + REDACTED).replace(/\b(authorization|auth)\s*[:=]\s*[^\s,;]+/gi, "$1 " + REDACTED).replace(/(\b[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/\s@:]*:)([^/\s]*)(@)/g, `$1${REDACTED}$3`);
8
+ return input.replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=:-]+/gi, `$1 ${REDACTED}`).replace(/\b(authorization|auth)\s*[:=]\s*[^\s,;]+/gi, `$1 ${REDACTED}`).replace(/(\b[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/\s@:]*:)([^/\s]*)(@)/g, `$1${REDACTED}$3`);
9
9
  }
10
10
  function redactValue(value, depth = 0) {
11
11
  if (typeof value === "string") return redactString(value);
package/dist/data.d.ts CHANGED
@@ -45,16 +45,33 @@ interface PostgresOptions {
45
45
  }
46
46
  declare function connectPostgres(options?: PostgresOptions): PostgresClient;
47
47
 
48
+ interface MigrationOptions {
49
+ /**
50
+ * Behavior when an already-applied migration file has changed on disk.
51
+ * "warn" (default) logs and continues; "fail" aborts the run. Migrations
52
+ * recorded before checksums existed are always treated as "unknown content"
53
+ * and only warned on, never failed.
54
+ */
55
+ onDrift?: "warn" | "fail";
56
+ }
48
57
  interface MigrationResult {
49
58
  applied: string[];
50
59
  skipped: string[];
60
+ /** Already-applied migrations whose file content no longer matches what ran. */
61
+ drifted: string[];
62
+ /** Already-applied migrations recorded before checksums existed. */
63
+ unknownContent: string[];
51
64
  }
52
- declare function runSQLiteMigrations(db: Database, migrationsDir: string): MigrationResult;
65
+ declare function runSQLiteMigrations(db: Database, migrationsDir: string, options?: MigrationOptions): MigrationResult;
53
66
  interface PostgresMigrationResult {
54
67
  applied: string[];
55
68
  skipped: string[];
69
+ /** Already-applied migrations whose file content no longer matches what ran. */
70
+ drifted: string[];
71
+ /** Already-applied migrations recorded before checksums existed. */
72
+ unknownContent: string[];
56
73
  }
57
- declare function runPostgresMigrations(client: PostgresClient, migrationsDir: string): Promise<PostgresMigrationResult>;
74
+ declare function runPostgresMigrations(client: PostgresClient, migrationsDir: string, options?: MigrationOptions): Promise<PostgresMigrationResult>;
58
75
 
59
76
  interface SQLiteOptions {
60
77
  path?: string;
@@ -63,4 +80,4 @@ interface SQLiteOptions {
63
80
  }
64
81
  declare function connectSQLite(options?: SQLiteOptions): Database;
65
82
 
66
- export { type MigrationResult, type PostgresMigrationResult, type PostgresOptions, type SQLiteOptions, connectPostgres, connectSQLite, runPostgresMigrations, runSQLiteMigrations };
83
+ export { type MigrationOptions, type MigrationResult, type PostgresMigrationResult, type PostgresOptions, type SQLiteOptions, connectPostgres, connectSQLite, runPostgresMigrations, runSQLiteMigrations };
package/dist/data.js CHANGED
@@ -2,9 +2,10 @@ import {
2
2
  dbTraceAttributes,
3
3
  tracePhase,
4
4
  tracePhaseSync
5
- } from "./chunk-VIXLBKMC.js";
5
+ } from "./chunk-OIPCIXYR.js";
6
6
 
7
7
  // src/data/migrate.ts
8
+ import { createHash } from "crypto";
8
9
  import { readdirSync, readFileSync } from "fs";
9
10
  import { join } from "path";
10
11
  function compareMigrationNames(a, b) {
@@ -16,29 +17,58 @@ function compareMigrationNames(a, b) {
16
17
  }
17
18
  return a < b ? -1 : a > b ? 1 : 0;
18
19
  }
19
- function runSQLiteMigrations(db, migrationsDir) {
20
+ function hashContent(sql) {
21
+ return createHash("sha256").update(sql).digest("hex");
22
+ }
23
+ function runSQLiteMigrations(db, migrationsDir, options = {}) {
20
24
  db.run(`CREATE TABLE IF NOT EXISTS _x_migrations (
21
25
  name TEXT PRIMARY KEY,
22
- applied_at TEXT DEFAULT (datetime('now'))
26
+ applied_at TEXT DEFAULT (datetime('now')),
27
+ checksum TEXT
23
28
  )`);
24
- const stmt = db.prepare("SELECT name FROM _x_migrations");
25
- const applied = new Set(stmt.all().map((r) => r.name));
29
+ const columns = db.query("PRAGMA table_info(_x_migrations)").all();
30
+ if (!columns.some((c) => c.name === "checksum")) {
31
+ db.run("ALTER TABLE _x_migrations ADD COLUMN checksum TEXT");
32
+ }
33
+ const stmt = db.prepare("SELECT name, checksum FROM _x_migrations");
34
+ const applied = new Map(
35
+ stmt.all().map((r) => [r.name, r.checksum])
36
+ );
26
37
  let files;
27
38
  try {
28
39
  files = readdirSync(migrationsDir).filter((f) => f.endsWith(".sql")).sort(compareMigrationNames);
29
40
  } catch {
30
- return { applied: [], skipped: [] };
41
+ return { applied: [], skipped: [], drifted: [], unknownContent: [] };
31
42
  }
32
- const result = { applied: [], skipped: [] };
43
+ const result = { applied: [], skipped: [], drifted: [], unknownContent: [] };
33
44
  for (const file of files) {
34
45
  if (applied.has(file)) {
35
46
  result.skipped.push(file);
47
+ const stored = applied.get(file) ?? null;
48
+ if (stored === null) {
49
+ result.unknownContent.push(file);
50
+ console.warn(`[x] migration checksum unknown (applied before checksums): ${file}`);
51
+ continue;
52
+ }
53
+ const current = hashContent(readFileSync(join(migrationsDir, file), "utf-8"));
54
+ if (current !== stored) {
55
+ result.drifted.push(file);
56
+ console.warn(`[x] migration changed after being applied: ${file}`);
57
+ if (options.onDrift === "fail") {
58
+ throw new Error(
59
+ `Migration "${file}" was already applied with different content. Refusing to continue (onDrift: "fail").`
60
+ );
61
+ }
62
+ }
36
63
  continue;
37
64
  }
38
65
  const sql = readFileSync(join(migrationsDir, file), "utf-8");
39
66
  db.transaction(() => {
40
67
  db.run(sql);
41
- db.run("INSERT INTO _x_migrations (name) VALUES (?1)", [file]);
68
+ db.run("INSERT INTO _x_migrations (name, checksum) VALUES (?1, ?2)", [
69
+ file,
70
+ hashContent(sql)
71
+ ]);
42
72
  })();
43
73
  console.log(`[x] migration applied: ${file}`);
44
74
  result.applied.push(file);
@@ -46,27 +76,51 @@ function runSQLiteMigrations(db, migrationsDir) {
46
76
  return result;
47
77
  }
48
78
  var MIGRATION_LOCK_KEY = 791975531451977;
49
- async function runPostgresMigrations(client, migrationsDir) {
79
+ async function runPostgresMigrations(client, migrationsDir, options = {}) {
50
80
  let files;
51
81
  try {
52
82
  files = readdirSync(migrationsDir).filter((f) => f.endsWith(".sql")).sort(compareMigrationNames);
53
83
  } catch {
54
- return { applied: [], skipped: [] };
84
+ return { applied: [], skipped: [], drifted: [], unknownContent: [] };
55
85
  }
56
- const result = { applied: [], skipped: [] };
86
+ const result = {
87
+ applied: [],
88
+ skipped: [],
89
+ drifted: [],
90
+ unknownContent: []
91
+ };
57
92
  let failed = null;
58
93
  await client.begin(async (tx) => {
59
94
  await tx.unsafe("SELECT pg_advisory_xact_lock($1)", [MIGRATION_LOCK_KEY]);
60
95
  await tx.unsafe(`CREATE TABLE IF NOT EXISTS _x_migrations (
61
96
  name TEXT PRIMARY KEY,
62
- applied_at TIMESTAMP DEFAULT NOW()
97
+ applied_at TIMESTAMP DEFAULT NOW(),
98
+ checksum TEXT
63
99
  )`);
64
- const rows = await tx.unsafe("SELECT name FROM _x_migrations");
65
- const applied = new Set(rows.map((r) => r.name));
100
+ await tx.unsafe("ALTER TABLE _x_migrations ADD COLUMN IF NOT EXISTS checksum TEXT");
101
+ const rows = await tx.unsafe("SELECT name, checksum FROM _x_migrations");
102
+ const applied = new Map(rows.map((r) => [r.name, r.checksum]));
66
103
  let seq = 0;
67
104
  for (const file of files) {
68
105
  if (applied.has(file)) {
69
106
  result.skipped.push(file);
107
+ const stored = applied.get(file) ?? null;
108
+ if (stored === null) {
109
+ result.unknownContent.push(file);
110
+ console.warn(`[x] migration checksum unknown (applied before checksums): ${file}`);
111
+ continue;
112
+ }
113
+ const current = hashContent(readFileSync(join(migrationsDir, file), "utf-8"));
114
+ if (current !== stored) {
115
+ result.drifted.push(file);
116
+ console.warn(`[x] migration changed after being applied: ${file}`);
117
+ if (options.onDrift === "fail") {
118
+ failed = new Error(
119
+ `Migration "${file}" was already applied with different content. Refusing to continue (onDrift: "fail").`
120
+ );
121
+ break;
122
+ }
123
+ }
70
124
  continue;
71
125
  }
72
126
  if (failed !== null) break;
@@ -75,7 +129,10 @@ async function runPostgresMigrations(client, migrationsDir) {
75
129
  await tx.unsafe(`SAVEPOINT ${savepoint}`);
76
130
  try {
77
131
  await tx.unsafe(raw);
78
- await tx.unsafe("INSERT INTO _x_migrations (name) VALUES ($1)", [file]);
132
+ await tx.unsafe("INSERT INTO _x_migrations (name, checksum) VALUES ($1, $2)", [
133
+ file,
134
+ hashContent(raw)
135
+ ]);
79
136
  await tx.unsafe(`RELEASE SAVEPOINT ${savepoint}`);
80
137
  console.log(`[x] migration applied: ${file}`);
81
138
  result.applied.push(file);
package/dist/index.js CHANGED
@@ -39,7 +39,7 @@ import {
39
39
  verifyOrigin,
40
40
  withCsrfCookie,
41
41
  writeManifest
42
- } from "./chunk-VC5XI6HX.js";
42
+ } from "./chunk-KKWPKTJ6.js";
43
43
  import {
44
44
  OTEL_ERROR_STATUS_CODE,
45
45
  REDACTED,
@@ -54,7 +54,7 @@ import {
54
54
  tracePhaseSync,
55
55
  traceRequestId,
56
56
  withRequestTracing
57
- } from "./chunk-VIXLBKMC.js";
57
+ } from "./chunk-OIPCIXYR.js";
58
58
 
59
59
  // src/build.ts
60
60
  import { cpSync, existsSync, mkdirSync, writeFileSync } from "fs";
@@ -78,7 +78,14 @@ function scanContent(rootDir) {
78
78
  }
79
79
  if (!CONTENT_FILE.test(name)) continue;
80
80
  const raw = readFileSync(full, "utf-8");
81
- const { frontmatter, body } = parseFrontmatter(raw);
81
+ let frontmatter;
82
+ let body;
83
+ try {
84
+ ({ frontmatter, body } = parseFrontmatter(raw));
85
+ } catch (e) {
86
+ const message = e instanceof Error ? e.message : String(e);
87
+ throw new Error(`${message} (in ${full})`);
88
+ }
82
89
  const rel = relative(rootDir, full).replace(CONTENT_FILE, "");
83
90
  const slug = name.replace(CONTENT_FILE, "");
84
91
  const routePath = toContentRoutePath(rel);
@@ -98,35 +105,29 @@ function parseFrontmatter(raw) {
98
105
  if (!trimmed.startsWith("---")) {
99
106
  return { frontmatter: {}, body: trimmed };
100
107
  }
101
- const endIndex = trimmed.indexOf("---", 3);
102
- if (endIndex === -1) {
108
+ const rest = trimmed.slice(3);
109
+ const endMatch = /^---[ \t]*$/m.exec(rest);
110
+ if (endMatch === null) {
103
111
  return { frontmatter: {}, body: trimmed };
104
112
  }
105
- const fmRaw = trimmed.slice(3, endIndex).trim();
106
- const body = trimmed.slice(endIndex + 3).trimStart();
107
- const frontmatter = parseYamlLines(fmRaw);
113
+ const fmRaw = rest.slice(0, endMatch.index);
114
+ const body = rest.slice(endMatch.index + endMatch[0].length).trimStart();
115
+ let frontmatter;
116
+ try {
117
+ frontmatter = parseYaml(fmRaw);
118
+ } catch (e) {
119
+ const message = e instanceof Error ? e.message : String(e);
120
+ throw new Error(`Invalid YAML in frontmatter: ${message}`);
121
+ }
108
122
  return { frontmatter, body };
109
123
  }
110
- function parseYamlLines(raw) {
111
- const result = {};
112
- for (const line of raw.split("\n")) {
113
- const colon = line.indexOf(":");
114
- if (colon === -1) continue;
115
- const key = line.slice(0, colon).trim();
116
- let value = line.slice(colon + 1).trim();
117
- if (typeof value === "string" && value.startsWith('"') && value.endsWith('"')) {
118
- value = value.slice(1, -1);
119
- }
120
- if (typeof value === "string" && value.startsWith("[")) {
121
- try {
122
- value = JSON.parse(value);
123
- } catch {
124
- value = value.slice(1, -1).split(",").map((s) => s.trim()).filter(Boolean);
125
- }
126
- }
127
- result[key] = value;
124
+ function parseYaml(raw) {
125
+ const parsed = Bun.YAML.parse(raw);
126
+ if (parsed === void 0 || parsed === null) return {};
127
+ if (typeof parsed !== "object" || Array.isArray(parsed)) {
128
+ throw new Error("expected a top-level mapping of key/value pairs");
128
129
  }
129
- return result;
130
+ return parsed;
130
131
  }
131
132
  function escapeHtml(s) {
132
133
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thexjs/core",
3
- "version": "1.5.0",
3
+ "version": "1.6.1",
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",