@thexjs/core 1.10.2 → 1.11.0

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/index.d.ts CHANGED
@@ -340,6 +340,79 @@ declare function buildSecurityHeaders(options?: SecurityHeadersOptions): Headers
340
340
  /** Returns a new Response with security headers merged onto the original response's headers. */
341
341
  declare function applySecurityHeaders(res: Response, options?: SecurityHeadersOptions): Response;
342
342
 
343
+ /**
344
+ * ISR (revalidate) cache with a bounded size and in-flight dedup. In-memory
345
+ * (per-process) by default; pass `store` (see `createRedisIsrCacheStore`) for
346
+ * multi-instance deployments, where purging one replica's local cache isn't
347
+ * enough — `/__x/revalidate` needs to invalidate the HTML every replica
348
+ * shares, not just the one that happened to handle the purge request.
349
+ *
350
+ * Three problems this solves over a plain `Map`:
351
+ *
352
+ * 1. **Unbounded growth** — cached HTML for every distinct URL ever requested
353
+ * would otherwise live for the life of the process. Entries are capped at
354
+ * `maxEntries` and evicted oldest-first (LRU via Map insertion order).
355
+ * (The Redis store has its own bound — a TTL, not an entry cap; see
356
+ * `createRedisIsrCacheStore`.)
357
+ *
358
+ * 2. **Cache stampede** — N concurrent misses for the same URL all ran the
359
+ * loader and rendered. `getOrCompute` shares one in-flight computation
360
+ * across all waiters, so a busy page rebuilds its entry exactly once.
361
+ * This dedup is per-process even with a shared store: two different
362
+ * replicas can still both miss and both recompute once each, same as two
363
+ * independent single-instance deployments would. Closing that too would
364
+ * need a distributed lock, which is a bigger step than what a shared
365
+ * cache store is for.
366
+ *
367
+ * 3. **Cross-replica staleness** — with no shared store, revalidating or
368
+ * purging a path on one instance leaves every sibling instance still
369
+ * serving the old cached HTML until their own TTL naturally expires.
370
+ *
371
+ * Keys are full URLs (pathname + search). The caller is responsible for that
372
+ * contract; see `isrCacheKey`.
373
+ */
374
+ interface StaticCacheEntry {
375
+ html: string;
376
+ timestamp: number;
377
+ /** CSP nonce baked into the inline scripts of `html`; must be reused when serving from cache. */
378
+ cspNonce: string;
379
+ }
380
+ /**
381
+ * A shared backend for ISR cache entries, so `IsrCache` can be backed by
382
+ * Redis (or any other store) instead of a local `Map`. All methods are
383
+ * async, even though the in-memory default resolves synchronously-fast —
384
+ * one uniform interface regardless of backend, the same choice
385
+ * `RateLimitStore` already makes.
386
+ */
387
+ interface IsrCacheStore {
388
+ get(key: string): Promise<StaticCacheEntry | undefined>;
389
+ set(key: string, entry: StaticCacheEntry): Promise<void>;
390
+ delete(key: string): Promise<void>;
391
+ /** Deletes every entry whose pathname matches (query-blind purge); returns the count removed. */
392
+ deletePath(pathname: string): Promise<number>;
393
+ clear(): Promise<void>;
394
+ }
395
+ /**
396
+ * Shared ISR cache store backed by Redis, so `/__x/revalidate` invalidates
397
+ * the HTML every replica serves, not just the one that handled the purge
398
+ * request. Connects lazily on first use and keeps retrying after a failed
399
+ * connection attempt — same lazy-connect contract as
400
+ * `createRedisRateLimitStore`.
401
+ *
402
+ * Entries carry a TTL (default 7 days) so an abandoned URL's cached HTML
403
+ * eventually falls out of Redis on its own, the same reason the in-memory
404
+ * `IsrCache` bounds itself with `maxEntries` -- a shared store needs its own
405
+ * answer to "unbounded growth," since there's no LRU cap to reuse here. The
406
+ * TTL only guards against a replica never requesting a URL again; the
407
+ * app-level `revalidate` staleness check (comparing `entry.timestamp`
408
+ * against `revalidateSeconds`) is unaffected and keeps working exactly as it
409
+ * does for the in-memory store.
410
+ */
411
+ declare function createRedisIsrCacheStore(options?: {
412
+ url?: string;
413
+ ttlSeconds?: number;
414
+ }): IsrCacheStore;
415
+
343
416
  /**
344
417
  * Lightweight fixed-window rate limiter. In-memory by default, keyed by client
345
418
  * IP — good enough for a single-process Bun deployment or as a first line of
@@ -449,6 +522,16 @@ interface CreateAppOptions$1 {
449
522
  headers?: SecurityHeadersOptions | false;
450
523
  /** Rate limiting applied ahead of all routing. Pass false to disable entirely. */
