isr-engine 4.0.1 → 4.1.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 +4 -1
  2. package/dist/cli/cli.js +1 -1
  3. package/dist/config/defineConfig.d.ts +1 -1
  4. package/dist/config/defineConfig.d.ts.map +1 -1
  5. package/dist/config/defineConfig.js +2 -1
  6. package/dist/config/defineConfig.js.map +1 -1
  7. package/dist/cookie-DcUeYm6E.js +42 -0
  8. package/dist/cookie-DcUeYm6E.js.map +1 -0
  9. package/dist/{createCacheInspectorMiddleware-C2QOaq2z.js → createCacheInspectorMiddleware-D6c-CINz.js} +2 -2
  10. package/dist/{createCacheInspectorMiddleware-C2QOaq2z.js.map → createCacheInspectorMiddleware-D6c-CINz.js.map} +1 -1
  11. package/dist/{createISRApp-CR1EeHfI.js → createISRApp-DTlZvKBm.js} +49 -28
  12. package/dist/createISRApp-DTlZvKBm.js.map +1 -0
  13. package/dist/defaults/runtime/client-navigation-policy.d.ts +1 -0
  14. package/dist/defaults/runtime/client-navigation-policy.d.ts.map +1 -1
  15. package/dist/defaults/runtime/defineSiteHooks.d.ts +1 -1
  16. package/dist/defaults/runtime/defineSiteHooks.d.ts.map +1 -1
  17. package/dist/defaults/runtime/defineSiteHooks.js +2 -2
  18. package/dist/defaults/runtime/locale-links.client.d.ts +6 -0
  19. package/dist/defaults/runtime/locale-links.client.d.ts.map +1 -0
  20. package/dist/defaults/runtime/navigation-history.client.d.ts +8 -0
  21. package/dist/defaults/runtime/navigation-history.client.d.ts.map +1 -1
  22. package/dist/{defineSiteHooks-DUEds_hB.js → defineSiteHooks-iwLiVChy.js} +15 -32
  23. package/dist/defineSiteHooks-iwLiVChy.js.map +1 -0
  24. package/dist/engine/ISREngine.d.ts.map +1 -1
  25. package/dist/engine/seo/SEOEngine.d.ts +2 -3
  26. package/dist/engine/seo/SEOEngine.d.ts.map +1 -1
  27. package/dist/engine/seo/resolveSeoConfig.d.ts +2 -0
  28. package/dist/engine/seo/resolveSeoConfig.d.ts.map +1 -1
  29. package/dist/{i18n-CJ0leKhc.js → i18n-B2mWmifk.js} +79 -57
  30. package/dist/i18n-B2mWmifk.js.map +1 -0
  31. package/dist/isr-engine.js +4 -3
  32. package/dist/isr-engine.js.map +1 -1
  33. package/dist/middlewares/LocaleRedirect.d.ts +4 -3
  34. package/dist/middlewares/LocaleRedirect.d.ts.map +1 -1
  35. package/dist/runtime/LocaleLink.d.ts +9 -0
  36. package/dist/runtime/LocaleLink.d.ts.map +1 -0
  37. package/dist/runtime/i18n.d.ts +6 -1
  38. package/dist/runtime/i18n.d.ts.map +1 -1
  39. package/dist/runtime/index.d.ts +1 -0
  40. package/dist/runtime/index.d.ts.map +1 -1
  41. package/dist/server/productionRuntime.d.ts.map +1 -1
  42. package/dist/types/ISRConfig.d.ts +1 -1
  43. package/dist/types/ISRConfig.d.ts.map +1 -1
  44. package/package.json +1 -1
  45. package/src/defaults/runtime/client-navigation-policy.ts +11 -0
  46. package/src/defaults/runtime/defineClientEntry.tsx +86 -43
  47. package/src/defaults/runtime/defineServerEntry.tsx +9 -1
  48. package/src/defaults/runtime/defineSiteHooks.ts +19 -41
  49. package/src/defaults/runtime/locale-links.client.ts +85 -0
  50. package/src/defaults/runtime/navigation-history.client.ts +166 -1
  51. package/src/runtime/LocaleContext.tsx +1 -1
  52. package/src/runtime/LocaleLink.tsx +26 -0
  53. package/src/runtime/i18n.ts +67 -19
  54. package/src/runtime/index.ts +1 -0
  55. package/src/types/ISRConfig.ts +1 -1
  56. package/dist/createISRApp-CR1EeHfI.js.map +0 -1
  57. package/dist/defineSiteHooks-DUEds_hB.js.map +0 -1
  58. package/dist/i18n-CJ0leKhc.js.map +0 -1
