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.
- package/README.md +9 -0
- package/dist/CacheTagContext-Btmq8KCD.js +69 -0
- package/dist/CacheTagContext-Btmq8KCD.js.map +1 -0
- package/dist/{abVariantContext-CGBlCt0q.js → abVariantContext-yWZOqscY.js} +118 -38
- package/dist/abVariantContext-yWZOqscY.js.map +1 -0
- package/dist/cache/RedisInvalidationBus.d.ts.map +1 -1
- package/dist/cache/RedisResponseCacheBackend.d.ts +1 -0
- package/dist/cache/RedisResponseCacheBackend.d.ts.map +1 -1
- package/dist/cache/ResponseCacheBackend.d.ts +6 -0
- package/dist/cache/ResponseCacheBackend.d.ts.map +1 -1
- package/dist/cli/cli.js +1 -1
- package/dist/config/defineConfig.js +1 -1
- package/dist/context/CacheTagContext.d.ts +10 -0
- package/dist/context/CacheTagContext.d.ts.map +1 -0
- package/dist/{createCacheInspectorMiddleware-D6c-CINz.js → createCacheInspectorMiddleware-glgtcBcQ.js} +2 -2
- package/dist/{createCacheInspectorMiddleware-D6c-CINz.js.map → createCacheInspectorMiddleware-glgtcBcQ.js.map} +1 -1
- package/dist/createCachedFetcher-CgJscexq.js +186 -0
- package/dist/createCachedFetcher-CgJscexq.js.map +1 -0
- package/dist/{createISRApp-DTlZvKBm.js → createISRApp-BG-s3uuL.js} +356 -162
- package/dist/createISRApp-BG-s3uuL.js.map +1 -0
- package/dist/defaults/runtime/contentRevalidation.d.ts +26 -0
- package/dist/defaults/runtime/contentRevalidation.d.ts.map +1 -0
- package/dist/defaults/runtime/createCachedFetcher.d.ts +8 -2
- package/dist/defaults/runtime/createCachedFetcher.d.ts.map +1 -1
- package/dist/defaults/runtime/defineSiteHooks.d.ts +4 -7
- package/dist/defaults/runtime/defineSiteHooks.d.ts.map +1 -1
- package/dist/defaults/runtime/defineSiteHooks.js +655 -2
- package/dist/defaults/runtime/defineSiteHooks.js.map +1 -0
- package/dist/defaults/runtime/locale-links.client.d.ts.map +1 -1
- package/dist/defaults/runtime/renderCancellation.d.ts +3 -0
- package/dist/defaults/runtime/renderCancellation.d.ts.map +1 -0
- package/dist/engine/ISREngine.d.ts.map +1 -1
- package/dist/engine/seo/SEOEngine.d.ts +3 -0
- package/dist/engine/seo/SEOEngine.d.ts.map +1 -1
- package/dist/engine/seo/resolveSeoConfig.d.ts +6 -0
- package/dist/engine/seo/resolveSeoConfig.d.ts.map +1 -1
- package/dist/{i18n-B2mWmifk.js → i18n-BZpAOZeO.js} +3 -2
- package/dist/{i18n-B2mWmifk.js.map → i18n-BZpAOZeO.js.map} +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/isr/ISRRoutes.d.ts +2 -0
- package/dist/isr/ISRRoutes.d.ts.map +1 -1
- package/dist/isr-engine.js +7 -7
- package/dist/middlewares/LocaleRedirect.d.ts +4 -3
- package/dist/middlewares/LocaleRedirect.d.ts.map +1 -1
- package/dist/plugin/coherentCacheStore.d.ts.map +1 -1
- package/dist/plugin/isrCacheMiddleware.d.ts +7 -6
- package/dist/plugin/isrCacheMiddleware.d.ts.map +1 -1
- package/dist/plugin/isrCacheStore.d.ts +2 -0
- package/dist/plugin/isrCacheStore.d.ts.map +1 -1
- package/dist/rsc/browser.d.ts +3 -0
- package/dist/rsc/browser.d.ts.map +1 -1
- package/dist/rsc/browser.js +4 -9
- package/dist/rsc/browser.js.map +1 -1
- package/dist/rsc/cacheTag.d.ts +1 -8
- package/dist/rsc/cacheTag.d.ts.map +1 -1
- package/dist/rsc/index.d.ts +1 -1
- package/dist/rsc/index.d.ts.map +1 -1
- package/dist/rsc/index.js +4 -3
- package/dist/rsc/revalidate.d.ts +18 -9
- package/dist/rsc/revalidate.d.ts.map +1 -1
- package/dist/{rsc-DWwcqD4W.js → rsc-BYq2vvnh.js} +2 -2
- package/dist/{rsc-DWwcqD4W.js.map → rsc-BYq2vvnh.js.map} +1 -1
- package/dist/runtime/LocaleLink.d.ts.map +1 -1
- package/dist/runtime/i18n.d.ts +3 -0
- package/dist/runtime/i18n.d.ts.map +1 -1
- package/dist/runtime/localePreference.d.ts +7 -0
- package/dist/runtime/localePreference.d.ts.map +1 -0
- package/dist/server/contentRevalidationRoute.d.ts +4 -0
- package/dist/server/contentRevalidationRoute.d.ts.map +1 -0
- package/dist/server/manager.d.ts.map +1 -1
- package/dist/server/opsConfig.d.ts +6 -1
- package/dist/server/opsConfig.d.ts.map +1 -1
- package/dist/server/productionRuntime.d.ts +2 -0
- package/dist/server/productionRuntime.d.ts.map +1 -1
- package/dist/server/publishedSitemap.d.ts +8 -0
- package/dist/server/publishedSitemap.d.ts.map +1 -0
- package/dist/types/ISRConfig.d.ts +27 -0
- package/dist/types/ISRConfig.d.ts.map +1 -1
- package/dist/utils/cookie.d.ts +2 -2
- package/dist/utils/cookie.d.ts.map +1 -1
- package/dist/utils/isrPath.d.ts +6 -0
- package/dist/utils/isrPath.d.ts.map +1 -0
- package/package.json +2 -2
- package/src/context/CacheTagContext.ts +20 -0
- package/src/defaults/entry.server.ssr.tsx +10 -0
- package/src/defaults/runtime/contentRevalidation.ts +96 -0
- package/src/defaults/runtime/createCachedFetcher.ts +76 -20
- package/src/defaults/runtime/defineServerEntry.tsx +30 -29
- package/src/defaults/runtime/defineSiteHooks.ts +117 -80
- package/src/defaults/runtime/locale-links.client.ts +14 -4
- package/src/defaults/runtime/renderCancellation.ts +10 -0
- package/src/runtime/LocaleLink.tsx +8 -2
- package/src/runtime/i18n.ts +4 -0
- package/src/runtime/localePreference.ts +36 -0
- package/src/types/ISRConfig.ts +29 -0
- package/src/utils/cookie.ts +11 -4
- package/src/utils/isrPath.ts +24 -0
- package/dist/abVariantContext-CGBlCt0q.js.map +0 -1
- package/dist/cookie-DcUeYm6E.js +0 -42
- package/dist/cookie-DcUeYm6E.js.map +0 -1
- package/dist/createISRApp-DTlZvKBm.js.map +0 -1
- package/dist/defineSiteHooks-iwLiVChy.js +0 -716
- package/dist/defineSiteHooks-iwLiVChy.js.map +0 -1
|
@@ -1,3 +1,656 @@
|
|
|
1
|
-
import { n as
|
|
2
|
-
import { a as
|
|
1
|
+
import { i as resolveI18nConfig, n as negotiateLocale, r as parseLocale, s as trimTrailingSlashes } from "../../i18n-BZpAOZeO.js";
|
|
2
|
+
import { a as getCookieHeader, i as readLocalePreference, l as contentPathname, o as parseCookieHeader, s as readCookie, t as createCachedFetcher } from "../../createCachedFetcher-CgJscexq.js";
|
|
3
|
+
import { a as registerContentInvalidator, n as markUncacheable } from "../../CacheTagContext-Btmq8KCD.js";
|
|
4
|
+
// src/defaults/runtime/defineSiteHooks.ts
|
|
5
|
+
/**
|
|
6
|
+
* defineSiteHooks —— 高阶 FaaS hooks 工厂(声明式配置 → 完整 ServerEntryHooks)
|
|
7
|
+
*
|
|
8
|
+
* 让用户的 src/entry.server.tsx 收紧到「只写请求期 hooks」。
|
|
9
|
+
* 部署/平台配置(api/site/redis/experiments/i18n/seo/telemetry)放
|
|
10
|
+
* ssr.config.ts 的 runtime 字段;entry.server.tsx 只保留 beforeRequest / onError。
|
|
11
|
+
* 注:experiments 是 experimentation platform 的通用字段名,业务侧可理解为 A/B testing。
|
|
12
|
+
* 内部固化:
|
|
13
|
+
* - i18n 字典缓存(createCachedFetcher: TTL/SWR/dedup/fallback)
|
|
14
|
+
* - SEO 路由表 pattern → resolver
|
|
15
|
+
* - locale 检测(cookie → Accept-Language → 默认)
|
|
16
|
+
* - i18n/seo 远端相对 endpoint 统一使用 runtime.services.api
|
|
17
|
+
* - 服务端渲染错误打印 + runtime.telemetry errors endpoint 上报
|
|
18
|
+
*
|
|
19
|
+
* beforeRequest 的边界:
|
|
20
|
+
* - 它在每次 HTTP/RSC 请求进入渲染前执行。
|
|
21
|
+
* - 返回值会合并进 RequestContext,Server Component 用 getRequestContext() 读取。
|
|
22
|
+
* - 适合放 userId / tenantId / requestSegment 这类请求现场字段。
|
|
23
|
+
* - 不适合放 Redis、SEO、i18n、A/B 定义、慢 API 或数据库查询。
|
|
24
|
+
* - A/B variant 由 runtime.experiments + engine middleware 注入,页面用 getVariant()。
|
|
25
|
+
*
|
|
26
|
+
* 用户态写法(商业项目推荐):
|
|
27
|
+
* import { defineAdminSiteHooks } from 'isr-engine/site-hooks';
|
|
28
|
+
*
|
|
29
|
+
* export default defineAdminSiteHooks({
|
|
30
|
+
* beforeRequest: req => ({
|
|
31
|
+
* userId: req.headers.get('x-user-id') ?? undefined,
|
|
32
|
+
* tenantId: req.headers.get('x-tenant-id') ?? 'public',
|
|
33
|
+
* requestSegment: req.headers.get('x-segment') ?? 'default',
|
|
34
|
+
* }),
|
|
35
|
+
* });
|
|
36
|
+
*/
|
|
37
|
+
var CONTENT_INVALIDATOR = Symbol("contentInvalidator");
|
|
38
|
+
var MARK_METADATA_DEGRADED = Symbol("markMetadataDegraded");
|
|
39
|
+
function createEmptyRuntimeConfig() {
|
|
40
|
+
return {
|
|
41
|
+
site: void 0,
|
|
42
|
+
services: {
|
|
43
|
+
api: void 0,
|
|
44
|
+
telemetry: void 0
|
|
45
|
+
},
|
|
46
|
+
redis: void 0,
|
|
47
|
+
experiments: {},
|
|
48
|
+
i18n: void 0,
|
|
49
|
+
seo: void 0,
|
|
50
|
+
telemetry: false
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
function escapeSeoPatternLiteral(literal) {
|
|
54
|
+
return literal.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
55
|
+
}
|
|
56
|
+
/** Both SEO entry points recognize named parameters and a terminal /* before escaping literals. */
|
|
57
|
+
function compileSeoPattern(pattern, captureWildcard = false) {
|
|
58
|
+
const paramNames = [];
|
|
59
|
+
const wildcard = pattern.endsWith("/*");
|
|
60
|
+
const base = wildcard ? pattern.slice(0, -2) : pattern;
|
|
61
|
+
let cursor = 0;
|
|
62
|
+
let source = "";
|
|
63
|
+
for (const match of base.matchAll(/:(\w+)/g)) {
|
|
64
|
+
source += escapeSeoPatternLiteral(base.slice(cursor, match.index)) + "([^/]+)";
|
|
65
|
+
paramNames.push(match[1]);
|
|
66
|
+
cursor = match.index + match[0].length;
|
|
67
|
+
}
|
|
68
|
+
source += escapeSeoPatternLiteral(base.slice(cursor));
|
|
69
|
+
if (wildcard) {
|
|
70
|
+
if (captureWildcard) paramNames.push("wildcard");
|
|
71
|
+
source += captureWildcard ? "(?:/(.*))?" : "(?:/.*)?";
|
|
72
|
+
}
|
|
73
|
+
return {
|
|
74
|
+
re: new RegExp(`^${source}$`),
|
|
75
|
+
paramNames
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
function fillTemplate(template, vars) {
|
|
79
|
+
return template.replace(/\{(\w+)\}/g, (_, k) => encodeURIComponent(vars[k] ?? ""));
|
|
80
|
+
}
|
|
81
|
+
function createAdminIntlLoader(options = {}) {
|
|
82
|
+
const endpoint = options.endpoint ?? "/api/i18n/{locale}/manifest";
|
|
83
|
+
const fallbackMessages = options.fallbackMessages ?? {};
|
|
84
|
+
const defaultLocale = options.defaultLocale;
|
|
85
|
+
const supportedLocales = Object.keys(fallbackMessages);
|
|
86
|
+
return async (locale, ctx) => {
|
|
87
|
+
const normalizedLocale = supportedLocales.length && defaultLocale ? matchConfiguredLocale(locale, supportedLocales) ?? defaultLocale : locale;
|
|
88
|
+
const remoteUrl = resolveAdminUrl(endpoint, { locale: normalizedLocale }, ctx);
|
|
89
|
+
const remoteMessages = extractIntlMessagesOrNull(remoteUrl ? await fetchMetadataJson(remoteUrl, options.timeoutMs, ctx[MARK_METADATA_DEGRADED]) : null);
|
|
90
|
+
const localMessages = fallbackMessages[normalizedLocale] ?? (defaultLocale ? fallbackMessages[defaultLocale] : void 0) ?? {};
|
|
91
|
+
return {
|
|
92
|
+
locale: normalizedLocale,
|
|
93
|
+
messages: remoteMessages ?? normalizeMessages(localMessages),
|
|
94
|
+
direction: rtlOf(normalizedLocale),
|
|
95
|
+
source: remoteMessages ? options.remoteSource ?? "remote" : options.fallbackSource ?? "local-fallback"
|
|
96
|
+
};
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
function createAdminSeoLoader(options = {}) {
|
|
100
|
+
const endpoint = options.endpoint ?? "/api/seo?path={pathname}";
|
|
101
|
+
const fallbackEntries = options.fallbackEntries ?? [];
|
|
102
|
+
const compiledResolvers = (options.dynamicResolvers ?? []).map((resolver) => ({
|
|
103
|
+
...compileSeoPattern(resolver.pattern, true),
|
|
104
|
+
resolver
|
|
105
|
+
}));
|
|
106
|
+
return async (params, ctx) => {
|
|
107
|
+
const pathname = normalizePathname(params.pathname || "/");
|
|
108
|
+
const remoteUrl = resolveAdminUrl(endpoint, {
|
|
109
|
+
...params,
|
|
110
|
+
pathname
|
|
111
|
+
}, ctx);
|
|
112
|
+
const remoteMeta = extractSeoMetaOrNull(remoteUrl ? await fetchMetadataJson(remoteUrl, options.timeoutMs, ctx[MARK_METADATA_DEGRADED]) : null);
|
|
113
|
+
if (remoteMeta) return remoteMeta;
|
|
114
|
+
if (compiledResolvers.length > 0) for (const compiled of compiledResolvers) {
|
|
115
|
+
const m = pathname.match(compiled.re);
|
|
116
|
+
if (!m) continue;
|
|
117
|
+
const resolverParams = {};
|
|
118
|
+
compiled.paramNames.forEach((name, i) => {
|
|
119
|
+
resolverParams[name] = m[i + 1] ?? "";
|
|
120
|
+
});
|
|
121
|
+
try {
|
|
122
|
+
const result = await compiled.resolver.resolve({
|
|
123
|
+
pathname,
|
|
124
|
+
params: resolverParams,
|
|
125
|
+
locale: typeof params.locale === "string" ? params.locale : void 0,
|
|
126
|
+
services: ctx.services
|
|
127
|
+
});
|
|
128
|
+
if (result) return result;
|
|
129
|
+
} catch (err) {
|
|
130
|
+
ctx[MARK_METADATA_DEGRADED]?.();
|
|
131
|
+
console.warn("[seo] dynamic resolver threw, falling through to fallback", err);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
const fallback = fallbackEntries.find((entry) => normalizePathname(entry.path) === pathname);
|
|
135
|
+
if (!fallback) return null;
|
|
136
|
+
const meta = { ...fallback };
|
|
137
|
+
delete meta.path;
|
|
138
|
+
delete meta.group;
|
|
139
|
+
return meta;
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
function defineAdminSiteHooks(options = {}) {
|
|
143
|
+
return createAdminSiteHooks(options, createEmptyRuntimeConfig());
|
|
144
|
+
}
|
|
145
|
+
function createAdminSeoEntry(seo, runtimeSeo) {
|
|
146
|
+
return {
|
|
147
|
+
load: createAdminSeoLoader({
|
|
148
|
+
endpoint: seo.endpoint ?? runtimeSeo.endpoint,
|
|
149
|
+
fallbackEntries: normalizeAdminSeoFallbackEntries(seo.fallbackLocal ?? runtimeSeo.fallbackLocal),
|
|
150
|
+
timeoutMs: seo.timeoutMs ?? runtimeSeo.timeoutMs,
|
|
151
|
+
dynamicResolvers: seo.dynamicResolvers ?? runtimeSeo.dynamicResolvers
|
|
152
|
+
}),
|
|
153
|
+
ttl: seo.ttl ?? runtimeSeo.ttl ?? 6e4
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
function createAdminSiteHooks(options, runtime) {
|
|
157
|
+
const runtimeI18n = runtime.i18n ?? {};
|
|
158
|
+
const runtimeSeo = runtime.seo ?? {};
|
|
159
|
+
const i18n = options.i18n ?? {};
|
|
160
|
+
const seo = options.seo ?? {};
|
|
161
|
+
const fallbackMessages = i18n.fallbackLocal ?? runtimeI18n.fallbackLocal ?? {};
|
|
162
|
+
const locales = i18n.locales ?? runtimeI18n.locales ?? (Object.keys(fallbackMessages).length > 0 ? Object.keys(fallbackMessages) : ["en"]);
|
|
163
|
+
const defaultLocale = i18n.defaultLocale ?? runtimeI18n.defaultLocale ?? locales[0] ?? "en";
|
|
164
|
+
const output = createSiteHooks({
|
|
165
|
+
beforeRequest: options.beforeRequest,
|
|
166
|
+
onError: options.onError,
|
|
167
|
+
headExtras: options.headExtras,
|
|
168
|
+
intl: {
|
|
169
|
+
locales,
|
|
170
|
+
defaultLocale,
|
|
171
|
+
prefixDefault: i18n.prefixDefault ?? runtimeI18n.prefixDefault,
|
|
172
|
+
detect: i18n.detect,
|
|
173
|
+
load: createAdminIntlLoader({
|
|
174
|
+
endpoint: i18n.endpoint ?? runtimeI18n.endpoint,
|
|
175
|
+
fallbackMessages,
|
|
176
|
+
defaultLocale,
|
|
177
|
+
timeoutMs: i18n.timeoutMs ?? runtimeI18n.timeoutMs,
|
|
178
|
+
remoteSource: i18n.remoteSource ?? runtimeI18n.remoteSource,
|
|
179
|
+
fallbackSource: i18n.fallbackSource ?? runtimeI18n.fallbackSource
|
|
180
|
+
}),
|
|
181
|
+
ttl: i18n.ttl ?? runtimeI18n.ttl ?? 6e4
|
|
182
|
+
},
|
|
183
|
+
seo: { "/*": createAdminSeoEntry(seo, runtimeSeo) }
|
|
184
|
+
}, runtime);
|
|
185
|
+
Object.defineProperty(output, "__configureRuntime", {
|
|
186
|
+
enumerable: false,
|
|
187
|
+
configurable: true,
|
|
188
|
+
value: (nextRuntime) => createAdminSiteHooks(options, nextRuntime)
|
|
189
|
+
});
|
|
190
|
+
return output;
|
|
191
|
+
}
|
|
192
|
+
function defineSiteHooks(config) {
|
|
193
|
+
return createSiteHooks(config, createEmptyRuntimeConfig());
|
|
194
|
+
}
|
|
195
|
+
function applyRuntimeToServerHooks(hooks, runtime) {
|
|
196
|
+
const maybeRuntimeAware = hooks;
|
|
197
|
+
if (typeof maybeRuntimeAware.__configureRuntime === "function") return maybeRuntimeAware.__configureRuntime(runtime);
|
|
198
|
+
const baseHooks = hooks;
|
|
199
|
+
const services = resolveRuntimeServices(runtime);
|
|
200
|
+
const siteBaseUrl = baseHooks.siteBaseUrl ?? runtime.site;
|
|
201
|
+
const apiBaseUrl = baseHooks.apiBaseUrl ?? services.api;
|
|
202
|
+
const hasUserContentHooks = !!baseHooks.intl || typeof baseHooks.loadIntl === "function" || typeof baseHooks.loadSeoMeta === "function";
|
|
203
|
+
if (!hasUserContentHooks && hasRuntimeContentConfig(runtime)) {
|
|
204
|
+
const runtimeHooks = createAdminSiteHooks({
|
|
205
|
+
beforeRequest: baseHooks.beforeRequest,
|
|
206
|
+
onError: baseHooks.onError
|
|
207
|
+
}, runtime);
|
|
208
|
+
return {
|
|
209
|
+
...hooks,
|
|
210
|
+
siteBaseUrl,
|
|
211
|
+
apiBaseUrl,
|
|
212
|
+
intl: runtimeHooks.intl,
|
|
213
|
+
beforeRequest: runtimeHooks.beforeRequest,
|
|
214
|
+
loadIntl: runtimeHooks.loadIntl,
|
|
215
|
+
loadSeoMeta: runtimeHooks.loadSeoMeta,
|
|
216
|
+
onError: runtimeHooks.onError
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
const runtimeSeo = runtime.seo;
|
|
220
|
+
const runtimeSeoHook = !hasUserContentHooks && runtimeSeo?.dynamicResolvers?.length ? createSiteHooks({
|
|
221
|
+
intl: runtime.i18n,
|
|
222
|
+
seo: { "/*": createAdminSeoEntry({}, runtimeSeo) }
|
|
223
|
+
}, runtime).loadSeoMeta : void 0;
|
|
224
|
+
return {
|
|
225
|
+
...hooks,
|
|
226
|
+
siteBaseUrl,
|
|
227
|
+
apiBaseUrl,
|
|
228
|
+
...runtimeSeoHook && { loadSeoMeta: runtimeSeoHook }
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
function createSiteHooks(config, runtime) {
|
|
232
|
+
const services = resolveRuntimeServices(runtime);
|
|
233
|
+
const api = services.api ?? "";
|
|
234
|
+
const site = runtime.site ?? "";
|
|
235
|
+
const runtimeCtx = {
|
|
236
|
+
runtime,
|
|
237
|
+
services,
|
|
238
|
+
telemetry: services.telemetry,
|
|
239
|
+
site: site || void 0
|
|
240
|
+
};
|
|
241
|
+
const metadataContext = (markDegraded) => ({
|
|
242
|
+
...runtimeCtx,
|
|
243
|
+
[MARK_METADATA_DEGRADED]: markDegraded
|
|
244
|
+
});
|
|
245
|
+
const fetchJson = (path, markDegraded) => api ? fetchMetadataJson(api + path, null, markDegraded) : Promise.resolve(null);
|
|
246
|
+
const runtimeLocale = runtime.i18n;
|
|
247
|
+
const rememberLocale = runtimeLocale?.prefixDefault && runtimeLocale.rememberLocale;
|
|
248
|
+
const intlCfg = rememberLocale ? {
|
|
249
|
+
...config.intl,
|
|
250
|
+
...resolveI18nConfig(runtimeLocale)
|
|
251
|
+
} : config.intl ?? {};
|
|
252
|
+
const supportedLocales = intlCfg.locales?.length ? intlCfg.locales : void 0;
|
|
253
|
+
const negotiationConfig = supportedLocales ? resolveI18nConfig(intlCfg) : {
|
|
254
|
+
locales: ["zh-CN", "en"],
|
|
255
|
+
defaultLocale: intlCfg.defaultLocale ?? "zh-CN"
|
|
256
|
+
};
|
|
257
|
+
const detectLocale = intlCfg.detect ?? ((req) => {
|
|
258
|
+
if (supportedLocales) try {
|
|
259
|
+
const pathname = new URL(req.url).pathname;
|
|
260
|
+
const cleanPath = pathname.endsWith("_.rsc") ? pathname.slice(0, -5) || "/" : pathname;
|
|
261
|
+
const first = cleanPath.split("/")[1];
|
|
262
|
+
if (first && supportedLocales.includes(first)) return first;
|
|
263
|
+
if (cleanPath === "/" && rememberLocale && runtimeLocale) {
|
|
264
|
+
const preference = readLocalePreference(req, runtimeLocale);
|
|
265
|
+
if (preference) return preference;
|
|
266
|
+
}
|
|
267
|
+
} catch {}
|
|
268
|
+
const localeCookie = readCookie(req, "locale");
|
|
269
|
+
if (localeCookie) {
|
|
270
|
+
const matchedCookie = supportedLocales ? matchConfiguredLocale(localeCookie, supportedLocales) : localeCookie;
|
|
271
|
+
if (matchedCookie) return matchedCookie;
|
|
272
|
+
}
|
|
273
|
+
return negotiateLocale(req.headers.get("accept-language"), negotiationConfig);
|
|
274
|
+
});
|
|
275
|
+
const intlLoader = createCachedFetcher({
|
|
276
|
+
key: (locale) => `intl:${locale}`,
|
|
277
|
+
ttl: intlCfg.ttl ?? 6e4,
|
|
278
|
+
swr: true,
|
|
279
|
+
onDegraded: markUncacheable,
|
|
280
|
+
fetch: async (locale, markDegraded) => {
|
|
281
|
+
if (intlCfg.load) return await intlCfg.load(locale, metadataContext(markDegraded)) ?? {
|
|
282
|
+
locale,
|
|
283
|
+
messages: {},
|
|
284
|
+
direction: rtlOf(locale)
|
|
285
|
+
};
|
|
286
|
+
if (intlCfg.endpoint) {
|
|
287
|
+
const url = fillTemplate(intlCfg.endpoint, { locale });
|
|
288
|
+
const json = await fetchJson(url, markDegraded);
|
|
289
|
+
if (json !== null && intlCfg.transform) {
|
|
290
|
+
const transformed = await intlCfg.transform(json, locale);
|
|
291
|
+
if (transformed) return {
|
|
292
|
+
...transformed,
|
|
293
|
+
direction: transformed.direction ?? rtlOf(transformed.locale)
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
return {
|
|
297
|
+
locale,
|
|
298
|
+
messages: extractIntlMessages(json),
|
|
299
|
+
direction: rtlOf(locale)
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
return {
|
|
303
|
+
locale,
|
|
304
|
+
messages: {},
|
|
305
|
+
direction: rtlOf(locale)
|
|
306
|
+
};
|
|
307
|
+
},
|
|
308
|
+
fallback: (locale) => ({
|
|
309
|
+
locale,
|
|
310
|
+
messages: {},
|
|
311
|
+
direction: rtlOf(locale)
|
|
312
|
+
})
|
|
313
|
+
});
|
|
314
|
+
const seoRoutes = [];
|
|
315
|
+
const seoCaches = [];
|
|
316
|
+
const seoLocaleConfig = supportedLocales ? resolveI18nConfig(intlCfg) : void 0;
|
|
317
|
+
const seoPath = (pathname) => seoLocaleConfig ? parseLocale(pathname, seoLocaleConfig).pathname : pathname;
|
|
318
|
+
for (const [pattern, value] of Object.entries(config.seo ?? {})) {
|
|
319
|
+
const { re, paramNames } = compileSeoPattern(pattern);
|
|
320
|
+
if (typeof value === "function") {
|
|
321
|
+
const resolve = value;
|
|
322
|
+
seoRoutes.push({
|
|
323
|
+
re,
|
|
324
|
+
paramNames,
|
|
325
|
+
resolver: ({ params }) => resolve(params)
|
|
326
|
+
});
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
if ("endpoint" in value && typeof value.endpoint === "string") {
|
|
330
|
+
const remote = value;
|
|
331
|
+
const cache = createCachedFetcher({
|
|
332
|
+
key: (request) => JSON.stringify(request),
|
|
333
|
+
ttl: remote.ttl ?? 3e5,
|
|
334
|
+
onDegraded: markUncacheable,
|
|
335
|
+
fetch: async ({ params }, markDegraded) => {
|
|
336
|
+
const data = await fetchJson(fillTemplate(remote.endpoint, params), markDegraded);
|
|
337
|
+
if (data === null) return null;
|
|
338
|
+
return remote.transform(data, { ...params });
|
|
339
|
+
},
|
|
340
|
+
fallback: () => null
|
|
341
|
+
});
|
|
342
|
+
seoCaches.push(cache);
|
|
343
|
+
seoRoutes.push({
|
|
344
|
+
re,
|
|
345
|
+
paramNames,
|
|
346
|
+
resolver: cache
|
|
347
|
+
});
|
|
348
|
+
continue;
|
|
349
|
+
}
|
|
350
|
+
if ("load" in value && typeof value.load === "function") {
|
|
351
|
+
const local = value;
|
|
352
|
+
const cache = createCachedFetcher({
|
|
353
|
+
key: (request) => JSON.stringify(request),
|
|
354
|
+
ttl: local.ttl ?? 3e5,
|
|
355
|
+
onDegraded: markUncacheable,
|
|
356
|
+
fetch: async ({ params }, markDegraded) => local.load({ ...params }, metadataContext(markDegraded)),
|
|
357
|
+
fallback: () => null
|
|
358
|
+
});
|
|
359
|
+
seoCaches.push(cache);
|
|
360
|
+
seoRoutes.push({
|
|
361
|
+
re,
|
|
362
|
+
paramNames,
|
|
363
|
+
resolver: cache
|
|
364
|
+
});
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
const staticMeta = value;
|
|
368
|
+
const withDefaults = {
|
|
369
|
+
...staticMeta,
|
|
370
|
+
canonical: staticMeta.canonical ?? (site && pattern && pattern !== "/*" ? `${site}${pattern}` : staticMeta.canonical)
|
|
371
|
+
};
|
|
372
|
+
seoRoutes.push({
|
|
373
|
+
re,
|
|
374
|
+
paramNames,
|
|
375
|
+
resolver: () => withDefaults
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
const platformOnError = createPlatformOnError(runtime, runtimeCtx);
|
|
379
|
+
const onError = async (err, req, ctx) => {
|
|
380
|
+
platformOnError(err, req, ctx);
|
|
381
|
+
if (config.onError) await config.onError(err, req, ctx);
|
|
382
|
+
};
|
|
383
|
+
const output = {
|
|
384
|
+
siteBaseUrl: site || void 0,
|
|
385
|
+
apiBaseUrl: api || void 0,
|
|
386
|
+
intl: rememberLocale ? intlCfg : config.intl,
|
|
387
|
+
headExtras: config.headExtras,
|
|
388
|
+
async beforeRequest(req, _engineCtx) {
|
|
389
|
+
return {
|
|
390
|
+
locale: detectLocale(req),
|
|
391
|
+
...config.beforeRequest ? await config.beforeRequest(req) : {}
|
|
392
|
+
};
|
|
393
|
+
},
|
|
394
|
+
async loadIntl(req) {
|
|
395
|
+
return intlLoader(detectLocale(req));
|
|
396
|
+
},
|
|
397
|
+
async loadSeoMeta(req) {
|
|
398
|
+
const url = new URL(req.url);
|
|
399
|
+
const locale = detectLocale(req);
|
|
400
|
+
const pathForRouting = url.pathname.endsWith("_.rsc") ? url.pathname.slice(0, -5) || "/" : url.pathname;
|
|
401
|
+
const cleanPath = seoPath(pathForRouting);
|
|
402
|
+
for (const { re, paramNames, resolver } of seoRoutes) {
|
|
403
|
+
const m = cleanPath.match(re);
|
|
404
|
+
if (m) {
|
|
405
|
+
const params = {
|
|
406
|
+
pathname: cleanPath,
|
|
407
|
+
locale
|
|
408
|
+
};
|
|
409
|
+
paramNames.forEach((n, i) => params[n] = m[i + 1] ?? "");
|
|
410
|
+
return await resolver({
|
|
411
|
+
pathname: cleanPath,
|
|
412
|
+
locale,
|
|
413
|
+
params
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
return null;
|
|
418
|
+
},
|
|
419
|
+
onError
|
|
420
|
+
};
|
|
421
|
+
const invalidate = (scopes) => {
|
|
422
|
+
const locales = new Set(scopes.locales);
|
|
423
|
+
if (scopes.allPageMetadata || locales.size) intlLoader.invalidate((locale) => !!scopes.allPageMetadata || locales.has(locale.toLowerCase()));
|
|
424
|
+
if (scopes.allPageMetadata || scopes.tags.length) {
|
|
425
|
+
for (const cache of seoCaches) cache.invalidate();
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
if (!scopes.paths.length && !locales.size) return;
|
|
429
|
+
const paths = new Set(scopes.paths.map((pathname) => trimTrailingSlashes(seoPath(contentPathname(pathname)))));
|
|
430
|
+
for (const cache of seoCaches) cache.invalidate(({ pathname, locale }) => paths.has(trimTrailingSlashes(pathname)) || locales.has(locale.toLowerCase()));
|
|
431
|
+
};
|
|
432
|
+
Object.defineProperty(output.loadIntl, CONTENT_INVALIDATOR, { value: invalidate });
|
|
433
|
+
Object.defineProperty(output.loadSeoMeta, CONTENT_INVALIDATOR, { value: invalidate });
|
|
434
|
+
registerContentInvalidator(invalidate, { weak: true });
|
|
435
|
+
Object.defineProperty(output, "__configureRuntime", {
|
|
436
|
+
enumerable: false,
|
|
437
|
+
configurable: true,
|
|
438
|
+
value: (nextRuntime) => createSiteHooks(config, nextRuntime)
|
|
439
|
+
});
|
|
440
|
+
return output;
|
|
441
|
+
}
|
|
442
|
+
function rtlOf(locale) {
|
|
443
|
+
return /^(ar|he|fa|ur)/.test(locale) ? "rtl" : "ltr";
|
|
444
|
+
}
|
|
445
|
+
function matchConfiguredLocale(value, supportedLocales) {
|
|
446
|
+
const lower = value.toLowerCase();
|
|
447
|
+
const exact = supportedLocales.find((locale) => locale.toLowerCase() === lower);
|
|
448
|
+
if (exact) return exact;
|
|
449
|
+
const prefix = lower.split("-")[0];
|
|
450
|
+
return supportedLocales.find((locale) => locale.toLowerCase().split("-")[0] === prefix);
|
|
451
|
+
}
|
|
452
|
+
function extractIntlMessages(data) {
|
|
453
|
+
return extractIntlMessagesOrNull(data) ?? {};
|
|
454
|
+
}
|
|
455
|
+
function extractIntlMessagesOrNull(data) {
|
|
456
|
+
if (!data || typeof data !== "object") return null;
|
|
457
|
+
const raw = data;
|
|
458
|
+
const dataValue = raw.data;
|
|
459
|
+
const candidate = raw.strings ?? raw.messages ?? (isRecord(dataValue) && "strings" in dataValue ? dataValue.strings : dataValue);
|
|
460
|
+
if (!candidate || typeof candidate !== "object") return null;
|
|
461
|
+
return normalizeMessages(candidate);
|
|
462
|
+
}
|
|
463
|
+
function normalizeMessages(messages) {
|
|
464
|
+
if (isFlatRecord(messages)) return expandDottedRecord(messages);
|
|
465
|
+
return messages;
|
|
466
|
+
}
|
|
467
|
+
/**
|
|
468
|
+
* 逐层剥 envelope —— admin 在不同分支返回三种 shape:
|
|
469
|
+
* - flat:`{ title, description, ... }`(admin no-locale fast path)
|
|
470
|
+
* - 单层:`{ data: { title, ... } }`(旧版本)
|
|
471
|
+
* - 双层:`{ status, code, data: { data: { title, ... }, version } }`
|
|
472
|
+
* (api-envelope plugin 包了一层,resolvePublic 自己又是 `{ data, version }`,
|
|
473
|
+
* 所以 locale-aware 路径会双层 wrap)
|
|
474
|
+
*
|
|
475
|
+
* 停止条件:候选对象有 `title` / `description`(SEO 形状),或没有 `data` 字段可剥。
|
|
476
|
+
*/
|
|
477
|
+
function extractSeoMetaOrNull(data) {
|
|
478
|
+
let candidate = data;
|
|
479
|
+
for (let i = 0; i < 4; i++) {
|
|
480
|
+
if (!isRecord(candidate)) return null;
|
|
481
|
+
if ("title" in candidate || "description" in candidate) break;
|
|
482
|
+
if ("data" in candidate) {
|
|
483
|
+
candidate = candidate.data;
|
|
484
|
+
continue;
|
|
485
|
+
}
|
|
486
|
+
return null;
|
|
487
|
+
}
|
|
488
|
+
if (!isRecord(candidate)) return null;
|
|
489
|
+
return candidate;
|
|
490
|
+
}
|
|
491
|
+
function normalizeAdminSeoFallbackEntries(entries = []) {
|
|
492
|
+
return entries.filter((entry) => typeof entry.path === "string");
|
|
493
|
+
}
|
|
494
|
+
function createPlatformOnError(runtime, ctx) {
|
|
495
|
+
const reportServerError = createServerErrorEndpointReporter(runtime, ctx);
|
|
496
|
+
return (err, req, errorCtx) => {
|
|
497
|
+
console.error("[onError]", {
|
|
498
|
+
traceId: errorCtx.traceId,
|
|
499
|
+
locale: errorCtx.locale,
|
|
500
|
+
url: req.url,
|
|
501
|
+
msg: err instanceof Error ? err.message : String(err)
|
|
502
|
+
});
|
|
503
|
+
reportServerError?.(err, req, errorCtx);
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
function createServerErrorEndpointReporter(runtime, ctx) {
|
|
507
|
+
const config = runtime.telemetry;
|
|
508
|
+
if (config === false || !config || config.errors === false) return null;
|
|
509
|
+
const endpoint = resolveAdminUrl((config.errors ?? {}).endpoint ?? "/api/observability/errors", {}, ctx, { baseUrl: (runtimeCtx) => runtimeCtx.services.telemetry ?? runtimeCtx.services.api });
|
|
510
|
+
if (!endpoint) return null;
|
|
511
|
+
const app = config.app ?? "isr-engine-app";
|
|
512
|
+
const release = config.release;
|
|
513
|
+
const environment = config.environment;
|
|
514
|
+
const includeQueryString = config.includeQueryString === true;
|
|
515
|
+
return (err, req, errorCtx) => {
|
|
516
|
+
const id = createServerReportId();
|
|
517
|
+
if (!id) return;
|
|
518
|
+
const report = normalizeServerErrorReport(err, req, errorCtx, {
|
|
519
|
+
id,
|
|
520
|
+
release,
|
|
521
|
+
environment,
|
|
522
|
+
includeQueryString
|
|
523
|
+
});
|
|
524
|
+
fetch(endpoint, {
|
|
525
|
+
method: "POST",
|
|
526
|
+
headers: {
|
|
527
|
+
"content-type": "application/json",
|
|
528
|
+
accept: "application/json"
|
|
529
|
+
},
|
|
530
|
+
body: JSON.stringify({
|
|
531
|
+
app,
|
|
532
|
+
sentAt: Date.now(),
|
|
533
|
+
reports: [report]
|
|
534
|
+
}),
|
|
535
|
+
signal: typeof AbortSignal !== "undefined" ? AbortSignal.timeout(1e3) : void 0
|
|
536
|
+
}).catch(() => {});
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
function normalizeServerErrorReport(err, req, ctx, options) {
|
|
540
|
+
const error = err instanceof Error ? err : null;
|
|
541
|
+
const message = error?.message || String(err);
|
|
542
|
+
const name = error?.name || "Error";
|
|
543
|
+
const url = safeRequestPath(req.url, options.includeQueryString);
|
|
544
|
+
return {
|
|
545
|
+
id: options.id,
|
|
546
|
+
ts: Date.now(),
|
|
547
|
+
level: "error",
|
|
548
|
+
message,
|
|
549
|
+
name,
|
|
550
|
+
stack: error?.stack,
|
|
551
|
+
release: options.release,
|
|
552
|
+
environment: options.environment,
|
|
553
|
+
url,
|
|
554
|
+
source: "server-render",
|
|
555
|
+
tags: {
|
|
556
|
+
traceId: ctx.traceId,
|
|
557
|
+
locale: ctx.locale
|
|
558
|
+
},
|
|
559
|
+
extra: {
|
|
560
|
+
method: req.method,
|
|
561
|
+
pathname: url.split("?")[0] || "/"
|
|
562
|
+
},
|
|
563
|
+
fingerprint: [
|
|
564
|
+
"server-render",
|
|
565
|
+
name,
|
|
566
|
+
message.slice(0, 160)
|
|
567
|
+
]
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
function safeRequestPath(rawUrl, includeQueryString) {
|
|
571
|
+
try {
|
|
572
|
+
const url = new URL(rawUrl);
|
|
573
|
+
return includeQueryString ? `${url.pathname}${url.search}` : url.pathname;
|
|
574
|
+
} catch {
|
|
575
|
+
return includeQueryString ? rawUrl : "/";
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
function createServerReportId() {
|
|
579
|
+
try {
|
|
580
|
+
return `srv_${crypto.randomUUID()}`;
|
|
581
|
+
} catch {
|
|
582
|
+
return null;
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
async function fetchMetadataJson(url, timeoutMs = 1200, markDegraded) {
|
|
586
|
+
try {
|
|
587
|
+
const response = timeoutMs === null ? await fetch(url) : await fetch(url, {
|
|
588
|
+
headers: { Accept: "application/json" },
|
|
589
|
+
signal: timeoutMs > 0 ? AbortSignal.timeout(timeoutMs) : void 0
|
|
590
|
+
});
|
|
591
|
+
if (!response.ok) {
|
|
592
|
+
if (response.status !== 404) markDegraded?.();
|
|
593
|
+
response.body?.cancel().catch(() => void 0);
|
|
594
|
+
return null;
|
|
595
|
+
}
|
|
596
|
+
if (response.status === 204) return null;
|
|
597
|
+
return await response.json();
|
|
598
|
+
} catch {
|
|
599
|
+
markDegraded?.();
|
|
600
|
+
return null;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
function resolveAdminUrl(endpoint, vars, ctx, options = {}) {
|
|
604
|
+
const filled = fillTemplate(endpoint, vars);
|
|
605
|
+
if (/^(https?:)?\/\//i.test(filled)) return filled;
|
|
606
|
+
const base = resolveRuntimeServiceBase(ctx, options.baseUrl);
|
|
607
|
+
if (!base) return null;
|
|
608
|
+
return `${trimTrailingSlashes(base)}/${filled.replace(/^\/+/, "")}`;
|
|
609
|
+
}
|
|
610
|
+
function resolveRuntimeServiceBase(ctx, baseUrl) {
|
|
611
|
+
if (typeof baseUrl === "function") return baseUrl(ctx) ?? null;
|
|
612
|
+
if (baseUrl) return baseUrl;
|
|
613
|
+
return ctx.services.api ?? null;
|
|
614
|
+
}
|
|
615
|
+
function resolveRuntimeServices(runtime) {
|
|
616
|
+
const services = runtime.services ?? {};
|
|
617
|
+
const api = services.api;
|
|
618
|
+
return {
|
|
619
|
+
api,
|
|
620
|
+
telemetry: services.telemetry ?? api
|
|
621
|
+
};
|
|
622
|
+
}
|
|
623
|
+
function hasRuntimeContentConfig(runtime) {
|
|
624
|
+
return !!(runtime.i18n?.endpoint || runtime.i18n?.fallbackLocal || runtime.seo?.endpoint || runtime.seo?.fallbackLocal || runtime.telemetry);
|
|
625
|
+
}
|
|
626
|
+
function normalizePathname(pathname) {
|
|
627
|
+
if (pathname === "/") return "/";
|
|
628
|
+
return trimTrailingSlashes(pathname) || "/";
|
|
629
|
+
}
|
|
630
|
+
function isRecord(value) {
|
|
631
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
632
|
+
}
|
|
633
|
+
function isFlatRecord(value) {
|
|
634
|
+
if (!value || typeof value !== "object") return false;
|
|
635
|
+
return Object.keys(value).some((key) => key.includes("."));
|
|
636
|
+
}
|
|
637
|
+
function expandDottedRecord(flat) {
|
|
638
|
+
const out = {};
|
|
639
|
+
for (const [key, value] of Object.entries(flat)) {
|
|
640
|
+
const parts = key.split(".");
|
|
641
|
+
let cur = out;
|
|
642
|
+
parts.forEach((part, index) => {
|
|
643
|
+
if (index === parts.length - 1) {
|
|
644
|
+
cur[part] = value;
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
const next = cur[part];
|
|
648
|
+
if (!next || typeof next !== "object") cur[part] = {};
|
|
649
|
+
cur = cur[part];
|
|
650
|
+
});
|
|
651
|
+
}
|
|
652
|
+
return out;
|
|
653
|
+
}
|
|
3
654
|
export { applyRuntimeToServerHooks, createAdminIntlLoader, createAdminSeoLoader, defineAdminSiteHooks, defineSiteHooks, getCookieHeader, parseCookieHeader, readCookie };
|
|
655
|
+
|
|
656
|
+
//# sourceMappingURL=defineSiteHooks.js.map
|