@thexjs/core 1.2.1 → 1.2.3

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/adapter.js CHANGED
@@ -8,7 +8,7 @@ import {
8
8
  scanNotFound,
9
9
  scanPages,
10
10
  scanRoutes
11
- } from "./chunk-Y3MLOFAG.js";
11
+ } from "./chunk-O6SIM7EF.js";
12
12
 
13
13
  // src/adapter/scan.ts
14
14
  import { existsSync } from "fs";
@@ -160,12 +160,19 @@ function extractParams(routePath, paramNames, url) {
160
160
  for (const name of paramNames) {
161
161
  const value = match[idx];
162
162
  if (value !== void 0) {
163
- params[name] = value;
163
+ params[name] = safeDecodeURIComponent(value);
164
164
  }
165
165
  idx++;
166
166
  }
167
167
  return params;
168
168
  }
169
+ function safeDecodeURIComponent(value) {
170
+ try {
171
+ return decodeURIComponent(value);
172
+ } catch {
173
+ return value;
174
+ }
175
+ }
169
176
  function generateManifestSource(routes) {
170
177
  const routeEntries = routes.map((r) => {
171
178
  const paramsType = r.paramNames.length === 0 ? "Record<string, never>" : `{ ${r.paramNames.map((n) => `${n}: string`).join("; ")} }`;
package/dist/data.js CHANGED
@@ -78,7 +78,12 @@ function connectPostgres(options = {}) {
78
78
  return primed;
79
79
  };
80
80
  const run = async (work) => {
81
- await prime();
81
+ try {
82
+ await prime();
83
+ } catch (error) {
84
+ primed = null;
85
+ throw error;
86
+ }
82
87
  return work();
83
88
  };
84
89
  return new Proxy(sql, {
@@ -102,6 +107,15 @@ function connectPostgres(options = {}) {
102
107
  // src/data/migrate.ts
103
108
  import { readFileSync, readdirSync } from "fs";
104
109
  import { join } from "path";
110
+ function compareMigrationNames(a, b) {
111
+ const numA = /^(\d+)/.exec(a)?.[1];
112
+ const numB = /^(\d+)/.exec(b)?.[1];
113
+ if (numA !== void 0 && numB !== void 0) {
114
+ const diff = Number(numA) - Number(numB);
115
+ if (diff !== 0) return diff;
116
+ }
117
+ return a < b ? -1 : a > b ? 1 : 0;
118
+ }
105
119
  function runSQLiteMigrations(db, migrationsDir) {
106
120
  db.run(`CREATE TABLE IF NOT EXISTS _x_migrations (
107
121
  name TEXT PRIMARY KEY,
@@ -111,7 +125,7 @@ function runSQLiteMigrations(db, migrationsDir) {
111
125
  const applied = new Set(stmt.all().map((r) => r.name));
112
126
  let files;
113
127
  try {
114
- files = readdirSync(migrationsDir).filter((f) => f.endsWith(".sql")).sort();
128
+ files = readdirSync(migrationsDir).filter((f) => f.endsWith(".sql")).sort(compareMigrationNames);
115
129
  } catch {
116
130
  return { applied: [], skipped: [] };
117
131
  }
@@ -140,7 +154,7 @@ async function runPostgresMigrations(client, migrationsDir) {
140
154
  const applied = new Set(rows.map((r) => r.name));
141
155
  let files;
142
156
  try {
143
- files = readdirSync(migrationsDir).filter((f) => f.endsWith(".sql")).sort();
157
+ files = readdirSync(migrationsDir).filter((f) => f.endsWith(".sql")).sort(compareMigrationNames);
144
158
  } catch {
145
159
  return { applied: [], skipped: [] };
146
160
  }
package/dist/index.js CHANGED
@@ -12,7 +12,7 @@ import {
12
12
  scanPages,
13
13
  scanRoutes,
14
14
  writeManifest
15
- } from "./chunk-Y3MLOFAG.js";
15
+ } from "./chunk-O6SIM7EF.js";
16
16
 
17
17
  // src/not-found.tsx
18
18
  import { jsx, jsxs } from "react/jsx-runtime";
@@ -610,7 +610,6 @@ var ALLOWED_CONTENT_TYPES = /* @__PURE__ */ new Set([
610
610
  "image/jpeg",
611
611
  "image/gif",
612
612
  "image/webp",
613
- "image/svg+xml",
614
613
  "image/avif",
615
614
  "image/x-icon"
616
615
  ]);
@@ -628,15 +627,34 @@ function createImageProxyHandler(options = {}) {
628
627
  } catch {
629
628
  return new Response("invalid url param", { status: 400 });
630
629
  }
631
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:" || !allowedHosts.has(parsed.hostname)) {
630
+ const allowedUrl = (u) => (u.protocol === "http:" || u.protocol === "https:") && allowedHosts.has(u.hostname);
631
+ if (!allowedUrl(parsed)) {
632
632
  return new Response("host not allow-listed for image proxy", { status: 403 });
633
633
  }
634
+ const isRedirect = (status) => status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
634
635
  let upstream;
635
636
  try {
636
- upstream = await fetch(parsed);
637
+ upstream = await fetch(parsed, { redirect: "manual" });
638
+ for (let hop = 0; hop < 5; hop++) {
639
+ if (!isRedirect(upstream.status)) break;
640
+ const location = upstream.headers.get("location");
641
+ let next;
642
+ try {
643
+ next = new URL(location ?? "", parsed);
644
+ } catch {
645
+ return new Response("upstream redirect was not a valid URL", { status: 502 });
646
+ }
647
+ if (!allowedUrl(next)) {
648
+ return new Response("upstream redirected off the allow-list", { status: 403 });
649
+ }
650
+ upstream = await fetch(next, { redirect: "manual" });
651
+ }
637
652
  } catch (err) {
638
653
  return new Response(`upstream fetch failed: ${String(err)}`, { status: 502 });
639
654
  }
655
+ if (isRedirect(upstream.status)) {
656
+ return new Response("too many upstream redirects", { status: 502 });
657
+ }
640
658
  if (!upstream.ok) {
641
659
  return new Response("upstream error", { status: 502 });
642
660
  }
@@ -970,12 +988,19 @@ function extractActionParams(routePath, paramNames, url) {
970
988
  for (const name of paramNames) {
971
989
  const value = match[idx];
972
990
  if (value !== void 0) {
973
- params[name] = value;
991
+ params[name] = safeDecodeURIComponent(value);
974
992
  }
975
993
  idx++;
976
994
  }
977
995
  return params;
978
996
  }
997
+ function safeDecodeURIComponent(value) {
998
+ try {
999
+ return decodeURIComponent(value);
1000
+ } catch {
1001
+ return value;
1002
+ }
1003
+ }
979
1004
 
980
1005
  // src/island-bundle.ts
981
1006
  function actionsRewritePlugin(actionModules) {
@@ -1074,6 +1099,13 @@ async function buildIslandBundleInMemory(routeFilePath, layoutFilePaths, islandN
1074
1099
  assertNoEnvLeakage(code, entryPath);
1075
1100
  return wrapIslandBundle(code);
1076
1101
  } catch (err) {
1102
+ if (err instanceof EnvLeakageError) {
1103
+ console.error(
1104
+ `\x1B[1;31m\u{1F512} SECURITY: [islands] ${err.message}\x1B[0m
1105
+ Falling back to a non-interactive hydration stub \u2014 fix the env isolation (prefix with THEXJS_PUBLIC_ or move the access server-side) before relying on this page's client behavior.`
1106
+ );
1107
+ return wrapIslandBundle(generateFallbackHydration(islandNames));
1108
+ }
1077
1109
  console.warn(` [islands] build failed for ${routeFilePath}:`, err);
1078
1110
  return wrapIslandBundle(generateFallbackHydration(islandNames));
1079
1111
  } finally {
@@ -1480,6 +1512,18 @@ function createRedisRateLimitStoreFromClient(clientFactory) {
1480
1512
  }
1481
1513
 
1482
1514
  // src/createApp.ts
1515
+ function sortRoutes(handlers) {
1516
+ return handlers.sort((a, b) => {
1517
+ const bp = routeMatchesForSort(b.entry);
1518
+ const ap = routeMatchesForSort(a.entry);
1519
+ return ap - bp;
1520
+ });
1521
+ }
1522
+ function routeMatchesForSort(entry) {
1523
+ const isStatic = entry.paramNames.length === 0;
1524
+ const isCatchAll = entry.routePath.includes("*");
1525
+ return isStatic ? 0 : isCatchAll ? 2 : 1;
1526
+ }
1483
1527
  function projectRootFromRoutesDir(routesDir) {
1484
1528
  return join4(routesDir, "..", "..");
1485
1529
  }
@@ -1650,18 +1694,19 @@ async function createApp(options) {
1650
1694
  try {
1651
1695
  const params = extractParams(route.routePath, route.paramNames, new URL(req.url).pathname) ?? {};
1652
1696
  const baseHandler = async (ctx) => {
1653
- let loaderData = {};
1654
- if (loader) {
1655
- const result = await loader(ctx);
1656
- if (result instanceof Response) return result;
1657
- loaderData = result;
1658
- }
1697
+ const cacheKey = new URL(ctx.request.url).pathname;
1659
1698
  if (mode === "server") {
1699
+ let loaderData2 = {};
1700
+ if (loader) {
1701
+ const result = await loader(ctx);
1702
+ if (result instanceof Response) return result;
1703
+ loaderData2 = result;
1704
+ }
1660
1705
  const registry2 = createIslandRegistry();
1661
1706
  const content2 = createElement(
1662
1707
  IslandProvider,
1663
1708
  { registry: registry2 },
1664
- wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
1709
+ wrapWithLayouts(Component, ctx.params, loaderData2, layoutModules)
1665
1710
  );
1666
1711
  let scripts2 = islandScripts;
1667
1712
  if (scripts2 === void 0) {
@@ -1681,12 +1726,23 @@ async function createApp(options) {
1681
1726
  headers: { "Content-Type": "text/html; charset=utf-8" }
1682
1727
  });
1683
1728
  }
1684
- const cached = staticCache.get(route.routePath);
1685
1729
  const revalidateSeconds = revalidate ?? 0;
1686
- if (revalidateSeconds > 0 && cached && Date.now() - cached.timestamp < revalidateSeconds * 1e3) {
1687
- return new Response(cached.html, {
1688
- headers: { "Content-Type": "text/html; charset=utf-8", "X-Revalidated": "hit" }
1689
- });
1730
+ if (revalidateSeconds > 0) {
1731
+ const cached = staticCache.get(cacheKey);
1732
+ if (cached && Date.now() - cached.timestamp < revalidateSeconds * 1e3) {
1733
+ return new Response(cached.html, {
1734
+ headers: {
1735
+ "Content-Type": "text/html; charset=utf-8",
1736
+ "X-Revalidated": "hit"
1737
+ }
1738
+ });
1739
+ }
1740
+ }
1741
+ let loaderData = {};
1742
+ if (loader) {
1743
+ const result = await loader(ctx);
1744
+ if (result instanceof Response) return result;
1745
+ loaderData = result;
1690
1746
  }
1691
1747
  const registry = createIslandRegistry();
1692
1748
  const content = createElement(
@@ -1705,7 +1761,7 @@ async function createApp(options) {
1705
1761
  islandScripts: scripts
1706
1762
  });
1707
1763
  if (revalidateSeconds > 0) {
1708
- staticCache.set(route.routePath, { html, timestamp: Date.now() });
1764
+ staticCache.set(cacheKey, { html, timestamp: Date.now() });
1709
1765
  }
1710
1766
  return new Response(html, {
1711
1767
  headers: {
@@ -1780,7 +1836,7 @@ async function createApp(options) {
1780
1836
  })
1781
1837
  });
1782
1838
  }
1783
- handlers = loaded2;
1839
+ handlers = sortRoutes(loaded2);
1784
1840
  return;
1785
1841
  }
1786
1842
  resetServerFunctions();
@@ -1920,7 +1976,7 @@ async function createApp(options) {
1920
1976
  })
1921
1977
  });
1922
1978
  }
1923
- handlers = loaded;
1979
+ handlers = sortRoutes(loaded);
1924
1980
  if (options.contentDir) {
1925
1981
  const content = scanContent(options.contentDir);
1926
1982
  const loadedContent = content.map((entry) => ({
@@ -1939,6 +1995,10 @@ async function createApp(options) {
1939
1995
  async function handleRevalidation(req) {
1940
1996
  if (new URL(req.url).pathname !== "/__x/revalidate") return null;
1941
1997
  if (req.method !== "POST") return new Response("Method not allowed", { status: 405 });
1998
+ const csrfResult = checkCsrf(req, options.security?.csrf);
1999
+ if (!csrfResult.ok) {
2000
+ return new Response(`Forbidden: ${csrfResult.reason}`, { status: 403 });
2001
+ }
1942
2002
  const body = await req.json();
1943
2003
  if (body.path) {
1944
2004
  staticCache.delete(body.path);
@@ -2353,6 +2413,7 @@ async function bundleRouteIslands(routeFilePath, layoutFilePaths, islandNames, i
2353
2413
  console.warn(` [islands] build error: ${log.message}`);
2354
2414
  }
2355
2415
  } catch (err) {
2416
+ if (err instanceof EnvLeakageError) throw err;
2356
2417
  console.warn(` [islands] build failed for ${routeFilePath}:`, err);
2357
2418
  }
2358
2419
  writeFileSync3(bundlePath, wrapIslandBundle(generateFallbackHydration(islandNames)), "utf-8");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thexjs/core",
3
- "version": "1.2.1",
3
+ "version": "1.2.3",
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",