@thexjs/core 1.3.2 → 1.3.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/adapter.js CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  scanNotFound,
10
10
  scanPages,
11
11
  scanRoutes
12
- } from "./chunk-MYYP67KQ.js";
12
+ } from "./chunk-LV4CJQYM.js";
13
13
 
14
14
  // src/adapter/bundle.ts
15
15
  import { mkdirSync, rmSync, writeFileSync } from "fs";
@@ -436,6 +436,13 @@ function registerServerFunctions(routePath, paramNames, fns) {
436
436
  ACTION_ROUTES.push({ routePath, paramNames, fns: fnMap });
437
437
  }
438
438
  }
439
+ function snapshotActionRoutes() {
440
+ return ACTION_ROUTES.map((entry) => ({
441
+ routePath: entry.routePath,
442
+ paramNames: entry.paramNames,
443
+ fns: new Map(entry.fns)
444
+ }));
445
+ }
439
446
  function getServerFunctionHandler(csrfOptions) {
440
447
  return async (req) => {
441
448
  if (req.method !== "POST") return null;
@@ -450,7 +457,7 @@ function getServerFunctionHandler(csrfOptions) {
450
457
  const actionName = parts.pop();
451
458
  if (!actionName) return null;
452
459
  const concretePath = `/${parts.join("/")}`;
453
- for (const entry of ACTION_ROUTES) {
460
+ for (const entry of snapshotActionRoutes()) {
454
461
  const params = extractActionParams(entry.routePath, entry.paramNames, concretePath);
455
462
  if (params === null) continue;
456
463
  const fn = entry.fns.get(actionName);
package/dist/index.d.ts CHANGED
@@ -514,6 +514,8 @@ interface AppServeOptions {
514
514
  development: boolean;
515
515
  port: number;
516
516
  fetch: (req: Request) => Response | Promise<Response>;
517
+ /** Last-resort error boundary: called when the fetch handler throws. */
518
+ error?: (error: Error) => Response;
517
519
  }
518
520
  interface RevalidateOptions {
519
521
  revalidate?: number;
@@ -570,16 +572,19 @@ interface IslandEntry {
570
572
  name: string;
571
573
  id: string;
572
574
  }
575
+ interface IslandRegistry {
576
+ entries: IslandEntry[];
577
+ /** Per-request id counter, so island ids never cross request boundaries. */
578
+ nextId: number;
579
+ }
573
580
  declare function IslandProvider({ registry, children, }: {
574
- registry: {
575
- entries: IslandEntry[];
576
- };
581
+ registry: IslandRegistry;
577
582
  children?: ReactNode;
578
583
  }): react.JSX.Element;
579
584
  declare function Island({ name, client, children, }: {
580
585
  name: string;
581
586
  client?: IslandMode;
582
- children: ReactNode;
587
+ children?: ReactNode;
583
588
  }): react.JSX.Element;
584
589
 
585
590
  interface LinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href"> {
@@ -629,6 +634,12 @@ interface RenderOptions {
629
634
  clientNav?: boolean;
630
635
  /** Inject live-reload script (development mode). */
631
636
  liveReload?: boolean;
637
+ /**
638
+ * Called when the SSR stream fails mid-flight. Pass this through to
639
+ * `renderStreamingPage` so the app can report the failure via its error
640
+ * reporter/metrics instead of shipping a partial page silently.
641
+ */
642
+ onRenderError?: (error: unknown) => void;
632
643
  }
633
644
  interface LoaderArgs {
634
645
  params: Record<string, string>;
package/dist/index.js CHANGED
@@ -34,7 +34,7 @@ import {
34
34
  verifyOrigin,
35
35
  withCsrfCookie,
36
36
  writeManifest
37
- } from "./chunk-MYYP67KQ.js";
37
+ } from "./chunk-LV4CJQYM.js";
38
38
 
39
39
  // src/build.ts
40
40
  import { cpSync, existsSync, mkdirSync, writeFileSync } from "fs";
@@ -123,11 +123,18 @@ function renderListBlock(block) {
123
123
  var ALLOWED_LINK_SCHEMES = /* @__PURE__ */ new Set(["http", "https", "mailto"]);
124
124
  var LINK_SCHEME_RE = /^([a-z][a-z0-9+.-]*):/i;
125
125
  function decodeLinkUrl(url) {
126
- try {
127
- return decodeURIComponent(url);
128
- } catch {
129
- return url;
126
+ let prev = url;
127
+ for (let i = 0; i < 5; i++) {
128
+ let next;
129
+ try {
130
+ next = decodeURIComponent(prev);
131
+ } catch {
132
+ return prev;
133
+ }
134
+ if (next === prev) return next;
135
+ prev = next;
130
136
  }
137
+ return prev;
131
138
  }
132
139
  function stripUrlControlChars(url) {
133
140
  return url.replace(/[\t\n\r]/g, "");
@@ -169,7 +176,7 @@ function renderMarkdown(md) {
169
176
  import { createContext, useContext } from "react";
170
177
  import { jsx } from "react/jsx-runtime";
171
178
  function createIslandRegistry() {
172
- return { entries: [] };
179
+ return { entries: [], nextId: 0 };
173
180
  }
174
181
  var IslandContext = createContext(null);
175
182
  function IslandProvider({
@@ -178,18 +185,18 @@ function IslandProvider({
178
185
  }) {
179
186
  return /* @__PURE__ */ jsx(IslandContext.Provider, { value: registry, children });
180
187
  }
181
- var islandCounter = 0;
182
188
  function Island({
183
189
  name,
184
190
  client = "idle",
185
191
  children
186
192
  }) {
187
193
  const registry = useContext(IslandContext);
188
- const id = `x-island-${islandCounter++}`;
189
194
  if (registry) {
195
+ const id = `x-island-${registry.nextId++}`;
190
196
  registry.entries.push({ name, id });
197
+ return /* @__PURE__ */ jsx("div", { "data-island": name, "data-island-id": id, "data-island-client": client, children });
191
198
  }
192
- return /* @__PURE__ */ jsx("div", { "data-island": name, "data-island-id": id, "data-island-client": client, children });
199
+ return /* @__PURE__ */ jsx("div", { "data-island": name, "data-island-id": "x-island-0", "data-island-client": client, children });
193
200
  }
194
201
 
195
202
  // src/render.ts
@@ -437,6 +444,55 @@ function renderStaticPage(node, options = {}) {
437
444
  buildLiveReloadTag(options.liveReload)
438
445
  );
439
446
  }
447
+ function pumpStreamingResponse(source, options) {
448
+ const { header, footer, onRenderError, onCancel } = options;
449
+ const reader = source.getReader();
450
+ let headerSent = false;
451
+ let ended = false;
452
+ async function readAhead(controller) {
453
+ if (!headerSent) {
454
+ headerSent = true;
455
+ controller.enqueue(header);
456
+ }
457
+ while (true) {
458
+ const { done, value } = await reader.read();
459
+ if (done) {
460
+ if (!ended) {
461
+ ended = true;
462
+ try {
463
+ controller.enqueue(footer);
464
+ } catch {
465
+ }
466
+ controller.close();
467
+ }
468
+ return;
469
+ }
470
+ controller.enqueue(value);
471
+ if (controller.desiredSize !== null && controller.desiredSize <= 0) return;
472
+ }
473
+ }
474
+ return new ReadableStream({
475
+ async pull(controller) {
476
+ try {
477
+ await readAhead(controller);
478
+ } catch (err) {
479
+ if (!ended) {
480
+ ended = true;
481
+ onRenderError?.(err);
482
+ }
483
+ try {
484
+ controller.error(err);
485
+ } catch {
486
+ }
487
+ }
488
+ },
489
+ cancel(reason) {
490
+ reader.cancel(reason).catch(() => {
491
+ });
492
+ onCancel?.(reason);
493
+ }
494
+ });
495
+ }
440
496
  async function renderStreamingPage(node, options = {}) {
441
497
  const { islandScripts, islandProps } = options;
442
498
  const title = escapeHtml2(options.title ?? "x app");
@@ -467,34 +523,11 @@ ${liveReloadTag} </body>
467
523
  </head>
468
524
  <body>
469
525
  <div id="root">`;
470
- return new ReadableStream({
471
- async start(controller) {
472
- controller.enqueue(encoder.encode(header));
473
- const reader = reactStream.getReader();
474
- async function pump() {
475
- try {
476
- const { done, value } = await reader.read();
477
- if (done) {
478
- controller.enqueue(encoder.encode(`${rootFooter}
479
- ${footer}`));
480
- controller.close();
481
- return;
482
- }
483
- controller.enqueue(value);
484
- await pump();
485
- } catch (err) {
486
- console.error("[x] stream read error:", err);
487
- controller.enqueue(
488
- encoder.encode(
489
- `${rootFooter}<div style="color:red;padding:1em;margin:1rem">Render error: ${err instanceof Error ? err.message : "Unknown"}</div>
490
- ${footer}`
491
- )
492
- );
493
- controller.close();
494
- }
495
- }
496
- await pump();
497
- }
526
+ return pumpStreamingResponse(reactStream, {
527
+ header: encoder.encode(header),
528
+ footer: encoder.encode(`${rootFooter}
529
+ ${footer}`),
530
+ ...options.onRenderError ? { onRenderError: options.onRenderError } : {}
498
531
  });
499
532
  }
500
533
 
@@ -752,7 +785,21 @@ function buildServerEntry(opts, configImportPath, stylesheetHref) {
752
785
  " drainTimer.unref?.();",
753
786
  "}",
754
787
  'process.on("SIGTERM", () => shutdown("SIGTERM"));',
755
- 'process.on("SIGINT", () => shutdown("SIGINT"));'
788
+ 'process.on("SIGINT", () => shutdown("SIGINT"));',
789
+ "",
790
+ "// Request-level errors are caught inside createApp's fetch boundary;",
791
+ "// anything that still escapes (a throw outside the request lifecycle,",
792
+ "// a rejected promise from a background sweep) is routed to the error",
793
+ "// reporter so the box reports instead of dying.",
794
+ 'const { reportException } = await import("@thexjs/core");',
795
+ 'process.on("uncaughtException", (err) => {',
796
+ ' reportException(err, { phase: "api" });',
797
+ ' console.error("[x] uncaught exception:", err);',
798
+ "});",
799
+ 'process.on("unhandledRejection", (reason) => {',
800
+ ' reportException(reason, { phase: "api" });',
801
+ ' console.error("[x] unhandled rejection:", reason);',
802
+ "});"
756
803
  );
757
804
  return lines.join("\n");
758
805
  }
@@ -1304,6 +1351,83 @@ function applySecurityHeaders(res, options = {}) {
1304
1351
  return res;
1305
1352
  }
1306
1353
 
1354
+ // src/security/isr-cache.ts
1355
+ var IsrCache = class {
1356
+ entries = /* @__PURE__ */ new Map();
1357
+ inFlight = /* @__PURE__ */ new Map();
1358
+ maxEntries;
1359
+ constructor(maxEntries = 500) {
1360
+ this.maxEntries = maxEntries;
1361
+ }
1362
+ get(key) {
1363
+ const entry = this.entries.get(key);
1364
+ if (entry) {
1365
+ this.entries.delete(key);
1366
+ this.entries.set(key, entry);
1367
+ }
1368
+ return entry;
1369
+ }
1370
+ set(key, html) {
1371
+ this.entries.delete(key);
1372
+ this.entries.set(key, { html, timestamp: Date.now() });
1373
+ this.evict();
1374
+ }
1375
+ delete(key) {
1376
+ this.entries.delete(key);
1377
+ }
1378
+ clear() {
1379
+ this.entries.clear();
1380
+ }
1381
+ /** Deletes every entry whose pathname matches (query-blind purge). */
1382
+ deletePath(pathname) {
1383
+ let removed = 0;
1384
+ for (const key of this.entries.keys()) {
1385
+ const url = new URL(key, "http://localhost");
1386
+ if (url.pathname === pathname) {
1387
+ this.entries.delete(key);
1388
+ removed++;
1389
+ }
1390
+ }
1391
+ return removed;
1392
+ }
1393
+ get size() {
1394
+ return this.entries.size;
1395
+ }
1396
+ /**
1397
+ * Returns the cached HTML for `key`, or runs `compute` exactly once — even
1398
+ * when multiple callers miss concurrently — and caches the result. A
1399
+ * `Response` returned by `compute` (e.g. a loader redirect) is passed
1400
+ * through and never cached.
1401
+ */
1402
+ getOrCompute(key, compute) {
1403
+ const cached = this.get(key);
1404
+ if (cached) return Promise.resolve(cached.html);
1405
+ const existing = this.inFlight.get(key);
1406
+ if (existing) return existing;
1407
+ const promise = compute().then((result) => {
1408
+ if (typeof result === "string") {
1409
+ this.set(key, result);
1410
+ }
1411
+ return result;
1412
+ }).finally(() => {
1413
+ this.inFlight.delete(key);
1414
+ });
1415
+ this.inFlight.set(key, promise);
1416
+ return promise;
1417
+ }
1418
+ evict() {
1419
+ while (this.entries.size > this.maxEntries) {
1420
+ const oldestKey = this.entries.keys().next().value;
1421
+ if (oldestKey === void 0) break;
1422
+ this.entries.delete(oldestKey);
1423
+ }
1424
+ }
1425
+ };
1426
+ function isrCacheKey(requestUrl) {
1427
+ const url = new URL(requestUrl);
1428
+ return url.pathname + url.search;
1429
+ }
1430
+
1307
1431
  // src/security/rate-limit.ts
1308
1432
  function defaultKeyFn(req, server) {
1309
1433
  if (server?.requestIP) {
@@ -1488,7 +1612,7 @@ async function createApp(options) {
1488
1612
  let notFoundComponent = DefaultNotFound;
1489
1613
  let notFoundLayout;
1490
1614
  const serverFnHandler = getServerFunctionHandler(options.security?.csrf);
1491
- const staticCache = /* @__PURE__ */ new Map();
1615
+ const staticCache = new IsrCache(500);
1492
1616
  let actionModules = /* @__PURE__ */ new Map();
1493
1617
  const islandBundleCache = /* @__PURE__ */ new Map();
1494
1618
  const islandFileCache = /* @__PURE__ */ new Map();
@@ -1588,33 +1712,37 @@ async function createApp(options) {
1588
1712
  try {
1589
1713
  const params = extractParams(route.routePath, route.paramNames, new URL(req.url).pathname) ?? {};
1590
1714
  const baseHandler = async (ctx) => {
1591
- const cacheKey = new URL(ctx.request.url).pathname;
1715
+ const cacheKey = isrCacheKey(ctx.request.url);
1592
1716
  if (mode === "server") {
1593
- let loaderData2 = {};
1717
+ let loaderData = {};
1594
1718
  if (loader) {
1595
1719
  const result = await loader(ctx);
1596
1720
  if (result instanceof Response) return result;
1597
- loaderData2 = result;
1721
+ loaderData = result;
1598
1722
  }
1599
- const registry2 = createIslandRegistry();
1600
- const content2 = createElement2(
1723
+ const registry = createIslandRegistry();
1724
+ const content = createElement2(
1601
1725
  IslandProvider,
1602
- { registry: registry2 },
1603
- wrapWithLayouts(Component, ctx.params, loaderData2, layoutModules)
1726
+ { registry },
1727
+ wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
1604
1728
  );
1605
- let scripts2 = islandScripts;
1606
- if (scripts2 === void 0) {
1607
- renderPage(content2, { stylesheet: stylesheetHref, liveReload: dev });
1608
- scripts2 = await resolveIslandScripts(
1729
+ let scripts = islandScripts;
1730
+ if (scripts === void 0) {
1731
+ renderPage(content, { stylesheet: stylesheetHref, liveReload: dev });
1732
+ scripts = await resolveIslandScripts(
1609
1733
  route.filePath,
1610
1734
  layoutFilePaths,
1611
- registry2.entries
1735
+ registry.entries
1612
1736
  );
1613
1737
  }
1614
- const stream = await renderStreamingPage(content2, {
1738
+ const stream = await renderStreamingPage(content, {
1615
1739
  stylesheet: stylesheetHref,
1616
1740
  liveReload: dev,
1617
- islandScripts: scripts2
1741
+ islandScripts: scripts,
1742
+ onRenderError: (error) => {
1743
+ reportException(error, { route: route.routePath, phase: "ssr" });
1744
+ metricsReporter?.incr("x_http_errors_total", 1, { phase: "ssr" });
1745
+ }
1618
1746
  });
1619
1747
  return new Response(stream, {
1620
1748
  headers: { "Content-Type": "text/html; charset=utf-8" }
@@ -1631,36 +1759,52 @@ async function createApp(options) {
1631
1759
  }
1632
1760
  });
1633
1761
  }
1762
+ if (cached) staticCache.delete(cacheKey);
1634
1763
  }
1635
- let loaderData = {};
1636
- if (loader) {
1637
- const result = await loader(ctx);
1638
- if (result instanceof Response) return result;
1639
- loaderData = result;
1640
- }
1641
- const registry = createIslandRegistry();
1642
- const content = createElement2(
1643
- IslandProvider,
1644
- { registry },
1645
- wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
1646
- );
1647
- let scripts = islandScripts;
1648
- if (scripts === void 0) {
1649
- renderPage(content, { stylesheet: stylesheetHref, liveReload: dev });
1650
- scripts = await resolveIslandScripts(route.filePath, layoutFilePaths, registry.entries);
1651
- }
1652
- const html = renderPage(content, {
1653
- stylesheet: stylesheetHref,
1654
- liveReload: dev,
1655
- islandScripts: scripts
1656
- });
1764
+ const computeHtml = async () => {
1765
+ let loaderData = {};
1766
+ if (loader) {
1767
+ const result = await loader(ctx);
1768
+ if (result instanceof Response) return result;
1769
+ loaderData = result;
1770
+ }
1771
+ const registry = createIslandRegistry();
1772
+ const content = createElement2(
1773
+ IslandProvider,
1774
+ { registry },
1775
+ wrapWithLayouts(Component, ctx.params, loaderData, layoutModules)
1776
+ );
1777
+ let scripts = islandScripts;
1778
+ if (scripts === void 0) {
1779
+ renderPage(content, { stylesheet: stylesheetHref, liveReload: dev });
1780
+ scripts = await resolveIslandScripts(
1781
+ route.filePath,
1782
+ layoutFilePaths,
1783
+ registry.entries
1784
+ );
1785
+ }
1786
+ return renderPage(content, {
1787
+ stylesheet: stylesheetHref,
1788
+ liveReload: dev,
1789
+ islandScripts: scripts
1790
+ });
1791
+ };
1657
1792
  if (revalidateSeconds > 0) {
1658
- staticCache.set(cacheKey, { html, timestamp: Date.now() });
1793
+ const result = await staticCache.getOrCompute(cacheKey, computeHtml);
1794
+ if (result instanceof Response) return result;
1795
+ return new Response(result, {
1796
+ headers: {
1797
+ "Content-Type": "text/html; charset=utf-8",
1798
+ "X-Revalidated": "miss"
1799
+ }
1800
+ });
1659
1801
  }
1802
+ const html = await computeHtml();
1803
+ if (html instanceof Response) return html;
1660
1804
  return new Response(html, {
1661
1805
  headers: {
1662
1806
  "Content-Type": "text/html; charset=utf-8",
1663
- "X-Revalidated": revalidateSeconds > 0 ? "miss" : "none"
1807
+ "X-Revalidated": "none"
1664
1808
  }
1665
1809
  });
1666
1810
  };
@@ -1885,6 +2029,20 @@ async function createApp(options) {
1885
2029
  }
1886
2030
  }
1887
2031
  await buildHandlers();
2032
+ async function guardFetchErrors(inner, req, server) {
2033
+ try {
2034
+ return await inner(req, server);
2035
+ } catch (error) {
2036
+ const path = new URL(req.url).pathname;
2037
+ const phase = path.startsWith("/__x/actions/") ? "action" : path === "/__x/revalidate" ? "api" : "loader";
2038
+ reportException(error, { phase, route: path });
2039
+ const e = error instanceof Error ? error.message : String(error);
2040
+ return new Response(
2041
+ options.development ? `Internal Server Error: ${e}` : "Internal Server Error",
2042
+ { status: 500, headers: { "Content-Type": "text/plain; charset=utf-8" } }
2043
+ );
2044
+ }
2045
+ }
1888
2046
  async function handleRevalidation(req) {
1889
2047
  if (new URL(req.url).pathname !== "/__x/revalidate") return null;
1890
2048
  if (req.method !== "POST") return new Response("Method not allowed", { status: 405 });
@@ -1892,10 +2050,15 @@ async function createApp(options) {
1892
2050
  if (!csrfResult.ok) {
1893
2051
  return new Response(`Forbidden: ${csrfResult.reason}`, { status: 403 });
1894
2052
  }
1895
- const body = await req.json();
2053
+ let body;
2054
+ try {
2055
+ body = await req.json();
2056
+ } catch {
2057
+ return new Response("Invalid JSON body", { status: 400 });
2058
+ }
1896
2059
  if (body.path) {
1897
- staticCache.delete(body.path);
1898
- return new Response(`Revalidated: ${body.path}`);
2060
+ const removed = staticCache.deletePath(new URL(body.path, "http://localhost").pathname);
2061
+ return new Response(`Revalidated: ${body.path} (${removed} cached variant(s))`);
1899
2062
  }
1900
2063
  staticCache.clear();
1901
2064
  return new Response("Revalidated all");
@@ -2035,14 +2198,22 @@ data: ${data}
2035
2198
  }
2036
2199
  return renderNotFound(req);
2037
2200
  };
2038
- const devFetchHardened = async (req, server) => withResponseHardening(await devFetchInner(req, server));
2201
+ const devFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(devFetchInner, req, server));
2039
2202
  const devFetchBase = loggingEnabled ? withRequestLogging(devFetchHardened) : devFetchHardened;
2040
2203
  const devFetch = metricsReporter ? withRequestMetrics(metricsReporter, devFetchBase) : devFetchBase;
2041
2204
  return {
2042
2205
  routes: {},
2043
2206
  development: true,
2044
2207
  port: options.port ?? 3e3,
2045
- fetch: devFetch
2208
+ fetch: devFetch,
2209
+ // Last-resort boundary: `guardFetchErrors` catches exceptions raised
2210
+ // inside routing, but anything thrown by the request-stack wrappers
2211
+ // (logging/metrics/hardening) or by Bun itself still reaches the
2212
+ // process. Returning a 500 here keeps the server up.
2213
+ error: (error) => {
2214
+ reportException(error, { phase: "api" });
2215
+ return new Response("Internal Server Error", { status: 500 });
2216
+ }
2046
2217
  };
2047
2218
  }
2048
2219
  const prodFetchInner = async (req, server) => {
@@ -2083,14 +2254,18 @@ data: ${data}
2083
2254
  }
2084
2255
  return renderNotFound(req);
2085
2256
  };
2086
- const prodFetchHardened = async (req, server) => withResponseHardening(await prodFetchInner(req, server));
2257
+ const prodFetchHardened = async (req, server) => withResponseHardening(await guardFetchErrors(prodFetchInner, req, server));
2087
2258
  const prodFetchBase = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
2088
2259
  const prodFetch = metricsReporter ? withRequestMetrics(metricsReporter, prodFetchBase) : prodFetchBase;
2089
2260
  return {
2090
2261
  routes: {},
2091
2262
  development: false,
2092
2263
  port: options.port ?? 3e3,
2093
- fetch: prodFetch
2264
+ fetch: prodFetch,
2265
+ error: (error) => {
2266
+ reportException(error, { phase: "api" });
2267
+ return new Response("Internal Server Error", { status: 500 });
2268
+ }
2094
2269
  };
2095
2270
  }
2096
2271
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thexjs/core",
3
- "version": "1.3.2",
3
+ "version": "1.3.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",