@@ -0,0 +1,85 @@
1
+ import { parseLocale, withLocale, type I18nConfig } from '../../runtime/i18n';
2
+ import { isPrimaryLinkClick } from './client-navigation-policy';
3
+ import { pushLinkNavigation } from './navigation-history.client';
4
+
5
+ const selector = 'a[data-isr-locale-link]';
6
+
7
+ function updateLink(link: HTMLAnchorElement): URL | undefined {
8
+ const data = link.dataset.isrLocaleLink;
9
+ if (!data) return undefined;
10
+ try {
11
+ const { locale, ...config } = JSON.parse(data) as I18nConfig & { locale: string };
12
+ const url = new URL(location.href);
13
+ const { pathname } = parseLocale(url.pathname, config);
14
+ url.pathname = withLocale(pathname, locale, config);
15
+ link.href = url.href;
16
+ link.removeAttribute('aria-disabled');
17
+ return url;
18
+ } catch {
19
+ link.removeAttribute('href');
20
+ link.setAttribute('aria-disabled', 'true');
21
+ return undefined;
22
+ }
23
+ }
24
+
25
+ /** Enable server-rendered links before hydration and hand navigation to the common router. */
26
+ export function installLocaleLinks() {
27
+ let connected = false;
28
+ let pending: string | undefined;
29
+
30
+ function handleLink(event: Event) {
31
+ if (!(event.target instanceof Element)) return;
32
+ const link = event.target.closest<HTMLAnchorElement>(selector);
33
+ if (!link) return;
34
+ const url = updateLink(link);
35
+ if (
36
+ url &&
37
+ event instanceof MouseEvent &&
38
+ event.type === 'click' &&
39
+ (!link.target || link.target === '_self') &&
40
+ isPrimaryLinkClick(event)
41
+ ) {
42
+ event.preventDefault();
43
+ if (!connected) pending = url.href;
44
+ else if (url.href !== location.href) pushLinkNavigation(url.href);
45
+ }
46
+ }
47
+
48
+ for (const type of ['click', 'auxclick', 'contextmenu', 'focusin']) {
49
+ document.addEventListener(type, handleLink, { capture: true });
50
+ }
51
+ function scan(root: ParentNode) {
52
+ if (root instanceof HTMLAnchorElement && root.matches(selector)) updateLink(root);
53
+ root.querySelectorAll<HTMLAnchorElement>(selector).forEach(updateLink);
54
+ }
55
+ const observer = new MutationObserver(records => {
56
+ for (const { target, type, addedNodes } of records) {
57
+ if (type === 'attributes' && target instanceof HTMLAnchorElement) updateLink(target);
58
+ for (const node of addedNodes) {
59
+ if (node instanceof Element) scan(node);
60
+ }
61
+ }
62
+ });
63
+ observer.observe(document, {
64
+ childList: true,
65
+ subtree: true,
66
+ attributes: true,
67
+ attributeFilter: ['data-isr-locale-link'],
68
+ });
69
+ scan(document);
70
+
71
+ return {
72
+ connect() {
73
+ connected = true;
74
+ queueMicrotask(() => {
75
+ if (!connected || !pending) return;
76
+ const href = pending;
77
+ pending = undefined;
78
+ if (location.href !== href) pushLinkNavigation(href);
79
+ });
80
+ },
81
+ disconnect() {
82
+ connected = false;
83
+ },
84
+ };
85
+ }
@@ -1,4 +1,6 @@
1
1
  const RSC_POSTFIX = '_.rsc';
