isr-engine 4.1.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 (104) hide show
  1. package/README.md +9 -0
  2. package/dist/CacheTagContext-Btmq8KCD.js +69 -0
  3. package/dist/CacheTagContext-Btmq8KCD.js.map +1 -0
  4. package/dist/{abVariantContext-CGBlCt0q.js → abVariantContext-yWZOqscY.js} +118 -38
  5. package/dist/abVariantContext-yWZOqscY.js.map +1 -0
  6. package/dist/cache/RedisInvalidationBus.d.ts.map +1 -1
  7. package/dist/cache/RedisResponseCacheBackend.d.ts +1 -0
  8. package/dist/cache/RedisResponseCacheBackend.d.ts.map +1 -1
  9. package/dist/cache/ResponseCacheBackend.d.ts +6 -0
  10. package/dist/cache/ResponseCacheBackend.d.ts.map +1 -1
  11. package/dist/cli/cli.js +1 -1
  12. package/dist/config/defineConfig.js +1 -1
  13. package/dist/context/CacheTagContext.d.ts +10 -0
  14. package/dist/context/CacheTagContext.d.ts.map +1 -0
  15. package/dist/{createCacheInspectorMiddleware-D6c-CINz.js → createCacheInspectorMiddleware-glgtcBcQ.js} +2 -2
  16. package/dist/{createCacheInspectorMiddleware-D6c-CINz.js.map → createCacheInspectorMiddleware-glgtcBcQ.js.map} +1 -1
  17. package/dist/createCachedFetcher-CgJscexq.js +186 -0
  18. package/dist/createCachedFetcher-CgJscexq.js.map +1 -0
  19. package/dist/{createISRApp-DTlZvKBm.js → createISRApp-BG-s3uuL.js} +356 -162
  20. package/dist/createISRApp-BG-s3uuL.js.map +1 -0
  21. package/dist/defaults/runtime/contentRevalidation.d.ts +26 -0
  22. package/dist/defaults/runtime/contentRevalidation.d.ts.map +1 -0
  23. package/dist/defaults/runtime/createCachedFetcher.d.ts +8 -2
  24. package/dist/defaults/runtime/createCachedFetcher.d.ts.map +1 -1
  25. package/dist/defaults/runtime/defineSiteHooks.d.ts +4 -7
  26. package/dist/defaults/runtime/defineSiteHooks.d.ts.map +1 -1
  27. package/dist/defaults/runtime/defineSiteHooks.js +655 -2
  28. package/dist/defaults/runtime/defineSiteHooks.js.map +1 -0
  29. package/dist/defaults/runtime/locale-links.client.d.ts.map +1 -1
  30. package/dist/defaults/runtime/renderCancellation.d.ts +3 -0
  31. package/dist/defaults/runtime/renderCancellation.d.ts.map +1 -0
  32. package/dist/engine/ISREngine.d.ts.map +1 -1
  33. package/dist/engine/seo/SEOEngine.d.ts +3 -0
  34. package/dist/engine/seo/SEOEngine.d.ts.map +1 -1
  35. package/dist/engine/seo/resolveSeoConfig.d.ts +6 -0
  36. package/dist/engine/seo/resolveSeoConfig.d.ts.map +1 -1
  37. package/dist/{i18n-B2mWmifk.js → i18n-BZpAOZeO.js} +3 -2
  38. package/dist/{i18n-B2mWmifk.js.map → i18n-BZpAOZeO.js.map} +1 -1
  39. package/dist/index.d.ts +2 -2
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/isr/ISRRoutes.d.ts +2 -0
  42. package/dist/isr/ISRRoutes.d.ts.map +1 -1
  43. package/dist/isr-engine.js +7 -7
  44. package/dist/middlewares/LocaleRedirect.d.ts +4 -3
  45. package/dist/middlewares/LocaleRedirect.d.ts.map +1 -1
  46. package/dist/plugin/coherentCacheStore.d.ts.map +1 -1
  47. package/dist/plugin/isrCacheMiddleware.d.ts +7 -6
  48. package/dist/plugin/isrCacheMiddleware.d.ts.map +1 -1
  49. package/dist/plugin/isrCacheStore.d.ts +2 -0
  50. package/dist/plugin/isrCacheStore.d.ts.map +1 -1
  51. package/dist/rsc/browser.d.ts +3 -0
  52. package/dist/rsc/browser.d.ts.map +1 -1
  53. package/dist/rsc/browser.js +4 -9
  54. package/dist/rsc/browser.js.map +1 -1
  55. package/dist/rsc/cacheTag.d.ts +1 -8
  56. package/dist/rsc/cacheTag.d.ts.map +1 -1
  57. package/dist/rsc/index.d.ts +1 -1
  58. package/dist/rsc/index.d.ts.map +1 -1
  59. package/dist/rsc/index.js +4 -3
  60. package/dist/rsc/revalidate.d.ts +18 -9
  61. package/dist/rsc/revalidate.d.ts.map +1 -1
  62. package/dist/{rsc-DWwcqD4W.js → rsc-BYq2vvnh.js} +2 -2
  63. package/dist/{rsc-DWwcqD4W.js.map → rsc-BYq2vvnh.js.map} +1 -1
  64. package/dist/runtime/LocaleLink.d.ts.map +1 -1
  65. package/dist/runtime/i18n.d.ts +3 -0
  66. package/dist/runtime/i18n.d.ts.map +1 -1
  67. package/dist/runtime/localePreference.d.ts +7 -0
  68. package/dist/runtime/localePreference.d.ts.map +1 -0
  69. package/dist/server/contentRevalidationRoute.d.ts +4 -0
  70. package/dist/server/contentRevalidationRoute.d.ts.map +1 -0
  71. package/dist/server/manager.d.ts.map +1 -1
  72. package/dist/server/opsConfig.d.ts +6 -1
  73. package/dist/server/opsConfig.d.ts.map +1 -1
  74. package/dist/server/productionRuntime.d.ts +2 -0
  75. package/dist/server/productionRuntime.d.ts.map +1 -1
  76. package/dist/server/publishedSitemap.d.ts +8 -0
  77. package/dist/server/publishedSitemap.d.ts.map +1 -0
  78. package/dist/types/ISRConfig.d.ts +27 -0
  79. package/dist/types/ISRConfig.d.ts.map +1 -1
  80. package/dist/utils/cookie.d.ts +2 -2
  81. package/dist/utils/cookie.d.ts.map +1 -1
  82. package/dist/utils/isrPath.d.ts +6 -0
  83. package/dist/utils/isrPath.d.ts.map +1 -0
  84. package/package.json +2 -2
  85. package/src/context/CacheTagContext.ts +20 -0
  86. package/src/defaults/entry.server.ssr.tsx +10 -0
  87. package/src/defaults/runtime/contentRevalidation.ts +96 -0
  88. package/src/defaults/runtime/createCachedFetcher.ts +76 -20
  89. package/src/defaults/runtime/defineServerEntry.tsx +30 -29
  90. package/src/defaults/runtime/defineSiteHooks.ts +117 -80
  91. package/src/defaults/runtime/locale-links.client.ts +14 -4
  92. package/src/defaults/runtime/renderCancellation.ts +10 -0
  93. package/src/runtime/LocaleLink.tsx +8 -2
  94. package/src/runtime/i18n.ts +4 -0
  95. package/src/runtime/localePreference.ts +36 -0
  96. package/src/types/ISRConfig.ts +29 -0
  97. package/src/utils/cookie.ts +11 -4
  98. package/src/utils/isrPath.ts +24 -0
  99. package/dist/abVariantContext-CGBlCt0q.js.map +0 -1
  100. package/dist/cookie-DcUeYm6E.js +0 -42
  101. package/dist/cookie-DcUeYm6E.js.map +0 -1
  102. package/dist/createISRApp-DTlZvKBm.js.map +0 -1
  103. package/dist/defineSiteHooks-iwLiVChy.js +0 -716
  104. package/dist/defineSiteHooks-iwLiVChy.js.map +0 -1
