isr-engine 4.2.0 → 4.3.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.
Files changed (58) hide show
  1. package/README.md +5 -1
  2. package/dist/{contentRevalidation-D3SZwwbX.js → CacheTagContext-Btmq8KCD.js} +20 -7
  3. package/dist/CacheTagContext-Btmq8KCD.js.map +1 -0
  4. package/dist/{abVariantContext-BNInoflb.js → abVariantContext-yWZOqscY.js} +94 -36
  5. package/dist/abVariantContext-yWZOqscY.js.map +1 -0
  6. package/dist/cli/cli.js +1 -1
  7. package/dist/context/CacheTagContext.d.ts +10 -0
  8. package/dist/context/CacheTagContext.d.ts.map +1 -0
  9. package/dist/{createCacheInspectorMiddleware-CDOoJXGO.js → createCacheInspectorMiddleware-glgtcBcQ.js} +2 -2
  10. package/dist/{createCacheInspectorMiddleware-CDOoJXGO.js.map → createCacheInspectorMiddleware-glgtcBcQ.js.map} +1 -1
  11. package/dist/{createCachedFetcher-Y7zbGgjb.js → createCachedFetcher-CgJscexq.js} +29 -10
  12. package/dist/createCachedFetcher-CgJscexq.js.map +1 -0
  13. package/dist/{createISRApp-DA3-5Ezk.js → createISRApp-BG-s3uuL.js} +74 -56
  14. package/dist/createISRApp-BG-s3uuL.js.map +1 -0
  15. package/dist/defaults/runtime/contentRevalidation.d.ts +5 -2
  16. package/dist/defaults/runtime/contentRevalidation.d.ts.map +1 -1
  17. package/dist/defaults/runtime/createCachedFetcher.d.ts +5 -1
  18. package/dist/defaults/runtime/createCachedFetcher.d.ts.map +1 -1
  19. package/dist/defaults/runtime/defineSiteHooks.d.ts +2 -0
  20. package/dist/defaults/runtime/defineSiteHooks.d.ts.map +1 -1
  21. package/dist/defaults/runtime/defineSiteHooks.js +29 -23
  22. package/dist/defaults/runtime/defineSiteHooks.js.map +1 -1
  23. package/dist/defaults/runtime/renderCancellation.d.ts +3 -0
  24. package/dist/defaults/runtime/renderCancellation.d.ts.map +1 -0
  25. package/dist/engine/seo/resolveSeoConfig.d.ts +1 -0
  26. package/dist/engine/seo/resolveSeoConfig.d.ts.map +1 -1
  27. package/dist/isr-engine.js +4 -4
  28. package/dist/plugin/isrCacheMiddleware.d.ts.map +1 -1
  29. package/dist/rsc/browser.js +1 -1
  30. package/dist/rsc/browser.js.map +1 -1
  31. package/dist/rsc/cacheTag.d.ts +1 -8
  32. package/dist/rsc/cacheTag.d.ts.map +1 -1
  33. package/dist/rsc/index.js +3 -2
  34. package/dist/rsc/revalidate.d.ts +3 -2
  35. package/dist/rsc/revalidate.d.ts.map +1 -1
  36. package/dist/{rsc-CbZ-BsWD.js → rsc-BYq2vvnh.js} +2 -2
  37. package/dist/{rsc-CbZ-BsWD.js.map → rsc-BYq2vvnh.js.map} +1 -1
  38. package/dist/server/contentRevalidationRoute.d.ts +4 -0
  39. package/dist/server/contentRevalidationRoute.d.ts.map +1 -0
  40. package/dist/server/opsConfig.d.ts +6 -1
  41. package/dist/server/opsConfig.d.ts.map +1 -1
  42. package/dist/server/productionRuntime.d.ts.map +1 -1
  43. package/dist/server/publishedSitemap.d.ts.map +1 -1
  44. package/dist/types/ISRConfig.d.ts +4 -0
  45. package/dist/types/ISRConfig.d.ts.map +1 -1
  46. package/package.json +2 -2
  47. package/src/context/CacheTagContext.ts +20 -0
  48. package/src/defaults/entry.server.ssr.tsx +10 -0
  49. package/src/defaults/runtime/contentRevalidation.ts +9 -3
  50. package/src/defaults/runtime/createCachedFetcher.ts +45 -10
  51. package/src/defaults/runtime/defineServerEntry.tsx +26 -28
  52. package/src/defaults/runtime/defineSiteHooks.ts +42 -25
  53. package/src/defaults/runtime/renderCancellation.ts +10 -0
  54. package/src/types/ISRConfig.ts +4 -0
  55. package/dist/abVariantContext-BNInoflb.js.map +0 -1
  56. package/dist/contentRevalidation-D3SZwwbX.js.map +0 -1
  57. package/dist/createCachedFetcher-Y7zbGgjb.js.map +0 -1
  58. package/dist/createISRApp-DA3-5Ezk.js.map +0 -1