2
+ const entryStateKey = '__isr_scroll_entry';
3
+ let nextLegacyEntry = 0;
2
4
 
3
5
  let internalNavigationHistoryMutationDepth = 0;
4
6
 
@@ -42,6 +44,169 @@ export function isInternalNavigationHistoryMutation(): boolean {
42
44
  return internalNavigationHistoryMutationDepth > 0;
43
45
  }
44
46
 
47
+ function navigationEntryKey(): string | undefined {
48
+ return (window as Window & { navigation?: { currentEntry?: { key: string } } }).navigation
49
+ ?.currentEntry?.key;
50
+ }
51
+
52
+ export function pushLinkNavigation(href: string): void {
53
+ window.history.pushState(null, '', href);
54
+ }
55
+
56
+ type ScrollPosition = [x: number, y: number];
57
+ export type HistoryChange = 'push' | 'replace' | 'traverse' | 'hash';
58
+
59
+ function currentScrollEntry(): string {
60
+ return navigationEntryKey() ?? legacyEntryKey() ?? window.location.href;
61
+ }
62
+
63
+ function legacyEntryKey(): string | undefined {
64
+ const value: unknown = window.history.state?.[entryStateKey];
65
+ return typeof value === 'string' ? value : undefined;
66
+ }
67
+
68
+ export function historyStateWithScrollEntry(data: unknown, replace: boolean): unknown {
69
+ if (
70
+ navigationEntryKey() ||
71
+ (data != null && (typeof data !== 'object' || Object.getPrototypeOf(data) !== Object.prototype))
72
+ ) {
73
+ return data;
74
+ }
75
+ // Preserve application fields and use the browser's entry key wherever available.
76
+ return {
77
+ ...(data as Record<string, unknown> | null),
78
+ [entryStateKey]:
79
+ (replace ? legacyEntryKey() : undefined) ?? performance.timeOrigin + ':' + ++nextLegacyEntry,
80
+ };
81
+ }
82
+
83
+ function fragmentTarget(hash: string): HTMLElement | undefined {
84
+ const raw = hash.slice(1);
85
+ let name = raw;
86
+ try {
87
+ name = decodeURIComponent(raw);
88
+ } catch {
89
+ // The literal fragment can still be a valid element ID.
90
+ }
91
+ return (
92
+ document.getElementById(name) ??
93
+ Array.from(document.getElementsByName(name)).find(element => element.localName === 'a')
94
+ );
95
+ }
96
+
97
+ export function createNavigationScroll() {
98
+ const { history } = window;
99
+ const previousRestoration = history.scrollRestoration;
100
+ history.scrollRestoration = 'manual';
101
+ if (!navigationEntryKey() && !legacyEntryKey()) {
102
+ const existing = history.state;
103
+ const state = historyStateWithScrollEntry(existing, true);
104
+ if (state !== existing) history.replaceState(state, '');
105
+ }
106
+
107
+ const positions = new Map<string, ScrollPosition>();
108
+ let entry = currentScrollEntry();
109
+ let pending: { restore?: ScrollPosition } | undefined;
110
+ let stopWaiting: (() => void) | undefined;
111
+ let scheduledScroll: number | undefined;
112
+
113
+ function save() {
114
+ if (!pending) positions.set(entry, [window.scrollX, window.scrollY]);
115
+ }
116
+
117
+ function apply(restore?: ScrollPosition) {
118
+ stopWaiting?.();
119
+ const { hash } = window.location;
120
+ function tryScroll(): boolean {
121
+ if (restore) {
122
+ window.scrollTo({ left: restore[0], top: restore[1], behavior: 'instant' });
123
+ return (
124
+ Math.abs(window.scrollX - restore[0]) < 1 && Math.abs(window.scrollY - restore[1]) < 1
125
+ );
126
+ }
127
+ const target = hash ? fragmentTarget(hash) : undefined;
128
+ if (!target) return false;
129
+ target.scrollIntoView({ behavior: 'instant' });
130
+ return true;
131
+ }
132
+ if (tryScroll()) return;
133
+ if (!restore) {
134
+ window.scrollTo({ left: 0, top: 0, behavior: 'instant' });
135
+ if (!hash || hash.toLowerCase() === '#top') return;
136
+ }
137
+
138
+ // Streamed content can mount an anchor or make saved coordinates reachable later.
139
+ const waiting = new AbortController();
140
+ stopWaiting = () => waiting.abort();
141
+ const retry = () => {
142
+ if (tryScroll()) waiting.abort();
143
+ };
144
+ const mutations = new MutationObserver(retry);
145
+ mutations.observe(document.body, {
146
+ childList: true,
147
+ subtree: true,
148
+ attributes: !restore,
149
+ ...(restore ? {} : { attributeFilter: ['id', 'name'] }),
150
+ });
151
+ const resize =
152
+ restore && typeof ResizeObserver !== 'undefined' ? new ResizeObserver(retry) : undefined;
153
+ resize?.observe(document.body);
154
+ waiting.signal.addEventListener(
155
+ 'abort',
156
+ () => {
157
+ mutations.disconnect();
158
+ resize?.disconnect();
159
+ stopWaiting = undefined;
160
+ },
161
+ { once: true }
162
+ );
163
+ for (const type of ['pointerdown', 'wheel', 'keydown']) {
164
+ window.addEventListener(type, stopWaiting, { passive: true, signal: waiting.signal });
165
+ }
166
+ }
167
+
168
+ window.addEventListener('scroll', save, { passive: true });
169
+ return {
170
+ save,
171
+ changed(kind: HistoryChange, needsPayload: boolean): (() => void) | undefined {
172
+ const nextEntry = currentScrollEntry();
173
+ const restore = kind === 'traverse' ? positions.get(nextEntry) : undefined;
174
+ const entryChanged = nextEntry !== entry;
175
+ if (entryChanged || needsPayload || kind === 'hash') {
176
+ stopWaiting?.();
177
+ if (scheduledScroll !== undefined) window.cancelAnimationFrame(scheduledScroll);
178
+ scheduledScroll = undefined;
179
+ }
180
+ entry = nextEntry;
181
+ if (!needsPayload) {
182
+ if (pending && entryChanged) pending.restore = restore;
183
+ else if (entryChanged && restore) {
184
+ scheduledScroll = window.requestAnimationFrame(() => {
185
+ scheduledScroll = undefined;
186
+ if (!pending && currentScrollEntry() === nextEntry) apply(restore);
187
+ });
188
+ }
189
+ return undefined;
190
+ }
191
+ const transition = { restore };
192
+ pending = transition;
193
+ return () => {
194
+ if (pending !== transition) return;
195
+ pending = undefined;
196
+ entry = currentScrollEntry();
197
+ apply(transition.restore);
198
+ };
199
+ },
200
+ dispose() {
201
+ window.removeEventListener('scroll', save);
202
+ stopWaiting?.();
203
+ if (scheduledScroll !== undefined) window.cancelAnimationFrame(scheduledScroll);
204
+ pending = undefined;
205
+ history.scrollRestoration = previousRestoration;
206
+ },
207
+ };
208
+ }
209
+
45
210
  /**
46
211
  * Synchronize an accepted server redirect without re-entering the RSC router.
47
212
  * A completed non-redirect response, or a redirect for a location the user has
@@ -68,7 +233,7 @@ export function syncBrowserUrlToFinalRedirect(
68
233
  internalNavigationHistoryMutationDepth += 1;
69
234
  try {
70
235
  browserWindow.history.replaceState(
71
- null,
236
+ browserWindow.history.state ?? null,
72
237
  '',
73
238
  `${final.pathname}${final.search}${browserWindow.location.hash}`
74
239
  );
@@ -2,7 +2,7 @@
2
2
  * LocaleProvider / useLocale —— 客户端 locale context(极小)
3
3
  *
4
4
  * 不内置消息字典;只暴露当前 locale + I18nConfig 给组件
5
- * 切换语言用 withLocale + <a href> 触发整页导航即可(SSR 重新分派)
5
+ * 切换当前页面的语言使用 LocaleLink。
6
6
  */