@@ -31,7 +31,9 @@
31
31
  * });
32
32
  */
33
33
  import { trimTrailingSlashes } from '../../utils/trimTrailingSlashes';
34
+ import { contentPathname, RSC_URL_POSTFIX } from '../../utils/isrPath';
34
35
  import { createCachedFetcher } from './createCachedFetcher';
36
+ import { registerContentInvalidator } from './contentRevalidation';
35
37
  import type { IntlPayload, PageSeoMeta } from './seo-runtime';
36
38
  import type {
37
39
  DynamicSeoResolver,
@@ -46,16 +48,22 @@ import {
46
48
  resolveI18nConfig,
47
49
  type I18nConfig,
48
50
  } from '../../runtime/i18n';
51
+ import { readLocalePreference } from '../../runtime/localePreference';
52
+ import { markUncacheable } from '../../context/CacheTagContext';
49
53
 
50
54
  export { getCookieHeader, parseCookieHeader, readCookie } from '../../utils/cookie';
51
55
 
52
56
  export type SiteRuntimeConfig = ISRConfig['runtime'];
53
57
 
58
+ const CONTENT_INVALIDATOR = Symbol('contentInvalidator');
59
+ const MARK_METADATA_DEGRADED = Symbol('markMetadataDegraded');
60
+
54
61
  export interface SiteRuntimeContext {
55
62
  runtime: SiteRuntimeConfig;
56
63
  services: RuntimeServices;
57
64
  telemetry?: string;
58
65
  site?: string;
66
+ [MARK_METADATA_DEGRADED]?: () => void;
59
67
  }
60
68
 
61
69
  export interface RuntimeServices {
@@ -139,15 +147,7 @@ export interface DefineAdminSiteHooksOptions {
139
147
  headExtras?: SiteHooksConfig['headExtras'];
140
148
  }
141
149
 
142
- export interface IntlConfig {
143
- // ─── URL 路由层(被 parseLocale / withLocale 等消费)───────────
144
- /** 支持的 locale 列表,如 ['zh', 'en'];用于 URL 前缀解析 */
145
- locales?: readonly string[];
146
- /** 默认 locale —— 必须在 locales 内;同时作为 detect 失败的兜底 */
147
- defaultLocale?: string;
148
- /** 默认 locale 是否带 URL 前缀(默认 false:'/about';true:'/zh/about') */
149
- prefixDefault?: boolean;
150
-
150
+ export interface IntlConfig extends Partial<I18nConfig> {
151
151
  // ─── 翻译消息加载层(被 SEO/Header 等消费)─────────────────────
152
152
  /** 远程 endpoint;`{locale}` 占位符自动替换 */
153
153
  endpoint?: string;
@@ -251,8 +251,14 @@ interface CompiledSeoPattern {
251
251
  paramNames: string[];
252
252
  }
253
253
 
254
+ interface SeoRouteRequest {
255
+ pathname: string;
256
+ locale: string;
257
+ params: Record<string, string>;
258
+ }
259
+
254
260
  interface CompiledRoute extends CompiledSeoPattern {
255
- resolver: (params: Record<string, string>) => Promise<PageSeoMeta | null> | PageSeoMeta | null;
261
+ resolver: (request: SeoRouteRequest) => Promise<PageSeoMeta | null> | PageSeoMeta | null;
256
262
  }
257
263
 
258
264
  function escapeSeoPatternLiteral(literal: string): string {
@@ -299,7 +305,7 @@ export function createAdminIntlLoader(
299
305
  : locale;
300
306
  const remoteUrl = resolveAdminUrl(endpoint, { locale: normalizedLocale }, ctx);
301
307
  const remote = remoteUrl
302
- ? await fetchJsonWithTimeout<unknown>(remoteUrl, options.timeoutMs)
308
+ ? await fetchMetadataJson(remoteUrl, options.timeoutMs, ctx[MARK_METADATA_DEGRADED])
303
309
  : null;
304
310
  const remoteMessages = extractIntlMessagesOrNull(remote);
305
311
  const localMessages =
@@ -336,7 +342,7 @@ export function createAdminSeoLoader(
336
342
  // 1. admin endpoint —— 运营在 dashboard 给具体 path 配过的覆盖优先级最高
337
343
  const remoteUrl = resolveAdminUrl(endpoint, { ...params, pathname }, ctx);
338
344
  const remote = remoteUrl
339
- ? await fetchJsonWithTimeout<unknown>(remoteUrl, options.timeoutMs)
345
+ ? await fetchMetadataJson(remoteUrl, options.timeoutMs, ctx[MARK_METADATA_DEGRADED])
340
346
  : null;
341
347
  const remoteMeta = extractSeoMetaOrNull(remote);
342
348
  if (remoteMeta) return remoteMeta;
@@ -359,6 +365,7 @@ export function createAdminSeoLoader(
359
365
  });
360
366
  if (result) return result as PageSeoMeta;
361
367
  } catch (err) {
368
+ ctx[MARK_METADATA_DEGRADED]?.();
362
369
  // resolver 抛错不阻塞渲染:业务异常时把 SEO 当 null 处理
363
370
  console.warn('[seo] dynamic resolver threw, falling through to fallback', err);
364
371
  }
@@ -552,26 +559,26 @@ function createSiteHooks(config: SiteHooksConfig, runtime: SiteRuntimeConfig): S
552
559
  telemetry: services.telemetry,
553
560
  site: site || undefined,
554
561
  };
555
- const fetchJson = async (path: string, baseUrl?: string): Promise<unknown> => {
556
- try {
557
- if (!baseUrl) return null;
558
- const r = await fetch(baseUrl + path);
559
- if (!r.ok) return null;
560
- return await r.json();
561
- } catch {
562
- return null;
563
- }
564
- };
562
+ const metadataContext = (markDegraded?: () => void): SiteRuntimeContext => ({
563
+ ...runtimeCtx,
564
+ [MARK_METADATA_DEGRADED]: markDegraded,
565
+ });
566
+ const fetchJson = (path: string, markDegraded?: () => void) =>
567
+ api ? fetchMetadataJson(api + path, null, markDegraded) : Promise.resolve(null);
565
568
 
566
569
  // ─── i18n 缓存(一次创建,请求级复用)──────────────
567
- const intlCfg = config.intl ?? {};
570
+ const runtimeLocale = runtime.i18n;
571
+ const rememberLocale = runtimeLocale?.prefixDefault && runtimeLocale.rememberLocale;
572
+ const intlCfg = rememberLocale
573
+ ? { ...config.intl, ...resolveI18nConfig(runtimeLocale) }
574
+ : (config.intl ?? {});
568
575
  const supportedLocales = intlCfg.locales?.length ? intlCfg.locales : undefined;
569
576
  const negotiationConfig = supportedLocales
570
577
  ? resolveI18nConfig(intlCfg)
571
578
  : { locales: ['zh-CN', 'en'], defaultLocale: intlCfg.defaultLocale ?? 'zh-CN' };
572
579
  // 默认 detect 优先级(业界标准 i18n 顺序):
573
580
  // 1. URL pathname 前缀 /en-US/... → 'en-US' ← 显式路由意图,最高优先级
574
- // 2. locale cookie ← 用户手动切换过的偏好
581
+ // 2. engine locale preference on the unprefixed root / legacy locale cookie
575
582
  // 3. Accept-Language 头 ← 浏览器系统语言
576
583
  // 4. defaultLocale ← 兜底
577
584
  //
@@ -595,6 +602,10 @@ function createSiteHooks(config: SiteHooksConfig, runtime: SiteRuntimeConfig): S
595
602
  : pathname;
596
603
  const first = cleanPath.split('/')[1];
597
604
  if (first && supportedLocales.includes(first)) return first;
605
+ if (cleanPath === '/' && rememberLocale && runtimeLocale) {
606
+ const preference = readLocalePreference(req, runtimeLocale);
607
+ if (preference) return preference;
608
+ }
598
609
  } catch {
599
610
  // 非法 URL(极少见,比如内部调用喂了相对路径)→ 继续后续策略
600
611
  }
@@ -615,14 +626,15 @@ function createSiteHooks(config: SiteHooksConfig, runtime: SiteRuntimeConfig): S
615
626
  key: locale => `intl:${locale}`,
616
627
  ttl: intlCfg.ttl ?? 60_000,
617
628
  swr: true,
618
- fetch: async locale => {
629
+ onDegraded: markUncacheable,
630
+ fetch: async (locale, markDegraded) => {
619
631
  if (intlCfg.load) {
620
- const r = await intlCfg.load(locale, runtimeCtx);
632
+ const r = await intlCfg.load(locale, metadataContext(markDegraded));
621
633
  return r ?? { locale, messages: {}, direction: rtlOf(locale) };
622
634
  }
623
635
  if (intlCfg.endpoint) {
624
636
  const url = fillTemplate(intlCfg.endpoint, { locale });
625
- const json = await fetchJson(url, services.api);
637
+ const json = await fetchJson(url, markDegraded);
626
638
  if (json !== null && intlCfg.transform) {
627
639
  const transformed = await intlCfg.transform(json, locale);
628
640
  if (transformed) {
@@ -645,57 +657,53 @@ function createSiteHooks(config: SiteHooksConfig, runtime: SiteRuntimeConfig): S
645
657
 
646
658
  // ─── SEO 路由表编译 + 远程 loader 缓存(每个 pattern 一份)─────
647
659
  const seoRoutes: CompiledRoute[] = [];
648
- const remoteCaches = new Map<
649
- string,
650
- ReturnType<typeof createCachedFetcher<string, PageSeoMeta | null>>
651
- >();
660
+ const seoCaches: Array<
661
+ ReturnType<typeof createCachedFetcher<SeoRouteRequest, PageSeoMeta | null>>
662
+ > = [];
663
+ const seoLocaleConfig = supportedLocales ? resolveI18nConfig(intlCfg) : undefined;
664
+ const seoPath = (pathname: string) =>
665
+ seoLocaleConfig ? parseLocale(pathname, seoLocaleConfig).pathname : pathname;
652
666
 
653
667
  for (const [pattern, value] of Object.entries(config.seo ?? {})) {
654
668
  const { re, paramNames } = compileSeoPattern(pattern);
655
669
 
656
670
  if (typeof value === 'function') {
657
671
  // 自定义 resolver
658
- seoRoutes.push({ re, paramNames, resolver: value as CompiledRoute['resolver'] });
672
+ const resolve = value as (
673
+ params: Record<string, string>
674
+ ) => PageSeoMeta | null | Promise<PageSeoMeta | null>;
675
+ seoRoutes.push({ re, paramNames, resolver: ({ params }) => resolve(params) });
659
676
  continue;
660
677
  }
661
678
  if ('endpoint' in value && typeof (value as SeoRemoteEntry).endpoint === 'string') {
662
679
  const remote = value as SeoRemoteEntry;
663
- const cache = createCachedFetcher<string, PageSeoMeta | null>({
664
- key: paramKey => `seo:${pattern}:${paramKey}`,
680
+ const cache = createCachedFetcher<SeoRouteRequest, PageSeoMeta | null>({
681
+ key: request => JSON.stringify(request),
665
682
  ttl: remote.ttl ?? 300_000,
666
- fetch: async paramKey => {
667
- const params = JSON.parse(paramKey) as Record<string, string>;
668
- const data = await fetchJson(fillTemplate(remote.endpoint, params), services.api);
683
+ onDegraded: markUncacheable,
684
+ fetch: async ({ params }, markDegraded) => {
685
+ const data = await fetchJson(fillTemplate(remote.endpoint, params), markDegraded);
669
686
  if (data === null) return null;
670
- return remote.transform(data, params);
687
+ return remote.transform(data, { ...params });
671
688
  },
672
689
  fallback: () => null,
673
690
  });
674
- remoteCaches.set(pattern, cache);
675
- seoRoutes.push({
676
- re,
677
- paramNames,
678
- resolver: params => cache(JSON.stringify(params)),
679
- });
691
+ seoCaches.push(cache);
692
+ seoRoutes.push({ re, paramNames, resolver: cache });
680
693
  continue;
681
694
  }
682
695
  if ('load' in value && typeof (value as SeoLocalEntry).load === 'function') {
683
696
  const local = value as SeoLocalEntry;
684
- const cache = createCachedFetcher<string, PageSeoMeta | null>({
685
- key: paramKey => `seo-local:${pattern}:${paramKey}`,
697
+ const cache = createCachedFetcher<SeoRouteRequest, PageSeoMeta | null>({
698
+ key: request => JSON.stringify(request),
686
699
  ttl: local.ttl ?? 300_000,
687
- fetch: async paramKey => {
688
- const params = JSON.parse(paramKey) as Record<string, string>;
689
- return await local.load(params, runtimeCtx);
690
- },
700
+ onDegraded: markUncacheable,
701
+ fetch: async ({ params }, markDegraded) =>
702
+ local.load({ ...params }, metadataContext(markDegraded)),
691
703
  fallback: () => null,
692
704
  });
693
- remoteCaches.set(pattern, cache);
694
- seoRoutes.push({
695
- re,
696
- paramNames,
697
- resolver: params => cache(JSON.stringify(params)),
698
- });
705
+ seoCaches.push(cache);
706
+ seoRoutes.push({ re, paramNames, resolver: cache });
699
707
  continue;
700
708
  }
701
709
  // 静态 meta
@@ -721,7 +729,7 @@ function createSiteHooks(config: SiteHooksConfig, runtime: SiteRuntimeConfig): S
721
729
  const output: ServerHooksOutput = {
722
730
  siteBaseUrl: site || undefined,
723
731
  apiBaseUrl: api || undefined,
724
- intl: config.intl,
732
+ intl: rememberLocale ? intlCfg : config.intl,
725
733
  headExtras: config.headExtras,
726
734
  async beforeRequest(req, _engineCtx) {
727
735
  const locale = detectLocale(req);
@@ -737,25 +745,15 @@ function createSiteHooks(config: SiteHooksConfig, runtime: SiteRuntimeConfig): S
737
745
  // 客户端 RSC 导航 fetch 的 URL 带 _.rsc 后缀(详见 defaults/runtime/request.tsx)。
738
746
  // 先剥后缀,否则 /zh-CN/books/1_.rsc 永远 match 不到 /books/:id route → seoMeta=null →
739
747
  // 客户端导航后 head 不更新。HTML 请求没这个后缀,原行为不变。
740
- let pathForRouting = url.pathname;
741
- if (pathForRouting.endsWith('_.rsc')) {
742
- pathForRouting = pathForRouting.slice(0, -'_.rsc'.length) || '/';
743
- }
744
748
  // SEO 表是按"业务规范路径"('/' / '/books' / '/about')入库的,
745
749
  // 不带 locale 前缀。请求 URL 是带前缀的('/en-US/'、'/zh-CN/books'),
746
750
  // 直接喂给 admin 查不到。先用 parseLocale 把 locale 段剥掉,
747
751
  // 再去 seoRoutes 里匹配 + 调 admin endpoint。
748
- // 同时 locale 单独传到 resolver params,让 endpoint 模板里 {locale}
749
- // 占位符能填对应语言(之前那个 fix 留着,跟 strip 配合一起才完整)。
750
- const intlConfig = config.intl;
751
- const cleanPath =
752
- intlConfig?.locales && intlConfig.locales.length > 0
753
- ? parseLocale(pathForRouting, {
754
- locales: intlConfig.locales,
755
- defaultLocale: intlConfig.defaultLocale ?? intlConfig.locales[0]!,
756
- prefixDefault: intlConfig.prefixDefault,
757
- } satisfies I18nConfig).pathname
758
- : pathForRouting;
752
+ // locale 单独传给 resolver,支持 endpoint 模板里的 {locale}。
753
+ const pathForRouting = url.pathname.endsWith(RSC_URL_POSTFIX)
754
+ ? url.pathname.slice(0, -RSC_URL_POSTFIX.length) || '/'
755
+ : url.pathname;
756
+ const cleanPath = seoPath(pathForRouting);
759
757
 
760
758
  for (const { re, paramNames, resolver } of seoRoutes) {
761
759
  const m = cleanPath.match(re);
@@ -765,13 +763,39 @@ function createSiteHooks(config: SiteHooksConfig, runtime: SiteRuntimeConfig): S
765
763
  locale,
766
764
  };
767
765
  paramNames.forEach((n, i) => (params[n] = m[i + 1] ?? ''));
768
- return await resolver(params);
766
+ return await resolver({ pathname: cleanPath, locale, params });
769
767
  }
770
768
  }
771
769
  return null;
772
770
  },
773
771
  onError,
774
772
  };
773
+ const invalidate: Parameters<typeof registerContentInvalidator>[0] = scopes => {
774
+ const locales = new Set(scopes.locales);
775
+ if (scopes.allPageMetadata || locales.size) {
776
+ intlLoader.invalidate(
777
+ locale => !!scopes.allPageMetadata || locales.has(locale.toLowerCase())
778
+ );
779
+ }
780
+ if (scopes.allPageMetadata || scopes.tags.length) {
781
+ for (const cache of seoCaches) cache.invalidate();
782
+ return;
783
+ }
784
+ if (!scopes.paths.length && !locales.size) return;
785
+ const paths = new Set(
786
+ scopes.paths.map(pathname => trimTrailingSlashes(seoPath(contentPathname(pathname))))
787
+ );
788
+ for (const cache of seoCaches) {
789
+ cache.invalidate(
790
+ ({ pathname, locale }) =>
791
+ paths.has(trimTrailingSlashes(pathname)) || locales.has(locale.toLowerCase())
792
+ );
793
+ }
794
+ };
795
+ // Keep the weak listener alive when the runtime copies these hooks into a server entry.
796
+ Object.defineProperty(output.loadIntl, CONTENT_INVALIDATOR, { value: invalidate });
797
+ Object.defineProperty(output.loadSeoMeta, CONTENT_INVALIDATOR, { value: invalidate });
798
+ registerContentInvalidator(invalidate, { weak: true });
775
799
  Object.defineProperty(output, '__configureRuntime', {
776
800
  enumerable: false,
777
801
  configurable: true,
@@ -971,15 +995,28 @@ function createServerReportId(): string | null {
971
995
  }
972
996
  }
973
997
 
974
- async function fetchJsonWithTimeout<T>(url: string, timeoutMs = 1200): Promise<T | null> {
998
+ async function fetchMetadataJson(
999
+ url: string,
1000
+ timeoutMs: number | null = 1200,
1001
+ markDegraded?: () => void
1002
+ ): Promise<unknown> {
975
1003
  try {
976
- const response = await fetch(url, {
977
- headers: { Accept: 'application/json' },
978
- signal: timeoutMs > 0 ? AbortSignal.timeout(timeoutMs) : undefined,
979
- });
980
- if (!response.ok) return null;
981
- return (await response.json()) as T;
1004
+ const response =
1005
+ timeoutMs === null
1006
+ ? await fetch(url)
1007
+ : await fetch(url, {
1008
+ headers: { Accept: 'application/json' },
1009
+ signal: timeoutMs > 0 ? AbortSignal.timeout(timeoutMs) : undefined,
1010
+ });
1011
+ if (!response.ok) {
1012
+ if (response.status !== 404) markDegraded?.();
1013
+ void response.body?.cancel().catch(() => undefined);
1014
+ return null;
1015
+ }
1016
+ if (response.status === 204) return null;
1017
+ return await response.json();
982
1018
  } catch {
1019
+ markDegraded?.();
983
1020
  return null;
984
1021
  }
985
1022
  }
@@ -1,10 +1,13 @@
1
1
  import { parseLocale, withLocale, type I18nConfig } from '../../runtime/i18n';
2
+ import { serializeLocalePreference } from '../../runtime/localePreference';
2
3
  import { isPrimaryLinkClick } from './client-navigation-policy';
3
4
  import { pushLinkNavigation } from './navigation-history.client';
4
5
 
5
6
  const selector = 'a[data-isr-locale-link]';
6
7
 
7
- function updateLink(link: HTMLAnchorElement): URL | undefined {
8
+ function updateLink(
9
+ link: HTMLAnchorElement
10
+ ): { url: URL; locale: string; config: I18nConfig } | undefined {
8
11
  const data = link.dataset.isrLocaleLink;
9
12
  if (!data) return undefined;
10
13
  try {
@@ -14,7 +17,7 @@ function updateLink(link: HTMLAnchorElement): URL | undefined {
14
17
  url.pathname = withLocale(pathname, locale, config);
15
18
  link.href = url.href;
16
19
  link.removeAttribute('aria-disabled');
17
- return url;
20
+ return { url, locale, config };
18
21
  } catch {
19
22
  link.removeAttribute('href');
20
23
  link.setAttribute('aria-disabled', 'true');
@@ -31,15 +34,22 @@ export function installLocaleLinks() {
31
34
  if (!(event.target instanceof Element)) return;
32
35
  const link = event.target.closest<HTMLAnchorElement>(selector);
33
36
  if (!link) return;
34
- const url = updateLink(link);
37
+ const destination = updateLink(link);
35
38
  if (
36
- url &&
39
+ destination &&
37
40
  event instanceof MouseEvent &&
38
41
  event.type === 'click' &&
39
42
  (!link.target || link.target === '_self') &&
40
43
  isPrimaryLinkClick(event)
41
44
  ) {
42
45
  event.preventDefault();
46
+ const { url, locale, config } = destination;
47
+ try {
48
+ const preference = serializeLocalePreference(locale, config, url.protocol === 'https:');
49
+ if (preference) document.cookie = preference;
50
+ } catch {
51
+ // A browser may block cookie access. Keep the link usable in that case.
52
+ }
43
53
  if (!connected) pending = url.href;
44
54
  else if (url.href !== location.href) pushLinkNavigation(url.href);
45
55
  }
@@ -0,0 +1,10 @@
1
+ export function isRenderCancellation(signal: AbortSignal | undefined, error: unknown): boolean {
2
+ // React receives this same reason through its render signal.
3
+ return signal?.aborted === true && error === signal.reason;
4
+ }
5
+
6
+ export function createRenderErrorHandler(signal: AbortSignal | undefined) {
7
+ return (error: unknown): void => {
8
+ if (!isRenderCancellation(signal, error)) console.error(error);
9
+ };
10
+ }
@@ -11,7 +11,7 @@ export type LocaleLinkProps = Omit<
11
11
 
12
12
  /** Switch the current route's locale through the engine's browser navigation. */
13
13
  export function LocaleLink({ locale, config, ...props }: LocaleLinkProps) {
14
- const { locales, defaultLocale, prefixDefault } = config;
14
+ const { locales, defaultLocale, prefixDefault, rememberLocale } = config;
15
15
  return (
16
16
  <a
17
17
  {...props}
@@ -19,7 +19,13 @@ export function LocaleLink({ locale, config, ...props }: LocaleLinkProps) {
19
19
  hrefLang={locale}
20
20
  data-prefetch='false'
21
21
  aria-disabled='true'
22
- data-isr-locale-link={JSON.stringify({ locale, locales, defaultLocale, prefixDefault })}
22
+ data-isr-locale-link={JSON.stringify({
23
+ locale,
24
+ locales,
25
+ defaultLocale,
26
+ prefixDefault,
27
+ rememberLocale,
28
+ })}
23
29
  suppressHydrationWarning
24
30
  />
25
31
  );
@@ -33,6 +33,8 @@ export interface I18nConfig {
33
33
  defaultLocale: string;
34
34
  /** 是否给默认 locale 也加 URL 前缀(默认 false:'/about';true:'/zh/about') */
35
35
  prefixDefault?: boolean;
36
+ /** Remember deliberate LocaleLink selections for the unprefixed root in prefixDefault mode. */
37
+ rememberLocale?: boolean;
36
38
  }
37
39
 
38
40
  export interface ParsedLocale {
@@ -225,6 +227,7 @@ export function resolveI18nConfig(
225
227
  locales?: readonly string[];
226
228
  defaultLocale?: string;
227
229
  prefixDefault?: boolean;
230
+ rememberLocale?: boolean;
228
231
  } | null
229
232
  ): I18nConfig {
230
233
  const locales = intl?.locales && intl.locales.length > 0 ? intl.locales : ['en'];
@@ -233,5 +236,6 @@ export function resolveI18nConfig(
233
236
  locales,
234
237
  defaultLocale,
235
238
  prefixDefault: intl?.prefixDefault,
239
+ ...(intl?.rememberLocale && { rememberLocale: true }),
236
240
  };
237
241
  }
@@ -0,0 +1,36 @@
1
+ import { readCookie, type CookieHeaderSource } from '../utils/cookie';
2
+ import type { I18nConfig } from './i18n';
3
+
4
+ export const LOCALE_PREFERENCE_COOKIE_NAME = 'isr_locale';
5
+ const MAX_AGE_SECONDS = 365 * 24 * 60 * 60;
6
+
7
+ export function isSupportedLocalePreference(
8
+ locale: string | undefined,
9
+ config: I18nConfig
10
+ ): locale is string {
11
+ return (
12
+ config.prefixDefault === true &&
13
+ config.rememberLocale === true &&
14
+ locale !== undefined &&
15
+ config.locales.includes(locale)
16
+ );
17
+ }
18
+
19
+ export function readLocalePreference(
20
+ source: CookieHeaderSource,
21
+ config: I18nConfig
22
+ ): string | undefined {
23
+ if (!config.rememberLocale || !config.prefixDefault) return undefined;
24
+ const locale = readCookie(source, LOCALE_PREFERENCE_COOKIE_NAME);
25
+ return isSupportedLocalePreference(locale, config) ? locale : undefined;
26
+ }
27
+
28
+ export function serializeLocalePreference(
29
+ locale: string,
30
+ config: I18nConfig,
31
+ secure: boolean
32
+ ): string | undefined {
33
+ if (!isSupportedLocalePreference(locale, config)) return undefined;
34
+ const value = encodeURIComponent(locale);
35
+ return `${LOCALE_PREFERENCE_COOKIE_NAME}=${value}; Path=/; Max-Age=${MAX_AGE_SECONDS}; SameSite=Lax${secure ? '; Secure' : ''}`;
36
+ }
@@ -105,6 +105,8 @@ export interface RuntimeI18nConfig {
105
105
  defaultLocale: string;
106
106
  /** 默认 locale 是否带 URL 前缀 */
107
107
  prefixDefault: boolean;
108
+ /** Opt in to remembering LocaleLink selections for the unprefixed root in prefixDefault mode. */
109
+ rememberLocale?: boolean;
108
110
  /** 远端字典端点;相对路径会拼到 services.api 上 */
109
111
  endpoint: string | undefined;
110
112
  /** 本地兜底字典;配置 API 不可用时使用 */
@@ -164,6 +166,29 @@ export interface DynamicSeoResolver {
164
166
  }) => Promise<Record<string, unknown> | null> | Record<string, unknown> | null;
165
167
  }
166
168
 
169
+ export interface RuntimeSitemapEntry {
170
+ /** Canonical, origin-relative, percent-encoded pathname. */
171
+ path: string;
172
+ status: 'published' | 'draft' | 'unpublished' | 'scheduled' | 'archived';
173
+ noindex?: boolean;
174
+ /** ISO 8601 timestamp of the last content change. */
175
+ modifiedTime?: string;
176
+ }
177
+
178
+ export interface RuntimeSitemapConfig {
179
+ /**
180
+ * Load the complete authoritative catalog in one operation. Each canonical path is unique.
181
+ * The emitted sitemap can contain up to 50,000 URLs and 50 MiB of uncompressed XML.
182
+ */
183
+ load: (input: {
184
+ services: RuntimeServicesConfig;
185
+ }) => readonly RuntimeSitemapEntry[] | Promise<readonly RuntimeSitemapEntry[]>;
186
+ /** Catalog cache TTL in milliseconds. Defaults to runtime.seo.ttl. */
187
+ ttl?: number;
188
+ /** Reuse a successful catalog on refresh errors for at most this long after expiry. Default 300000. */
189
+ staleIfErrorMs?: number;
190
+ }
191
+
167
192
  export interface RuntimeSeoConfig {
168
193
  /** 远端 SEO 端点;支持 {pathname} */
169
194
  endpoint: string | undefined;
@@ -180,6 +205,8 @@ export interface RuntimeSeoConfig {
180
205
  * generateSeo。详见 DynamicSeoResolver 注释。
181
206
  */
182
207
  dynamicResolvers: readonly DynamicSeoResolver[] | undefined;
208
+ /** Optional authoritative sitemap catalog. */
209
+ sitemap?: RuntimeSitemapConfig;
183
210
  }
184
211
 
185
212
  export interface RuntimeServicesConfig {
@@ -503,6 +530,8 @@ export interface ISRConfig {
503
530
  enabled: boolean;
504
531
  public: boolean;
505
532
  };
533
+ /** Enable the authenticated Node production publication endpoint. Defaults to false. */
534
+ contentRevalidation?: boolean;
506
535
  };
507
536
  };
508
537
 
@@ -23,13 +23,20 @@ export function getCookieHeader(source: CookieHeaderSource): string {
23
23
  return raw === undefined || raw === null ? '' : String(raw);
24
24
  }
25
25
 
26
- export function readCookie(source: CookieHeaderSource, name: string): string | undefined {
26
+ export function readCookie(
27
+ source: CookieHeaderSource,
28
+ name: string,
29
+ duplicate: 'first' | 'last' = 'last'
30
+ ): string | undefined {
27
31
  if (!name) return undefined;
28
- const cookies = parseCookieHeader(getCookieHeader(source));
32
+ const cookies = parseCookieHeader(getCookieHeader(source), duplicate);
29
33
  return cookies[name];
30
34
  }
31
35
 
32
- export function parseCookieHeader(header: string): Record<string, string> {
36
+ export function parseCookieHeader(
37
+ header: string,
38
+ duplicate: 'first' | 'last' = 'last'
39
+ ): Record<string, string> {
33
40
  const entries = new Map<string, string>();
34
41
 
35
42
  for (const part of header.split(';')) {
@@ -40,7 +47,7 @@ export function parseCookieHeader(header: string): Record<string, string> {
40
47
  if (index <= 0) continue;
41
48
 
42
49
  const key = trimmed.slice(0, index).trim();
43
- if (!key) continue;
50
+ if (!key || (duplicate === 'first' && entries.has(key))) continue;
44
51
 
45
52
  const rawValue = trimmed.slice(index + 1).trim();
46
53
  entries.set(key, safeDecodeCookieValue(rawValue));
@@ -0,0 +1,24 @@
1
+ export const RSC_URL_POSTFIX = '_.rsc';
2
+
3
+ export function stripQuery(url: string): string {
4
+ const index = url.indexOf('?');
5
+ return index === -1 ? url : url.slice(0, index);
6
+ }
7
+
8
+ export function stripRscSuffix(path: string): string {
9
+ if (path.endsWith(`/${RSC_URL_POSTFIX}`)) {
10
+ return path.slice(0, -(RSC_URL_POSTFIX.length + 1)) || '/';
11
+ }
12
+ if (path.endsWith(RSC_URL_POSTFIX)) {
13
+ return path.slice(0, -RSC_URL_POSTFIX.length) || '/';
14
+ }
15
+ return path;
16
+ }
17
+
18
+ export function normalizePath(path: string): string {
19
+ return path.startsWith('/') ? path : '/' + path;
20
+ }
21
+
22
+ export function contentPathname(path: string): string {
23
+ return stripRscSuffix(normalizePath(stripQuery(path)));
24
+ }