@@ -1,6 +1,6 @@
1
- import { C as getRequestContext, D as requestContext, T as getTraceId, _ as encodeLogField, a as isUncacheable, b as snapshotLogArgument, g as setOriginLogger, l as contentResponseTargets, m as setRevalidationMetricRecorder, r as collectTags, s as runWithTagStore, u as registerInvalidator, v as encodeSpinnerMessage, w as getRequestId, y as escapeSupplementalLogControls } from "./abVariantContext-BNInoflb.js";
2
- import { n as normalizeContentScopes, r as registerContentInvalidator, t as invalidateContentCaches } from "./contentRevalidation-D3SZwwbX.js";
3
- import { a as getCookieHeader, c as RSC_URL_POSTFIX, d as stripQuery$1, f as stripRscSuffix, i as readLocalePreference, l as contentPathname, o as parseCookieHeader, r as isSupportedLocalePreference, s as readCookie, t as createCachedFetcher, u as normalizePath$1 } from "./createCachedFetcher-Y7zbGgjb.js";
1
+ import { A as isHtmlRoutePattern, C as getRequestId, D as assertDistinctHtmlRouteIdentities, E as requestContext, O as decodeHtmlPathname, S as getRequestContext, _ as encodeSpinnerMessage, a as isUncacheable, c as contentResponseTargets, g as encodeLogField, h as setOriginLogger, k as htmlRouteIdentity, l as registerInvalidator, o as runWithTagStore, p as setRevalidationMetricRecorder, r as collectTags, u as revalidateContent, v as escapeSupplementalLogControls, w as getTraceId, y as snapshotLogArgument } from "./abVariantContext-yWZOqscY.js";
2
+ import { a as registerContentInvalidator, i as normalizeContentScopes, r as invalidateContentCaches } from "./CacheTagContext-Btmq8KCD.js";
3
+ import { a as getCookieHeader, c as RSC_URL_POSTFIX, d as stripQuery$1, f as stripRscSuffix, i as readLocalePreference, l as contentPathname, o as parseCookieHeader, r as isSupportedLocalePreference, s as readCookie, t as createCachedFetcher, u as normalizePath$1 } from "./createCachedFetcher-CgJscexq.js";
4
4
  import { a as selectAcceptableLocale, i as resolveI18nConfig, r as parseLocale } from "./i18n-BZpAOZeO.js";
5
5
  import fs, { createReadStream, promises } from "node:fs";
6
6
  import path from "node:path";
@@ -60,48 +60,6 @@ function resolveImageOptions(images) {
60
60
  });
61
61
  return { remoteAllowlist: [...new Set(hosts)] };
62
62
  }