7
7
  'use client';
8
8
 
@@ -0,0 +1,26 @@
1
+ import type { ComponentPropsWithoutRef } from 'react';
2
+ import type { I18nConfig } from './i18n';
3
+
4
+ export type LocaleLinkProps = Omit<
5
+ ComponentPropsWithoutRef<'a'>,
6
+ 'href' | 'hrefLang' | 'role' | 'aria-disabled' | 'download' | 'onClick' | 'onClickCapture'
7
+ > & {
8
+ locale: string;
9
+ config: I18nConfig;
10
+ };
11
+
12
+ /** Switch the current route's locale through the engine's browser navigation. */
13
+ export function LocaleLink({ locale, config, ...props }: LocaleLinkProps) {
14
+ const { locales, defaultLocale, prefixDefault } = config;
15
+ return (
16
+ <a
17
+ {...props}
18
+ role='link'
19
+ hrefLang={locale}
20
+ data-prefetch='false'
21
+ aria-disabled='true'
22
+ data-isr-locale-link={JSON.stringify({ locale, locales, defaultLocale, prefixDefault })}
23
+ suppressHydrationWarning
24
+ />
25
+ );
26
+ }
@@ -90,7 +90,7 @@ export function withLocale(pathname: string, locale: string, config: I18nConfig)
90
90
  }