451
524
  rateLimit?: RateLimitOptions | false;
525
+ /**
526
+ * Shared ISR cache store (e.g. `createRedisIsrCacheStore()`) for
527
+ * multi-instance deployments, so `/__x/revalidate` purges the cache
528
+ * every replica serves, not just the one that handled the request.
529
+ * In-memory per-process by default.
530
+ */
531
+ isrCache?: {
532
+ store?: IsrCacheStore;
533
+ maxEntries?: number;
534
+ };
452
535
  };
453
536
  observability?: {
454
537
  /** Structured JSON request logging. Default: true. */
@@ -1119,5 +1202,5 @@ declare function resetServerFunctions(): void;
1119
1202
  declare function registerServerFunctions(routePath: string, paramNames: string[], fns: Record<string, (...args: unknown[]) => Promise<unknown>>): void;
1120
1203
  declare function getServerFunctionHandler(csrfOptions?: CsrfOptions): (req: Request) => Promise<Response | null>;
1121
1204
 
1122
- export { BackpressureOptions, CLIENT_NAV_SCRIPT, DEFAULT_HISTOGRAM_BUCKETS_MS, DEFAULT_MAX_BODY_SIZE, DefaultNotFound, EnvLeakageError, Image, Island, IslandProvider, Link, OTEL_ERROR_STATUS_CODE, PUBLIC_ENV_PREFIX, REDACTED, RequestBodyTooLargeError, SRCSET_WIDTHS, applySecurityHeaders, assertNoEnvLeakage, audit, auditLoginFailure, auditLoginSuccess, auditLogout, auditPasswordChanged, auditPermissionDenied, auditRoleChanged, auditSessionRevoked, build, buildSecurityHeaders, buildSrcSet, checkCsrf, clientIpFromRequest, combineReporters, composeMiddleware, configureTrustedProxy, createApp, createConsoleAuditSink, createHealthCheckHandler, createImageProxyHandler, createInMemoryMetrics, createOtelReporter, createOtlpMetricsReporter, createRateLimiter, createRedisRateLimitStore, createSentryReporter, dbTraceAttributes, defineConfig, enforceRequestBodySize, escapeHtml, findLayoutChain, findLeakedEnvKeys, findMiddlewareChain, generateCsrfToken, generateManifestSource, generateServerFunctionClient, getAuditSink, getErrorReporter, getServerFunctionHandler, getTracer, installProcessCrashHandlers, isSensitiveKey, isTrustedProxy, logger, noopAuditSink, noopMetrics, noopReporter, rateLimitMiddleware, redactString, redactValue, registerServerFunctions, renderErrorOverlay, renderMarkdown, renderPage, renderStaticPage, renderStreamingPage, reportException, requestIdFromRequest, resetServerFunctions, resetTrustedProxy, runWithRequestSpan, scanApiDir, scanContent, scanLayouts, scanLayoutsDir, scanMiddleware, scanNotFound, scanPages, scanRoutes, setAuditSink, setErrorReporter, setImageRemoteHosts, setTracer, tracePhase, tracePhaseSync, traceRequestId, verifyCsrfToken, verifyOrigin, withCsrfCookie, withRequestLogging, withRequestMetrics, withRequestTracing, writeManifest };
1123
- export type { AuditEntry, AuditEvent, AuditSink, BuildOptions, ContentEntry, CounterSeries, CreateAppOptions, CsrfOptions, CsrfResult, ErrorContext, ErrorReporter, Frontmatter, HealthCheck, HealthCheckOptions, HistogramSeries, ImageProps, ImageProxyOptions, InMemoryMetricsOptions, InMemoryMetricsReporter, IslandEntry, IslandMode, LayoutEntry, LinkProps, LoaderArgs, LoaderReturn, LogFields, Logger, MetricLabels, MetricsReporter, MetricsSnapshot, MiddlewareContext, MiddlewareEntry, MiddlewareFn, MiddlewareNext, NotFoundEntry, OtelMeterLike, OtelTracerLike, ProcessCrashHandlerOptions, RateLimitOptions, RateLimitResult, RateLimitStore, ReadinessResult, RevalidateOptions, RouteEntry, RouteMode, RouteProps, SecurityHeadersOptions, SentryLike, TraceSpan, TracerLike, TrustedProxyOptions };
1205
+ export { BackpressureOptions, CLIENT_NAV_SCRIPT, DEFAULT_HISTOGRAM_BUCKETS_MS, DEFAULT_MAX_BODY_SIZE, DefaultNotFound, EnvLeakageError, Image, Island, IslandProvider, Link, OTEL_ERROR_STATUS_CODE, PUBLIC_ENV_PREFIX, REDACTED, RequestBodyTooLargeError, SRCSET_WIDTHS, applySecurityHeaders, assertNoEnvLeakage, audit, auditLoginFailure, auditLoginSuccess, auditLogout, auditPasswordChanged, auditPermissionDenied, auditRoleChanged, auditSessionRevoked, build, buildSecurityHeaders, buildSrcSet, checkCsrf, clientIpFromRequest, combineReporters, composeMiddleware, configureTrustedProxy, createApp, createConsoleAuditSink, createHealthCheckHandler, createImageProxyHandler, createInMemoryMetrics, createOtelReporter, createOtlpMetricsReporter, createRateLimiter, createRedisIsrCacheStore, createRedisRateLimitStore, createSentryReporter, dbTraceAttributes, defineConfig, enforceRequestBodySize, escapeHtml, findLayoutChain, findLeakedEnvKeys, findMiddlewareChain, generateCsrfToken, generateManifestSource, generateServerFunctionClient, getAuditSink, getErrorReporter, getServerFunctionHandler, getTracer, installProcessCrashHandlers, isSensitiveKey, isTrustedProxy, logger, noopAuditSink, noopMetrics, noopReporter, rateLimitMiddleware, redactString, redactValue, registerServerFunctions, renderErrorOverlay, renderMarkdown, renderPage, renderStaticPage, renderStreamingPage, reportException, requestIdFromRequest, resetServerFunctions, resetTrustedProxy, runWithRequestSpan, scanApiDir, scanContent, scanLayouts, scanLayoutsDir, scanMiddleware, scanNotFound, scanPages, scanRoutes, setAuditSink, setErrorReporter, setImageRemoteHosts, setTracer, tracePhase, tracePhaseSync, traceRequestId, verifyCsrfToken, verifyOrigin, withCsrfCookie, withRequestLogging, withRequestMetrics, withRequestTracing, writeManifest };
1206
+ export type { AuditEntry, AuditEvent, AuditSink, BuildOptions, ContentEntry, CounterSeries, CreateAppOptions, CsrfOptions, CsrfResult, ErrorContext, ErrorReporter, Frontmatter, HealthCheck, HealthCheckOptions, HistogramSeries, ImageProps, ImageProxyOptions, InMemoryMetricsOptions, InMemoryMetricsReporter, IslandEntry, IslandMode, IsrCacheStore, LayoutEntry, LinkProps, LoaderArgs, LoaderReturn, LogFields, Logger, MetricLabels, MetricsReporter, MetricsSnapshot, MiddlewareContext, MiddlewareEntry, MiddlewareFn, MiddlewareNext, NotFoundEntry, OtelMeterLike, OtelTracerLike, ProcessCrashHandlerOptions, RateLimitOptions, RateLimitResult, RateLimitStore, ReadinessResult, RevalidateOptions, RouteEntry, RouteMode, RouteProps, SecurityHeadersOptions, SentryLike, TraceSpan, TracerLike, TrustedProxyOptions };
package/dist/index.js CHANGED
@@ -1470,10 +1470,13 @@ var IsrCache = class {
1470
1470
  entries = /* @__PURE__ */ new Map();
1471
1471
  inFlight = /* @__PURE__ */ new Map();
1472
1472
  maxEntries;
1473
- constructor(maxEntries = 500) {
1473
+ store;
1474
+ constructor(maxEntries = 500, store) {
1474
1475
  this.maxEntries = maxEntries;
1476
+ this.store = store;
1475
1477
  }
1476
- get(key) {
1478
+ async get(key) {
1479
+ if (this.store) return this.store.get(key);
1477
1480
  const entry = this.entries.get(key);
1478
1481
  if (entry) {
1479
1482
  this.entries.delete(key);
@@ -1481,19 +1484,33 @@ var IsrCache = class {
1481
1484
  }
1482
1485
  return entry;
1483
1486
  }
1484
- set(key, html, cspNonce) {
1487
+ async set(key, html, cspNonce) {
1488
+ const entry = { html, timestamp: Date.now(), cspNonce };
1489
+ if (this.store) {
1490
+ await this.store.set(key, entry);
1491
+ return;
1492
+ }
1485
1493
  this.entries.delete(key);
1486
- this.entries.set(key, { html, timestamp: Date.now(), cspNonce });
1494
+ this.entries.set(key, entry);
1487
1495
  this.evict();
1488
1496
  }
1489
- delete(key) {
1497
+ async delete(key) {
1498
+ if (this.store) {
1499
+ await this.store.delete(key);
1500
+ return;
1501
+ }
1490
1502
  this.entries.delete(key);
1491
1503
  }
1492
- clear() {
1504
+ async clear() {
1505
+ if (this.store) {
1506
+ await this.store.clear();
1507
+ return;
1508
+ }
1493
1509
  this.entries.clear();
1494
1510
  }
1495
1511
  /** Deletes every entry whose pathname matches (query-blind purge). */
1496
- deletePath(pathname) {
1512
+ async deletePath(pathname) {
1513
+ if (this.store) return this.store.deletePath(pathname);
1497
1514
  let removed = 0;
1498
1515
  for (const key of this.entries.keys()) {
1499
1516
  const url = new URL(key, "http://localhost");
@@ -1504,6 +1521,7 @@ var IsrCache = class {
1504
1521
  }
1505
1522
  return removed;
1506
1523
  }
1524
+ /** In-process entry count. With a shared store, this only reflects in-flight dedup bookkeeping, not the store's size. */
1507
1525
  get size() {
1508
1526
  return this.entries.size;
1509
1527
  }
@@ -1513,14 +1531,14 @@ var IsrCache = class {
1513
1531
  * `Response` returned by `compute` (e.g. a loader redirect) is passed
1514
1532
  * through and never cached.
1515
1533
  */
1516
- getOrCompute(key, compute) {
1517
- const cached = this.get(key);
1518
- if (cached) return Promise.resolve({ html: cached.html, cspNonce: cached.cspNonce });
1534
+ async getOrCompute(key, compute) {
1535
+ const cached = await this.get(key);
1536
+ if (cached) return { html: cached.html, cspNonce: cached.cspNonce };
1519
1537
  const existing = this.inFlight.get(key);
1520
1538
  if (existing) return existing;
1521
- const promise = compute().then((result) => {
1539
+ const promise = compute().then(async (result) => {
1522
1540
  if (result instanceof Response) return result;
1523
- this.set(key, result.html, result.cspNonce);
1541
+ await this.set(key, result.html, result.cspNonce);
1524
1542
  return result;
1525
1543
  }).finally(() => {
1526
1544
  this.inFlight.delete(key);
@@ -1540,6 +1558,96 @@ function isrCacheKey(requestUrl) {
1540
1558
  const url = new URL(requestUrl);
1541
1559
  return url.pathname + url.search;
1542
1560
  }
1561
+ function createBunRedisClient(options) {
1562
+ return async () => {
1563
+ const BunRedis = globalThis.Bun.RedisClient;
1564
+ const instance = options.url ? new BunRedis(options.url) : new BunRedis();
1565
+ await instance.connect();
1566
+ return {
1567
+ sendCommand: (command, ...args) => instance.send(command, args)
1568
+ };
1569
+ };
1570
+ }
1571
+ var REDIS_KEY_PREFIX = "x:isr:";
1572
+ function escapeRedisGlob(value) {
1573
+ return value.replace(/[*?[\]\\]/g, "\\$&");
1574
+ }
1575
+ async function scanKeys(client, pattern) {
1576
+ const found = [];
1577
+ let cursor = "0";
1578
+ do {
1579
+ const reply = await client.sendCommand("SCAN", cursor, "MATCH", pattern, "COUNT", "200");
1580
+ cursor = reply[0];
1581
+ found.push(...reply[1]);
1582
+ } while (cursor !== "0");
1583
+ return found;
1584
+ }
1585
+ function createRedisIsrCacheStore(options = {}) {
1586
+ return createRedisIsrCacheStoreFromClient(createBunRedisClient(options), options.ttlSeconds);
1587
+ }
1588
+ function createRedisIsrCacheStoreFromClient(clientFactory, ttlSeconds = 7 * 24 * 60 * 60) {
1589
+ let client = null;
1590
+ let connecting = null;
1591
+ function getClient() {
1592
+ if (client) return Promise.resolve(client);
1593
+ if (!connecting) {
1594
+ connecting = clientFactory().then(
1595
+ (c) => {
1596
+ client = c;
1597
+ return c;
1598
+ },
1599
+ (err) => {
1600
+ connecting = null;
1601
+ throw err;
1602
+ }
1603
+ );
1604
+ }
1605
+ return connecting;
1606
+ }
1607
+ return {
1608
+ async get(key) {
1609
+ const c = await getClient();
1610
+ const raw = await c.sendCommand("GET", REDIS_KEY_PREFIX + key);
1611
+ if (typeof raw !== "string") return void 0;
1612
+ try {
1613
+ return JSON.parse(raw);
1614
+ } catch {
1615
+ return void 0;
1616
+ }
1617
+ },
1618
+ async set(key, entry) {
1619
+ const c = await getClient();
1620
+ await c.sendCommand(
1621
+ "SET",
1622
+ REDIS_KEY_PREFIX + key,
1623
+ JSON.stringify(entry),
1624
+ "EX",
1625
+ String(ttlSeconds)
1626
+ );
1627
+ },
1628
+ async delete(key) {
1629
+ const c = await getClient();
1630
+ await c.sendCommand("DEL", REDIS_KEY_PREFIX + key);
1631
+ },
1632
+ async deletePath(pathname) {
1633
+ const c = await getClient();
1634
+ const exactKey = REDIS_KEY_PREFIX + pathname;
1635
+ const escapedKey = REDIS_KEY_PREFIX + escapeRedisGlob(pathname);
1636
+ const withQuery = await scanKeys(c, `${escapedKey}\\?*`);
1637
+ const exists = await c.sendCommand("EXISTS", exactKey);
1638
+ const keysToDelete = [...Number(exists) > 0 ? [exactKey] : [], ...withQuery];
1639
+ if (keysToDelete.length === 0) return 0;
1640
+ await c.sendCommand("DEL", ...keysToDelete);
1641
+ return keysToDelete.length;
1642
+ },
1643
+ async clear() {
1644
+ const c = await getClient();
1645
+ const keys = await scanKeys(c, `${REDIS_KEY_PREFIX}*`);
1646
+ if (keys.length === 0) return;
1647
+ await c.sendCommand("DEL", ...keys);
1648
+ }
1649
+ };
1650
+ }
1543
1651
 
1544
1652
  // src/security/trusted-proxy.ts
1545
1653
  var trustForwardedHeaders = false;
@@ -1613,7 +1721,7 @@ async function rateLimitMiddleware(limiter, req, server) {
1613
1721
  }
1614
1722
  });
1615
1723
  }
1616
- function createBunRedisClient(options) {
1724
+ function createBunRedisClient2(options) {
1617
1725
  return async () => {
1618
1726
  const BunRedis = globalThis.Bun.RedisClient;
1619
1727
  const instance = options.url ? new BunRedis(options.url) : new BunRedis();
@@ -1624,7 +1732,7 @@ function createBunRedisClient(options) {
1624
1732
  };
1625
1733
  }
1626
1734
  function createRedisRateLimitStore(options = {}) {
1627
- return createRedisRateLimitStoreFromClient(createBunRedisClient(options));
1735
+ return createRedisRateLimitStoreFromClient(createBunRedisClient2(options));
1628
1736
  }
1629
1737
  var INCR_WITH_WINDOW_SCRIPT = `local c = redis.call('INCR', KEYS[1])
1630
1738
  if redis.call('PTTL', KEYS[1]) == -1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end
@@ -1790,7 +1898,10 @@ async function createApp(options) {
1790
1898
  let notFoundComponent = DefaultNotFound;
1791
1899
  let notFoundLayout;
1792
1900
  const serverFnHandler = getServerFunctionHandler(options.security?.csrf);
1793
- const staticCache = new IsrCache(500);
1901
+ const staticCache = new IsrCache(
1902
+ options.security?.isrCache?.maxEntries ?? 500,
1903
+ options.security?.isrCache?.store
1904
+ );
1794
1905
  let actionModules = /* @__PURE__ */ new Map();
1795
1906
  const islandBundleCache = new BoundedCache(
1796
1907
  options.islandCacheMaxEntries ?? 500
@@ -1967,7 +2078,7 @@ async function createApp(options) {
1967
2078
  }
1968
2079
  const revalidateSeconds = revalidate ?? 0;
1969
2080
  if (revalidateSeconds > 0) {
1970
- const cached = staticCache.get(cacheKey);
2081
+ const cached = await staticCache.get(cacheKey);
1971
2082
  if (cached && Date.now() - cached.timestamp < revalidateSeconds * 1e3) {
1972
2083
  const res2 = new Response(cached.html, {
1973
2084
  headers: {
@@ -1978,7 +2089,7 @@ async function createApp(options) {
1978
2089
  res2.headers.set(CSP_NONCE_HEADER, cached.cspNonce);
1979
2090
  return res2;
1980
2091
  }
1981
- if (cached) staticCache.delete(cacheKey);
2092
+ if (cached) await staticCache.delete(cacheKey);
1982
2093
  }
1983
2094
  const computeHtml = async () => {
1984
2095
  let loaderData = {};
@@ -2323,10 +2434,10 @@ async function createApp(options) {
2323
2434
  return new Response("Invalid JSON body", { status: 400 });
2324
2435
  }
2325
2436
  if (body.path) {
2326
- const removed = staticCache.deletePath(new URL(body.path, "http://localhost").pathname);
2437
+ const removed = await staticCache.deletePath(new URL(body.path, "http://localhost").pathname);
2327
2438
  return new Response(`Revalidated: ${body.path} (${removed} cached variant(s))`);
2328
2439
  }
2329
- staticCache.clear();
2440
+ await staticCache.clear();
2330
2441
  return new Response("Revalidated all");
2331
2442
  }
2332
2443
  async function handleHydrationMismatch(req) {
@@ -3206,6 +3317,7 @@ export {
3206
3317
  createOtelReporter,
3207
3318
  createOtlpMetricsReporter,
3208
3319
  createRateLimiter,
3320
+ createRedisIsrCacheStore,
3209
3321
  createRedisRateLimitStore,
3210
3322
  createSentryReporter,
3211
3323
  dbTraceAttributes,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thexjs/core",
3
- "version": "1.10.2",
3
+ "version": "1.11.0",
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",