63
- // src/utils/htmlPathname.ts
64
- /** Shared logical identity for HTML dispatch, aliases and build-time route validation. */
65
- function decodeHtmlPathname(raw) {
66
- const pathname = decodeURIComponent(raw);
67
- if (pathname.includes("\\") || pathname.includes("\0") || pathname.split("/").some((segment) => segment === ".." || segment === ".")) throw new Error("Invalid HTML pathname");
68
- return pathname;
69
- }
70
- function isHtmlRoutePattern(route) {
71
- return route.includes("*") || route.split("/").some((segment) => segment.startsWith(":"));
72
- }
73
- /** Validate the original declaration before a URL parser can repair or normalize it. */
74
- function htmlRouteIdentity(route, { allowPatterns = false } = {}) {
75
- const invalid = (reason) => /* @__PURE__ */ new Error(`Invalid HTML route ${JSON.stringify(route)}: ${reason}`);
76
- if (typeof route !== "string") throw invalid("expected a path string");
77
- if (allowPatterns && route === "*") return route;
78
- if (!(allowPatterns ? /^\/[A-Za-z0-9%\-._~/*:]*$/ : /^\/[A-Za-z0-9%\-._~/]*$/).test(route) || route.startsWith("//")) throw invalid("expected one origin-relative, percent-encoded pathname without query or fragment");
79
- const segments = route.slice(1).split("/");
80
- if (segments.at(-1) === "") segments.pop();
81
- if (segments.some((segment) => !segment)) throw invalid("empty path segment");
82
- let identity;
83
- try {
84
- identity = decodeHtmlPathname(route);
85
- } catch (cause) {
86
- throw new Error(`Invalid HTML route ${JSON.stringify(route)}: malformed or unsafe pathname`, { cause });
87
- }
88
- if (Array.from(identity).some((character) => {
89
- const code = character.charCodeAt(0);
90
- return code < 32 || code === 127;
91
- })) throw invalid("control characters are forbidden");
92
- return identity;
93
- }
94
- /** Exact duplicates are idempotent; matching rules do not own concrete page identities. */
95
- function assertDistinctHtmlRouteIdentities(routes, options = {}) {
96
- const owners = /* @__PURE__ */ new Map();
97
- for (const route of routes) {
98
- const identity = htmlRouteIdentity(route, options);
99
- if (options.allowPatterns && isHtmlRoutePattern(route)) continue;
100
- const owner = owners.get(identity);
101
- if (owner !== void 0 && owner !== route) throw new Error(`Route identity collision: ${JSON.stringify(owner)} and ${JSON.stringify(route)} resolve to ${JSON.stringify(identity)}`);
102
- owners.set(identity, route);
103
- }
104
- }
105
63
  // src/utils/cacheDuration.ts
106
64
  /** Cache deadlines must remain finite, positive (or explicitly zero for SWR) timestamps. */
107
65
  function assertCacheDuration(seconds, label, allowZero = false) {
@@ -1657,7 +1615,7 @@ function resolveFetchHandler(module) {
1657
1615
  }
1658
1616
  var package_default = {
1659
1617
  name: "isr-engine",
1660
- version: "4.2.0",
1618
+ version: "4.3.0",
1661
1619
  description: "ISR/SSG/Fallback rendering orchestration on Vite + React 19 RSC.",
1662
1620
  license: "UNLICENSED",
1663
1621
  repository: {
@@ -1741,7 +1699,7 @@ var package_default = {
1741
1699
  "test": "vitest run",
1742
1700
  "pretest:browser": "pnpm run build",
1743
1701
  "test:browser:production": "pnpm run build && playwright test --config playwright.production.config.ts",
1744
- "test:browser": "playwright test e2e/dev-css-lifecycle/dev-css-lifecycle.spec.ts",
1702
+ "test:browser": "playwright test",
1745
1703
  "bench": "node bench/runner.mjs",
1746
1704
  "check": "pnpm run type-check && pnpm run lint && pnpm run test",
1747
1705
  "audit:security": "pnpm audit --registry=https://registry.npmjs.org --audit-level=low",
@@ -2900,6 +2858,7 @@ async function resolveImportPath(filePath, options) {
2900
2858
  return pathToFileURL$1(filePath).href + (forceReload ? `?t=${Date.now()}` : "");
2901
2859
  }
2902
2860
  // src/server/opsConfig.ts
2861
+ var CONTENT_REVALIDATION_PATH = "/__isr/content/revalidate";
2903
2862
  var opsLimiters = /* @__PURE__ */ new WeakMap();
2904
2863
  var runtimeOpsConfigs = /* @__PURE__ */ new WeakMap();
2905
2864
  /** Carry one resolved policy from the Vite plugin into its owning Express runtime. */
@@ -2984,6 +2943,8 @@ function resolveOpsConfig(config, env) {
2984
2943
  const defaults = env === "production" ? PROD_DEFAULTS : DEV_DEFAULTS;
2985
2944
  const warnings = [];
2986
2945
  const authToken = trimToUndefined(ops?.authToken);
2946
+ const publicationEnabled = env === "production" && ops?.contentRevalidation === true;
2947
+ if (publicationEnabled && !authToken) warnings.push(`${CONTENT_REVALIDATION_PATH} requires server.ops.authToken and was disabled.`);
2987
2948
  return {
2988
2949
  authToken,
2989
2950
  requestLimit: resolveRequestLimitPolicy("ops", config?.server?.requestLimits?.ops),
@@ -2991,6 +2952,10 @@ function resolveOpsConfig(config, env) {
2991
2952
  health: resolveEndpointConfig("health", ops?.health, defaults.health, env, authToken, warnings),
2992
2953
  metrics: resolveEndpointConfig("metrics", ops?.metrics, defaults.metrics, env, authToken, warnings),
2993
2954
  inventory: resolveEndpointConfig("inventory", ops?.inventory, defaults.inventory, env, authToken, warnings),
2955
+ contentRevalidation: {
2956
+ enabled: publicationEnabled && !!authToken,
2957
+ public: false
2958
+ },
2994
2959
  warnings
2995
2960
  };
2996
2961
  }
@@ -4836,7 +4801,7 @@ function createIsrCacheHandler(config, options = {}) {
4836
4801
  scopes: publication.scopes,
4837
4802
  ...protocol && { protocol }
4838
4803
  });
4839
- });
4804
+ }, config?.runtime?.i18n);
4840
4805
  const unsubscribeBus = options.invalidationBus?.subscribe(async (target) => {
4841
4806
  const durable = target.protocol !== "response-v1";
4842
4807
  if (target.kind === "content") {
@@ -4996,7 +4961,7 @@ function createIsrCacheMiddleware(explicitConfig, options = {}) {
4996
4961
  development: true
4997
4962
  }));
4998
4963
  try {
4999
- const inspector = opsConfig.inventory.enabled ? (await import("./createCacheInspectorMiddleware-CDOoJXGO.js")).createCacheInspectorMiddleware(nextHandler, opsConfig) : void 0;
4964
+ const inspector = opsConfig.inventory.enabled ? (await import("./createCacheInspectorMiddleware-glgtcBcQ.js")).createCacheInspectorMiddleware(nextHandler, opsConfig) : void 0;
5000
4965
  handler = nextHandler;
5001
4966
  server.middlewares.use((req, res, next) => {
5002
4967
  if (handler !== nextHandler) return next();
@@ -6647,6 +6612,7 @@ function resolveSitemapLoader(config, engine) {
6647
6612
  const sitemap = engine ?? SEOEngine.getInstance({ baseUrl: resolveSeoConfig(config).baseUrl });
6648
6613
  return {
6649
6614
  ttl: source.ttl ?? seo.ttl,
6615
+ staleIfErrorMs: source.staleIfErrorMs ?? 3e5,
6650
6616
  load: async () => sitemap.generatePublishedSitemap(await source.load({ services: config.runtime.services }))
6651
6617
  };
6652
6618
  }
@@ -7097,6 +7063,50 @@ function createLocaleRedirectMiddleware(options) {
7097
7063
  redirectLocale(res, 302, prefix, path, rscSuffix, req.url);
7098
7064
  };
7099
7065
  }
7066
+ // src/server/contentRevalidationRoute.ts
7067
+ var parsePublication = express.json({
7068
+ limit: "64kb",
7069
+ inflate: false
7070
+ });
7071
+ var requireJson = (req, res, next) => {
7072
+ if (!req.is("application/json")) {
7073
+ res.status(415).json({ error: "Expected application/json" });
7074
+ return;
7075
+ }
7076
+ parsePublication(req, res, next);
7077
+ };
7078
+ var rejectInvalidJson = (error, _req, res, _next) => {
7079
+ const status = error.status === 413 || error.status === 415 ? error.status : 400;
7080
+ res.status(status).json({ error: "Invalid content publication JSON" });
7081
+ };
7082
+ var applyPublication = async (req, res) => {
7083
+ try {
7084
+ await revalidateContent(req.body);
7085
+ res.status(204).end();
7086
+ } catch (error) {
7087
+ if (error instanceof TypeError) {
7088
+ res.status(400).json({ error: error.message });
7089
+ return;
7090
+ }
7091
+ logger$8.error("[Ops] Content revalidation failed", error);
7092
+ res.status(503).json({ error: "Content revalidation unavailable" });
7093
+ }
7094
+ };
7095
+ function mountContentRevalidationRoute(app, ops) {
7096
+ const requirePost = (req, res, next) => {
7097
+ res.set("Cache-Control", "no-store");
7098
+ if (!ops.contentRevalidation.enabled) {
7099
+ res.status(404).end();
7100
+ return;
7101
+ }
7102
+ if (req.method !== "POST") {
7103
+ res.set("Allow", "POST").status(405).end();
7104
+ return;
7105
+ }
7106
+ next();
7107
+ };
7108
+ app.all(CONTENT_REVALIDATION_PATH, requirePost, getOpsRequestLimiter(ops), createOpsAuthMiddleware("contentRevalidation", ops), requireJson, rejectInvalidJson, applyPublication);
7109
+ }
7100
7110
  // src/server/publishedSitemap.ts
7101
7111
  function createPublishedSitemap(config, engine) {
7102
7112
  const source = resolveSitemapLoader(config, engine);
@@ -7104,8 +7114,16 @@ function createPublishedSitemap(config, engine) {
7104
7114
  const cached = createCachedFetcher({
7105
7115
  key: () => "sitemap",
7106
7116
  ttl: source.ttl,
7117
+ staleIfErrorMs: source.staleIfErrorMs,
7107
7118
  max: 1,
7108
- fetch: source.load
7119
+ async fetch() {
7120
+ try {
7121
+ return await source.load();
7122
+ } catch (error) {
7123
+ logger$8.warn("[SEO] Publication sitemap refresh failed", error);
7124
+ throw error;
7125
+ }
7126
+ }
7109
7127
  });
7110
7128
  let generation = 0;
7111
7129
  return {
@@ -7117,9 +7135,8 @@ function createPublishedSitemap(config, engine) {
7117
7135
  const xml = await cached(void 0);
7118
7136
  if (current !== generation) continue;
7119
7137
  if (isOpen()) res.type("application/xml").set("Cache-Control", "no-cache").end(xml);
7120
- } catch (error) {
7138
+ } catch {
7121
7139
  if (current !== generation) continue;
7122
- logger$8.warn("[SEO] Publication sitemap unavailable", error);
7123
7140
  if (isOpen()) res.status(503).type("text/plain").set("Cache-Control", "no-store").end("Sitemap unavailable");
7124
7141
  }
7125
7142
  return;
@@ -7464,12 +7481,13 @@ async function createProductionRuntime(config, options = {}) {
7464
7481
  const app = express();
7465
7482
  app.disable("x-powered-by");
7466
7483
  app.set("trust proxy", config.server.trustProxy ?? false);
7467
- app.use(createProductionJsonMiddleware());
7468
7484
  const opsConfig = resolveOpsConfig(config, "production");
7469
7485
  for (const warning of opsConfig.warnings) logger$8.warn(`[Ops] ${warning}`);
7470
7486
  app.use(createCspNonceMiddleware());
7471
7487
  app.use(createSecurityMiddleware(false, extraConnectSrc));
7472
7488
  app.use(createCompressionMiddleware());
7489
+ mountContentRevalidationRoute(app, opsConfig);
7490
+ app.use(createProductionJsonMiddleware());
7473
7491
  if (extraConnectSrc.length > 0) logger$8.info(`🔒 CSP connect-src 加入:${extraConnectSrc.join(", ")}`);
7474
7492
  const cookieDomain = runtime?.cookieDomain;
7475
7493
  app.use((req, res, next) => {
@@ -7602,7 +7620,7 @@ async function createProductionRuntime(config, options = {}) {
7602
7620
  });
7603
7621
  cleanups.push(() => cache.destroy());
7604
7622
  if (opsConfig.inventory.enabled) {
7605
- const { createCacheInspectorMiddleware } = await import("./createCacheInspectorMiddleware-CDOoJXGO.js");
7623
+ const { createCacheInspectorMiddleware } = await import("./createCacheInspectorMiddleware-glgtcBcQ.js");
7606
7624
  app.use(createCacheInspectorMiddleware(cache, opsConfig));
7607
7625
  logger$8.info("🔍 ISR cache inventory 已启用:GET /__isr/cache/inventory");
7608
7626
  }
@@ -8516,6 +8534,6 @@ async function createISRApp(appOption) {
8516
8534
  shutdown: async () => engine.shutdown()
8517
8535
  };
8518
8536
  }
8519
- export { parseComponents as $, invalidatorRunsTotal as A, InternalStrategies as B, createCoherentCacheStore as C, loadConfig as D, getOpsRequestLimiter as E, getFallbackChain as F, DEFAULT_PORT as G, extractSsgRoutes as H, getRouteFallbackChain as I, DEFAULT_SCAN_CONFIG as J, package_default as K, matchRoutePattern as L, recordHttpRequest as M, createHybridCacheStore as N, createPrometheusMetricsMiddleware as O, createMemoryCacheStore as P, parseComponentFromFile as Q, resolveRenderMode as R, MemoryCacheAdapter as S, createOpsAuthMiddleware as T, spiderSsgRoutes as U, RenderModes as V, logger$8 as W, scanProject as X, scanComponents as Y, scanRoutes as Z, requestPinnedImage as _, closeServer as a, isDev as at, RedisInvalidationBus as b, prepareProductionBuild as c, CacheCleanup as ct, SEOEngine as d, resolveImageOptions as dt, parseRouteFromFile as et, createSEOEngine as f, createImagePlugin as g, createImageMiddleware as h, startAppServer as i, readDirRecursive as it, promRegistry as j, invalidatorFailuresTotal as k, generateStaticCspManifest as l, Logger as lt, mergeSEOConfig as m, ISREngine as n, isCodeFile as nt, startServer as o, isProd as ot, DEFAULT_SEO_CONFIG as p, resolveFetchHandler as q, shutdownServer as r, isTestFile as rt, createProductionRuntime as s, getEnv as st, createISRApp as t, parseRoutes as tt, createABVariantMiddleware as u, assertDistinctHtmlRouteIdentities as ut, createIsrCacheHandler as v, createDevAssetRequestMiddleware as w, RedisCacheAdapter as x, createIsrCacheMiddleware as y, FallbackChain as z };
8537
+ export { parseComponents as $, invalidatorRunsTotal as A, InternalStrategies as B, createCoherentCacheStore as C, loadConfig as D, getOpsRequestLimiter as E, getFallbackChain as F, DEFAULT_PORT as G, extractSsgRoutes as H, getRouteFallbackChain as I, DEFAULT_SCAN_CONFIG as J, package_default as K, matchRoutePattern as L, recordHttpRequest as M, createHybridCacheStore as N, createPrometheusMetricsMiddleware as O, createMemoryCacheStore as P, parseComponentFromFile as Q, resolveRenderMode as R, MemoryCacheAdapter as S, createOpsAuthMiddleware as T, spiderSsgRoutes as U, RenderModes as V, logger$8 as W, scanProject as X, scanComponents as Y, scanRoutes as Z, requestPinnedImage as _, closeServer as a, isDev as at, RedisInvalidationBus as b, prepareProductionBuild as c, CacheCleanup as ct, SEOEngine as d, parseRouteFromFile as et, createSEOEngine as f, createImagePlugin as g, createImageMiddleware as h, startAppServer as i, readDirRecursive as it, promRegistry as j, invalidatorFailuresTotal as k, generateStaticCspManifest as l, Logger as lt, mergeSEOConfig as m, ISREngine as n, isCodeFile as nt, startServer as o, isProd as ot, DEFAULT_SEO_CONFIG as p, resolveFetchHandler as q, shutdownServer as r, isTestFile as rt, createProductionRuntime as s, getEnv as st, createISRApp as t, parseRoutes as tt, createABVariantMiddleware as u, resolveImageOptions as ut, createIsrCacheHandler as v, createDevAssetRequestMiddleware as w, RedisCacheAdapter as x, createIsrCacheMiddleware as y, FallbackChain as z };
8520
8538
 
8521
- //# sourceMappingURL=createISRApp-DA3-5Ezk.js.map
8539
+ //# sourceMappingURL=createISRApp-BG-s3uuL.js.map