91
91
 
92
92
  /**
93
- * Accept-Language 协商 —— RFC 4647 lookup(含主语言回退)
93
+ * 按权重协商 Accept-Language(支持主语言回退和通配符)
94
94
  *
95
95
  * negotiateLocale('zh-CN,en;q=0.9', { locales: ['zh','en'], defaultLocale: 'en' })
96
96
  * → 'zh' ('zh-CN' 命中 'zh')
@@ -99,39 +99,87 @@ export function withLocale(pathname: string, locale: string, config: I18nConfig)
99
99
  * → 'en-us' ('en-GB' 主语言 'en' 回退到第一个 en-*)
100
100
  *
101
101
  * negotiateLocale(null, ...) → defaultLocale
102
+ *
103
+ * @throws {RangeError} When the header explicitly rejects every available locale.
102
104
  */
103
105
  export function negotiateLocale(
104
106
  acceptLanguage: string | null | undefined,
105
107
  config: I18nConfig
106
108
  ): string {
109
+ const locale = selectAcceptableLocale(acceptLanguage, config);
110
+ if (locale !== null) return locale;
111
+ const error = new RangeError('[i18n] no supported locale is acceptable');
112
+ Object.defineProperty(error, NO_ACCEPTABLE_LOCALE, { value: true });
113
+ throw error;
114
+ }
115
+
116
+ // The server entry and SiteHooks can load separately bundled copies of this module.
117
+ const NO_ACCEPTABLE_LOCALE = Symbol.for('isr-engine.no-acceptable-locale');
118
+
119
+ export function isNoAcceptableLocaleError(error: unknown): boolean {
120
+ return error instanceof RangeError && NO_ACCEPTABLE_LOCALE in error;
121
+ }
122
+
123
+ /** Returns null when the header explicitly rejects every available locale. */
124
+ export function selectAcceptableLocale(
125
+ acceptLanguage: string | null | undefined,
126
+ config: I18nConfig
127
+ ): string | null {
107
128
  if (!acceptLanguage) return config.defaultLocale;
108
129
  const ranked = acceptLanguage
109
130
  .split(',')
110
- .map(part => {
111
- const [tag, ...params] = part.trim().split(';');
112
- const q = params.find(p => p.startsWith('q='));
113
- return { tag: tag.toLowerCase(), q: q ? Number(q.slice(2)) || 0 : 1 };
131
+ .flatMap(part => {
132
+ const [rawTag, ...params] = part.split(';');
133
+ const tag = rawTag.trim().toLowerCase();
134
+ const weight = params
135
+ .map(param => param.trim())
136
+ .find(param => /^q=/i.test(param))
137
+ ?.slice(2)
138
+ .trim();
139
+ const q = weight === undefined ? 1 : Number(weight);
140
+ return tag && weight !== '' && q >= 0 && q <= 1 ? [{ tag, q }] : [];
114
141
  })
115
142
  .sort((a, b) => b.q - a.q);
116
143
 
117
- const supported = config.locales.map(l => l.toLowerCase());
118
- for (const { tag } of ranked) {
119
- // 1) 完整 code 精确匹配('en-us' === 'en-us')
120
- const exact = supported.indexOf(tag);
121
- if (exact >= 0) return config.locales[exact];
144
+ // Apply the most specific range to each available tag before lookup or fallback.
145
+ const bySpecificity = [...ranked].sort(
146
+ (a, b) => rangeSpecificity(b.tag) - rangeSpecificity(a.tag) || a.q - b.q
147
+ );
148
+ const matchingRange = (locale: string) =>
149
+ bySpecificity.find(({ tag }) => tag === '*' || locale === tag || locale.startsWith(tag + '-'));
150
+ const defaultRange = matchingRange(config.defaultLocale.toLowerCase());
151
+ const supported = config.locales
152
+ .map(locale => {
153
+ const tag = locale.toLowerCase();
154
+ return { locale, tag, range: matchingRange(tag) };
155
+ })
156
+ .filter(({ range }) => range?.q !== 0);
122
157
 
158
+ for (const preferred of ranked) {
159
+ const { tag, q } = preferred;
160
+ if (q === 0) continue;
161
+ if (tag === '*') {
162
+ if (defaultRange?.tag === '*' && defaultRange.q > 0) return config.defaultLocale;
163
+ const match = supported.find(locale => locale.range?.tag === '*');
164
+ if (match) return match.locale;
165
+ continue;
166
+ }
123
167
  const primary = tag.split('-')[0];
168
+ const candidates = supported.filter(
169
+ ({ range }) => !range || range.tag === '*' || range === preferred
170
+ );
171
+ const match =
172
+ candidates.find(locale => locale.tag === tag) ??
173
+ candidates.find(locale => locale.tag === primary) ??
174
+ candidates.find(locale => locale.tag.startsWith(primary + '-'));
175
+ if (match) return match.locale;
176
+ }
124
177
 
125
- // 2) 主语言精确匹配('ja' === 'ja',针对无地区后缀的 locale 如 ja/fr/tr)
126
- const sub = supported.indexOf(primary);
127
- if (sub >= 0) return config.locales[sub];
178
+ return defaultRange?.q === 0 ? (supported[0]?.locale ?? null) : config.defaultLocale;
179
+ }
128
180
 
129
- // 3) 主语言回退('en' / 'en-GB' → 第一个 en-*;'zh' / 'zh-CN' → zh-hans)
130
- // 解决「浏览器只发 en / en-GB,而 locales 是 en-us/en-au」这类地区码不匹配问题。
131
- const primaryPrefix = supported.findIndex(l => l.startsWith(primary + '-'));
132
- if (primaryPrefix >= 0) return config.locales[primaryPrefix];
133
- }
134
- return config.defaultLocale;
181
+ function rangeSpecificity(tag: string): number {
182
+ return tag === '*' ? 0 : tag.length;
135
183
  }
136
184
 
137
185
  /**
@@ -26,6 +26,7 @@ export {
26
26
  type Translate,
27
27
  } from './i18n-store';
28
28
  export { LocaleProvider, useLocale } from './LocaleContext';
29
+ export { LocaleLink, type LocaleLinkProps } from './LocaleLink';
29
30
  export {
30
31
  capture,
31
32
  flushTelemetry,
@@ -167,7 +167,7 @@ export interface DynamicSeoResolver {
167
167
  export interface RuntimeSeoConfig {
168
168
  /** 远端 SEO 端点;支持 {pathname} */
169
169
  endpoint: string | undefined;
170
- /** 本地兜底 SEO 路由表;配置 API 不可用时使用 */
170
+ /** 本地兜底 SEO 路由表。可为已知更新时间的 sitemap URL 声明 ISO 8601 modifiedTime。 */
171
171
  fallbackLocal: readonly Record<string, unknown>[] | undefined;
172
172
  /** SEO 元数据缓存 TTL(毫秒) */
173
173
  ttl: number;