@farm.js/plugin 0.1.68 → 0.1.70
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/rsc/config-routes.d.ts +53 -0
- package/dist/rsc/config-routes.d.ts.map +1 -0
- package/dist/rsc/config-routes.js +136 -0
- package/dist/rsc/entries/client.d.ts +2 -0
- package/dist/rsc/entries/client.d.ts.map +1 -1
- package/dist/rsc/entries/client.js +72 -24
- package/dist/rsc/entries/rsc.d.ts +14 -0
- package/dist/rsc/entries/rsc.d.ts.map +1 -1
- package/dist/rsc/entries/rsc.js +1140 -88
- package/dist/rsc/index.d.ts +15 -10
- package/dist/rsc/index.d.ts.map +1 -1
- package/dist/rsc/index.js +190 -30
- package/dist/rsc/test-fixture-dependencies.d.ts +2 -0
- package/dist/rsc/test-fixture-dependencies.d.ts.map +1 -1
- package/dist/rsc/test-fixture-dependencies.js +2 -0
- package/dist/rsc/types.d.ts +53 -4
- package/dist/rsc/types.d.ts.map +1 -1
- package/package.json +4 -4
package/dist/rsc/entries/rsc.js
CHANGED
|
@@ -1,11 +1,261 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
1
2
|
import { createRequire } from "node:module";
|
|
3
|
+
import path from "node:path";
|
|
2
4
|
import { FARM_RSC_MOBILE_SHELL_CLIENT_PLACEHOLDER, FARM_RSC_NATIVE_STYLESHEETS_PLACEHOLDER, } from "../mobile-client.js";
|
|
3
5
|
const require_ = createRequire(import.meta.url);
|
|
6
|
+
/**
|
|
7
|
+
* The import query the entry globs static `opengraph-image`/`twitter-image` files with. The
|
|
8
|
+
* plugin's loader answers it with the file's info and bytes (index.ts).
|
|
9
|
+
*/
|
|
10
|
+
export const FARM_METADATA_IMAGE_QUERY = "?farm-metadata-image";
|
|
4
11
|
/** Core's production source for the \`mcp\` plugin, so both servers merge config the same way. */
|
|
5
12
|
function generateMCPPluginSource() {
|
|
6
13
|
const { generateNativeMCPPluginSource } = require_("@farm.js/core/internal/production-runtime");
|
|
7
14
|
return generateNativeMCPPluginSource({ enabled: true });
|
|
8
15
|
}
|
|
16
|
+
/** Each locale's catalog file, where core's i18n config resolves it (resolveFarmI18nMessagePath). */
|
|
17
|
+
function farmI18nCatalogFiles(i18n) {
|
|
18
|
+
return i18n.locales.map((locale) => i18n.messages.includes("{locale}")
|
|
19
|
+
? i18n.messages.split("{locale}").join(locale)
|
|
20
|
+
: path.join(i18n.messages, `${locale}.json`));
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The request locale of an app with i18n, from core's runtime: each request resolves its locale
|
|
24
|
+
* as in core's servers, so `getLocale()`, `t()` and `format` from `@farm.js/core/i18n/server`
|
|
25
|
+
* work in server components, server actions, route handlers and middleware, and client
|
|
26
|
+
* components read the same locale.
|
|
27
|
+
*/
|
|
28
|
+
function generateI18nRuntime(ctx, i18n) {
|
|
29
|
+
const catalogs = ctx.development === true
|
|
30
|
+
? `// Development reads the catalogs from disk, as core's dev server does. Importing them makes an
|
|
31
|
+
// edited catalog reload this entry; a missing one fails initialize() with core's error.
|
|
32
|
+
${farmI18nCatalogFiles(i18n)
|
|
33
|
+
.filter((file) => existsSync(file))
|
|
34
|
+
.map((file) => `import ${JSON.stringify(`${file.replace(/\\/g, "/")}?raw`)};`)
|
|
35
|
+
.join("\n")}
|
|
36
|
+
const farmI18nRuntime = createFarmI18nRuntime(farmRouteI18n);
|
|
37
|
+
await farmI18nRuntime.initialize();`
|
|
38
|
+
: `// The catalogs the build read and validated, inlined as core's build inlines them.
|
|
39
|
+
const farmI18nRuntime = createFarmI18nRuntime(farmRouteI18n, ${JSON.stringify(ctx.i18nCatalogs ?? {})});`;
|
|
40
|
+
return `import {
|
|
41
|
+
_runWithFarmI18nRequest,
|
|
42
|
+
_setDefaultFarmI18nRuntime,
|
|
43
|
+
createFarmI18nRuntime,
|
|
44
|
+
getFarmI18nClientSnapshot,
|
|
45
|
+
} from '@farm.js/core/i18n/server';
|
|
46
|
+
import {
|
|
47
|
+
createFarmLocaleCookie,
|
|
48
|
+
getFarmLocaleVaryHeaders,
|
|
49
|
+
localizeFarmHref,
|
|
50
|
+
localizeFarmPathname,
|
|
51
|
+
renderFarmLocaleAlternateLinks,
|
|
52
|
+
resolveFarmWebRequestOrigin as resolveFarmI18nRequestOrigin,
|
|
53
|
+
} from '@farm.js/core/internal/production-runtime';
|
|
54
|
+
${catalogs}
|
|
55
|
+
// createTranslator(locale) and runWithLocale() outside a request.
|
|
56
|
+
_setDefaultFarmI18nRuntime(farmI18nRuntime);
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Runs a request in its locale, as core's servers do. A page GET whose URL lacks the locale the
|
|
60
|
+
* visitor's cookie or Accept-Language picks is redirected to it (307), and a payload request to
|
|
61
|
+
* that page's payload; a response that depends on those signals varies on them and stays out of
|
|
62
|
+
* shared caches. API routes keep their URLs, as in core, and so does the image optimizer, which
|
|
63
|
+
* this server answers only at its path. Core's resolver answers site-level agent files
|
|
64
|
+
* (llms.txt, sitemap.xml, robots.txt) where they are asked for, without a redirect, as in core.
|
|
65
|
+
*/
|
|
66
|
+
async function runFarmLocalizedRequest(request, payloadRequested, render) {
|
|
67
|
+
const { pathname } = new URL(request.url);
|
|
68
|
+
const redirect =
|
|
69
|
+
!isFarmAPIPathname(pathname, farmApiBasePath) &&
|
|
70
|
+
!isFarmAPIPathname(pathname) &&
|
|
71
|
+
pathname !== farmImagePath;
|
|
72
|
+
return _runWithFarmI18nRequest(farmI18nRuntime, request, async (resolution) => {
|
|
73
|
+
if (resolution.redirect && (request.method === 'GET' || request.method === 'HEAD')) {
|
|
74
|
+
let location = resolution.redirect;${ctx.trailingSlash
|
|
75
|
+
? `
|
|
76
|
+
// With trailingSlash a page answers at '/fr/about/': send the visitor there at once rather
|
|
77
|
+
// than through the trailing-slash 308 that would follow (core's renderers redirect twice).
|
|
78
|
+
const localized = new URL(location, request.url);
|
|
79
|
+
if (matchRoute(localized.pathname)) {
|
|
80
|
+
location = normalizeFarmTrailingSlashPathname(localized.pathname, true) + localized.search;
|
|
81
|
+
}`
|
|
82
|
+
: ""}
|
|
83
|
+
if (payloadRequested) {
|
|
84
|
+
const target = new URL(location, request.url);
|
|
85
|
+
location = farmPayloadPath(target.pathname) + target.search;
|
|
86
|
+
}
|
|
87
|
+
return applyFarmI18nResponse(new Response(null, { status: 307, headers: { location } }), resolution);
|
|
88
|
+
}
|
|
89
|
+
return applyFarmI18nResponse(await render(), resolution);
|
|
90
|
+
}, { redirect });
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* redirect('/about') from a French page sends /fr/about, below the basePath, as core's servers
|
|
95
|
+
* localize a redirect: pages, server actions and form submissions alike. A URL that is not
|
|
96
|
+
* app-relative stays as written.
|
|
97
|
+
*/
|
|
98
|
+
function localizeFarmRedirectUrl(url) {
|
|
99
|
+
const snapshot = getFarmI18nClientSnapshot();
|
|
100
|
+
return snapshot && url.startsWith('/') && !url.startsWith('//')
|
|
101
|
+
? localizeFarmHref(url, snapshot.locale, snapshot)
|
|
102
|
+
: url;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* The page's \`<link rel="alternate" hreflang>\` tags, as core's servers render them: its URL in each
|
|
107
|
+
* locale and x-default, absolute on the route's metadataBase, else on the request's origin (under
|
|
108
|
+
* server.trustProxy). A prerendered page, which no visitor's request drives, uses metadataBase
|
|
109
|
+
* only, as core's background regeneration does.
|
|
110
|
+
*/
|
|
111
|
+
function renderFarmI18nAlternateLinks(request, pathname, metadata) {
|
|
112
|
+
const snapshot = getFarmI18nClientSnapshot();
|
|
113
|
+
if (!snapshot) return '';
|
|
114
|
+
return renderFarmLocaleAlternateLinks(pathname, snapshot, {
|
|
115
|
+
metadataBase: metadata.metadataBase,
|
|
116
|
+
origin: isFarmPrerenderRequest(request)
|
|
117
|
+
? undefined
|
|
118
|
+
: resolveFarmI18nRequestOrigin(request, { trustProxy: ${JSON.stringify(ctx.server?.trustProxy === true)} }),
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* A root layout that renders \`<html>\` gets the request's \`lang\` and \`dir\` on it, replacing its
|
|
124
|
+
* own, as core's servers set them on any document. They go on the element the layout returns, so
|
|
125
|
+
* the browser hydrates the attributes the HTML has. FarmLocaleDocument renders a synchronous
|
|
126
|
+
* layout in its place, within the render, as React would.
|
|
127
|
+
*/
|
|
128
|
+
function FarmLocaleDocument({ Layout, layoutProps }) {
|
|
129
|
+
const element = Layout(layoutProps);
|
|
130
|
+
return element && typeof element.then === 'function'
|
|
131
|
+
? element.then(withFarmDocumentLocale)
|
|
132
|
+
: withFarmDocumentLocale(element);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function withFarmDocumentLocale(element) {
|
|
136
|
+
const snapshot = getFarmI18nClientSnapshot();
|
|
137
|
+
return snapshot && React.isValidElement(element) && element.type === 'html'
|
|
138
|
+
? React.cloneElement(element, { lang: snapshot.locale, dir: snapshot.direction })
|
|
139
|
+
: element;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function applyFarmI18nResponse(response, resolution) {
|
|
143
|
+
const varyHeaders = getFarmLocaleVaryHeaders(farmRouteI18n, resolution);
|
|
144
|
+
if (!resolution.persist && varyHeaders.length === 0) return response;
|
|
145
|
+
const headers = new Headers(response.headers);
|
|
146
|
+
if (resolution.persist) {
|
|
147
|
+
headers.append('set-cookie', createFarmLocaleCookie(resolution.locale, farmRouteI18n));
|
|
148
|
+
}
|
|
149
|
+
if (varyHeaders.length > 0) {
|
|
150
|
+
const vary = new Set((headers.get('vary') || '').split(',').map((entry) => entry.trim()).filter(Boolean));
|
|
151
|
+
for (const header of varyHeaders) vary.add(header);
|
|
152
|
+
headers.set('vary', [...vary].join(', '));
|
|
153
|
+
headers.set('cache-control', 'private, no-store');
|
|
154
|
+
}
|
|
155
|
+
return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
|
|
156
|
+
}
|
|
157
|
+
`;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* The config `redirects()`, `rewrites()` and `headers()` in the production server, with core's
|
|
161
|
+
* matchers: sources match the path below the basePath and locale, a redirect keeps the query and
|
|
162
|
+
* an internal destination stays below the basePath (in the request's locale under i18n), and a
|
|
163
|
+
* rewrite keeps the query when its destination names none. A payload request ('<page>.rsc')
|
|
164
|
+
* matches as its page and is sent to the destination's payload. Development gets only the check
|
|
165
|
+
* for a local route, which its dev server asks before a rewrite.
|
|
166
|
+
*/
|
|
167
|
+
export function generateConfigRoutesRuntime(ctx, configRoutes, localRouteCheck) {
|
|
168
|
+
if (!configRoutes && !localRouteCheck)
|
|
169
|
+
return "";
|
|
170
|
+
const llms = ctx.llmsTxt?.enabled === true;
|
|
171
|
+
const localRoute = localRouteCheck
|
|
172
|
+
? `
|
|
173
|
+
// Whether this server answers the URL itself: a page, an API route, the image optimizer, a
|
|
174
|
+
// metadata route file or image, or a generated agent file. A config rewrite applies only when
|
|
175
|
+
// none does, as in core's servers.
|
|
176
|
+
function farmHasLocalRequestRoute(url) {
|
|
177
|
+
const pathname = url.pathname;
|
|
178
|
+
if (matchRoute(pathname)) return true;
|
|
179
|
+
if (matchAPIRouteAtBasePath(apiRouteMap, pathname, farmApiBasePath)) return true;
|
|
180
|
+
if (farmImageHandler && pathname === farmImagePath) return true;
|
|
181
|
+
const routePathname = getFarmRoutePathname(pathname.replace(/\\/+$/, '') || '/');${ctx.appMetadataRoutes === true
|
|
182
|
+
? `
|
|
183
|
+
if (matchFarmAppMetadataRoute(routePathname)) return true;`
|
|
184
|
+
: ""}${ctx.metadataImages?.static || ctx.metadataImages?.generated
|
|
185
|
+
? `
|
|
186
|
+
if (matchFarmMetadataImageRequest(routePathname)) return true;`
|
|
187
|
+
: ""}${llms
|
|
188
|
+
? `
|
|
189
|
+
if (routePathname === '/llms.txt' || (farmLlmsTxtConfig.full && routePathname === '/llms-full.txt')) return true;`
|
|
190
|
+
: ""}${ctx.sitemap?.enabled
|
|
191
|
+
? `
|
|
192
|
+
if (routePathname === '/sitemap.xml') return true;`
|
|
193
|
+
: ""}${ctx.crawlers?.enabled === true
|
|
194
|
+
? `
|
|
195
|
+
if (routePathname === '/robots.txt') return true;`
|
|
196
|
+
: ""}
|
|
197
|
+
return false;
|
|
198
|
+
}
|
|
199
|
+
${ctx.development === true
|
|
200
|
+
? `// farm dev applies config rewrites ahead of this entry, and asks it first.
|
|
201
|
+
export function __farmHasLocalRequestRoute(href) {
|
|
202
|
+
return farmHasLocalRequestRoute(new URL(href));
|
|
203
|
+
}
|
|
204
|
+
`
|
|
205
|
+
: ""}`
|
|
206
|
+
: "";
|
|
207
|
+
if (!configRoutes)
|
|
208
|
+
return localRoute;
|
|
209
|
+
return `
|
|
210
|
+
import {
|
|
211
|
+
applyConfigResponseHeaders,
|
|
212
|
+
createConfigHeadersMatcher,
|
|
213
|
+
createConfigRedirectMatcher,
|
|
214
|
+
createConfigRewriteMatcher,
|
|
215
|
+
fetchFarmExternalRewrite,
|
|
216
|
+
} from '@farm.js/core/internal/production-runtime';
|
|
217
|
+
|
|
218
|
+
// The config redirects(), rewrites() and headers(), resolved by the build as core resolves them.
|
|
219
|
+
const farmConfigRouteOptions = { i18n: farmRouteI18n, basePath: ${JSON.stringify(ctx.basePath)} };
|
|
220
|
+
const matchFarmConfigRedirect = createConfigRedirectMatcher(${JSON.stringify(configRoutes.redirects)}, farmConfigRouteOptions);
|
|
221
|
+
const matchFarmConfigRewrite = createConfigRewriteMatcher(${JSON.stringify(configRoutes.rewrites)}, farmConfigRouteOptions);
|
|
222
|
+
const matchFarmConfigHeaders = createConfigHeadersMatcher(${JSON.stringify(configRoutes.headers)}, farmConfigRouteOptions);
|
|
223
|
+
${localRoute}
|
|
224
|
+
/**
|
|
225
|
+
* A config redirect's response, the Request a config rewrite replaces this one with (a payload
|
|
226
|
+
* request's stays one), the proxied response of a rewrite to another origin, or null.
|
|
227
|
+
*/
|
|
228
|
+
async function resolveFarmConfigRoute(request, payloadRequested) {
|
|
229
|
+
const url = new URL(request.url);
|
|
230
|
+
const redirect = matchFarmConfigRedirect(url);
|
|
231
|
+
if (redirect) {
|
|
232
|
+
let location = redirect.destination;
|
|
233
|
+
if (payloadRequested) {
|
|
234
|
+
const target = new URL(location, url);
|
|
235
|
+
if (target.origin === url.origin) location = farmPayloadPath(target.pathname) + target.search;
|
|
236
|
+
}
|
|
237
|
+
return new Response('Redirecting to ' + location, {
|
|
238
|
+
status: redirect.statusCode,
|
|
239
|
+
headers: { Location: location },
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
const destination = matchFarmConfigRewrite(url);
|
|
243
|
+
if (!destination${localRouteCheck ? " || farmHasLocalRequestRoute(url)" : ""}) return null;
|
|
244
|
+
const rewritten = new Request(destination, request);
|
|
245
|
+
if (destination.origin !== url.origin) return fetchFarmExternalRewrite(rewritten);
|
|
246
|
+
if (payloadRequested) farmPayloadRequests.add(rewritten);
|
|
247
|
+
return rewritten;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// A prerendered page is a file the platform serves without this server, so a page a config
|
|
251
|
+
// redirect or rewrite may answer, or that config headers apply to, stays server-rendered.
|
|
252
|
+
function farmConfigRouteMayHandlePath(pathname) {
|
|
253
|
+
const url = new URL(pathname, 'http://farm.invalid');
|
|
254
|
+
return Boolean(matchFarmConfigRedirect(url) || matchFarmConfigRewrite(url)) ||
|
|
255
|
+
matchFarmConfigHeaders(url).length > 0;
|
|
256
|
+
}
|
|
257
|
+
`;
|
|
258
|
+
}
|
|
9
259
|
/**
|
|
10
260
|
* Generates the terminal middleware-result handling shared by the RSC entry
|
|
11
261
|
* and its executable contract tests.
|
|
@@ -37,6 +287,19 @@ export function generateRscMiddlewareResultHandling() {
|
|
|
37
287
|
* - Either returns the stream directly (for client navigation) or delegates to SSR (for initial page load)
|
|
38
288
|
*/
|
|
39
289
|
export function generateRscEntry(ctx) {
|
|
290
|
+
// A root-mounted app without i18n matches pages on the path as received, with no extra work.
|
|
291
|
+
const hasBasePath = !["", "/"].includes(ctx.basePath.trim());
|
|
292
|
+
const i18n = ctx.i18n?.enabled === true ? ctx.i18n : undefined;
|
|
293
|
+
const routesBelowPrefix = hasBasePath || i18n !== undefined;
|
|
294
|
+
// The config redirects(), rewrites() and headers(). This server applies them in production; in
|
|
295
|
+
// development the dev server does, ahead of Vite and the API routes, as core's dev server does.
|
|
296
|
+
const configRoutes = ctx.development === true ? undefined : ctx.configRoutes;
|
|
297
|
+
const configHeaders = (configRoutes?.headers.length ?? 0) > 0;
|
|
298
|
+
// A static or revalidating page gets core's shared Cache-Control in production. farm dev keeps
|
|
299
|
+
// pages out of shared caches, as core's dev server never sends an s-maxage.
|
|
300
|
+
const sharedPageCache = ctx.development !== true;
|
|
301
|
+
const pageCacheArg = sharedPageCache ? ", farmPageCacheControl" : "";
|
|
302
|
+
const localRouteCheck = (ctx.configRoutes?.rewrites.length ?? 0) > 0;
|
|
40
303
|
// Build the glob pattern for discovering routes (Farm convention: src/app when routesDir unset)
|
|
41
304
|
const appSegment = ctx.routesDir === undefined ? "app" : ctx.routesDir.trim();
|
|
42
305
|
const glob = appSegment ? `/${ctx.srcDir}/${appSegment}` : `/${ctx.srcDir}`;
|
|
@@ -95,7 +358,7 @@ import {
|
|
|
95
358
|
applyProductionMiddlewareHeaders,
|
|
96
359
|
createProductionMiddlewareRunner,
|
|
97
360
|
} from '@farm.js/core/middleware';
|
|
98
|
-
import { _withFarmGuardedResponseCache } from '@farm.js/core/internal/production-runtime';
|
|
361
|
+
import { _withFarmGuardedResponseCache, _withFarmResponseHeaders } from '@farm.js/core/internal/production-runtime';
|
|
99
362
|
${ctx.mobileClient === "entry" ? "import { _applyFarmMobileShellClient, createFarmNativeTreeResponse, resolveFarmWebRequestOrigin } from '@farm.js/core/internal/production-runtime';\n" : ctx.mobileClient === "inline" ? "import { createFarmNativeTreeResponse, resolveFarmWebRequestOrigin } from '@farm.js/core/internal/production-runtime';\n" : ""}import {
|
|
100
363
|
getAllowedAPIRouteMethods,
|
|
101
364
|
invokeAPIRouteEndpoint,
|
|
@@ -121,7 +384,14 @@ import {
|
|
|
121
384
|
renderMetadataHead,
|
|
122
385
|
resolveMetadataTitle,
|
|
123
386
|
} from '@farm.js/core/internal/production-runtime';
|
|
124
|
-
|
|
387
|
+
${sharedPageCache
|
|
388
|
+
? `import {
|
|
389
|
+
_getRequestReadCount,
|
|
390
|
+
_hasPrivateFarmRequestHeaders,
|
|
391
|
+
resolveRouteSharedCacheControl,
|
|
392
|
+
} from '@farm.js/core/internal/production-runtime';
|
|
393
|
+
${i18n ? "import { getLocaleSource } from '@farm.js/core/i18n/server';\n" : ""}`
|
|
394
|
+
: ""}
|
|
125
395
|
import {
|
|
126
396
|
FARM_MARKDOWN_CONTENT_TYPE,
|
|
127
397
|
applyMarkdownNegotiationHeaders,
|
|
@@ -129,8 +399,28 @@ import {
|
|
|
129
399
|
createMarkdownMirrorResponse,
|
|
130
400
|
farmRequestWantsMarkdown,
|
|
131
401
|
} from '@farm.js/core/markdown';
|
|
132
|
-
|
|
402
|
+
${ctx.markdown?.enabled
|
|
403
|
+
? `import { getFarmMarkdownAlternatePath } from '@farm.js/core/markdown';
|
|
404
|
+
import { addMetadataMarkdownAlternate } from '@farm.js/core/internal/production-runtime';
|
|
405
|
+
`
|
|
406
|
+
: ""}import { stripFarmBasePath, stripFarmLocaleFromPathname } from '@farm.js/core/internal/production-runtime';
|
|
407
|
+
import { resolveFarmTrailingSlashRedirect } from '@farm.js/core/internal/production-runtime';
|
|
408
|
+
${ctx.trailingSlash
|
|
409
|
+
? `import { normalizeFarmTrailingSlashPathname, setFarmTrailingSlashPreference } from '@farm.js/core/internal/production-runtime';
|
|
410
|
+
|
|
411
|
+
// trailingSlash: <Link href="/about"> renders /about/, as in core's renderers. Client components
|
|
412
|
+
// render in the SSR environment, which shares this process; the browser entry sets it too.
|
|
413
|
+
setFarmTrailingSlashPreference(true);
|
|
414
|
+
`
|
|
415
|
+
: ""}
|
|
416
|
+
${hasBasePath
|
|
417
|
+
? `import { applyFarmBasePath, setFarmBasePath } from '@farm.js/core/internal/production-runtime';
|
|
133
418
|
|
|
419
|
+
// <Link href="/about"> renders /console/about, as in core's renderers. Client components render in
|
|
420
|
+
// the SSR environment, which shares this process; the browser entry sets it for hydration.
|
|
421
|
+
setFarmBasePath(${JSON.stringify(ctx.basePath)});
|
|
422
|
+
`
|
|
423
|
+
: ""}
|
|
134
424
|
${ctx.images && ctx.images.runtime !== "none"
|
|
135
425
|
? `import { createCloudflareImageTransformer, createFarmImageHandler } from '@farm.js/core/image/server';
|
|
136
426
|
${ctx.images.runtime === "node"
|
|
@@ -162,29 +452,76 @@ const farmRouteI18n = ${JSON.stringify(ctx.i18n ?? { enabled: false, basePath: c
|
|
|
162
452
|
|
|
163
453
|
/**
|
|
164
454
|
* A request path without the app's basePath and locale prefix, as core's servers and the
|
|
165
|
-
* middleware runner read it: '/console/fr/about' is '/about'.
|
|
166
|
-
* '<prefix>/index.md' and matches md.expose on it.
|
|
455
|
+
* middleware runner read it: '/console/fr/about' is '/about'. Pages match it (matchRoute), and
|
|
456
|
+
* Markdown names a home page '<prefix>/index.md' and matches md.expose on it.
|
|
167
457
|
*/
|
|
168
458
|
function getFarmRoutePathname(pathname) {
|
|
169
459
|
return farmRouteI18n.enabled
|
|
170
460
|
? stripFarmLocaleFromPathname(pathname, farmRouteI18n)
|
|
171
461
|
: stripFarmBasePath(pathname, farmRouteI18n.basePath);
|
|
172
462
|
}
|
|
463
|
+
${i18n ? generateI18nRuntime(ctx, i18n) : ""}`;
|
|
464
|
+
// sitemap.ts, robots.ts, llms.ts and llms-full.ts route files, served as core serves them. An
|
|
465
|
+
// llms.ts receives the pages and defaults the generated llms.txt would list.
|
|
466
|
+
const servesAppMetadataRoutes = ctx.appMetadataRoutes === true;
|
|
467
|
+
const buildsLlmsTxt = ctx.llmsTxt?.enabled === true || servesAppMetadataRoutes;
|
|
468
|
+
// The generated agent files list the app's static pages.
|
|
469
|
+
const listsAgentPages = ctx.llmsTxt?.enabled === true || ctx.sitemap?.enabled === true || servesAppMetadataRoutes;
|
|
470
|
+
// agent.crawlers: a generated robots.txt, as core serves it.
|
|
471
|
+
const servesAgentRobots = ctx.crawlers?.enabled === true;
|
|
472
|
+
// opengraph-image and twitter-image files: static images and generated modules, served and
|
|
473
|
+
// added to the page head as core does.
|
|
474
|
+
const staticMetadataImages = ctx.metadataImages?.static === true;
|
|
475
|
+
const generatedMetadataImages = ctx.metadataImages?.generated === true;
|
|
476
|
+
const servesMetadataImages = staticMetadataImages || generatedMetadataImages;
|
|
477
|
+
if (servesMetadataImages) {
|
|
478
|
+
code += `import { addMetadataImageReference, matchesFarmIfNoneMatch } from '@farm.js/core/internal/production-runtime';
|
|
479
|
+
`;
|
|
480
|
+
}
|
|
481
|
+
if (generatedMetadataImages) {
|
|
482
|
+
// Loads @vercel/og only when a generated image renders, as in core's servers.
|
|
483
|
+
code += `import { createFarmSearchParams } from '@farm.js/core/internal/production-runtime';
|
|
484
|
+
import { createFarmMetadataImageResponse } from '@farm.js/core/internal/metadata-image-runtime';
|
|
485
|
+
`;
|
|
486
|
+
}
|
|
487
|
+
if (listsAgentPages || servesAgentRobots) {
|
|
488
|
+
code += `import { createFarmMetadataRouteResponse } from '@farm.js/core/internal/production-runtime';
|
|
489
|
+
`;
|
|
490
|
+
}
|
|
491
|
+
if (servesAgentRobots) {
|
|
492
|
+
code += `import { createFarmAgentRobots } from '@farm.js/core/internal/production-runtime';
|
|
493
|
+
|
|
494
|
+
const farmAgentCrawlers = ${JSON.stringify(ctx.crawlers)};
|
|
495
|
+
`;
|
|
496
|
+
}
|
|
497
|
+
if (listsAgentPages) {
|
|
498
|
+
code += `import {
|
|
499
|
+
farmPathGuardCoversPage,
|
|
500
|
+
isFarmPageNoIndex,
|
|
501
|
+
resolveFarmAgentOrigin,
|
|
502
|
+
} from '@farm.js/core/internal/production-runtime';
|
|
173
503
|
`;
|
|
174
|
-
|
|
504
|
+
}
|
|
505
|
+
if (buildsLlmsTxt) {
|
|
175
506
|
code += `import {
|
|
176
507
|
collectFarmLlmsTxtPages,
|
|
177
508
|
createFarmDefaultLlmsTxt,
|
|
178
509
|
createFarmLlmsFullRenderer,
|
|
179
510
|
createFarmLlmsMarkdownReader,
|
|
180
|
-
createFarmMetadataRouteResponse,
|
|
181
|
-
farmPathGuardCoversPage,
|
|
182
511
|
renderFarmLlmsFullTxt,
|
|
183
512
|
} from '@farm.js/core/internal/production-runtime';
|
|
184
513
|
import { FARM_MARKDOWN_ANONYMOUS_CLIENT_ADDRESS } from '@farm.js/core/internal/app-markdown-runtime';
|
|
185
514
|
|
|
186
|
-
const farmLlmsTxtConfig = ${JSON.stringify(ctx.llmsTxt)};
|
|
515
|
+
const farmLlmsTxtConfig = ${JSON.stringify(ctx.llmsTxt ?? { enabled: false, include: [], exclude: [], full: false })};
|
|
187
516
|
const farmLlmsFullRenderer = createFarmLlmsFullRenderer({ revalidate: farmLlmsTxtConfig.revalidate });
|
|
517
|
+
`;
|
|
518
|
+
}
|
|
519
|
+
if (ctx.sitemap?.enabled) {
|
|
520
|
+
code += `import { createFarmDefaultSitemap } from '@farm.js/core/internal/production-runtime';
|
|
521
|
+
|
|
522
|
+
const farmAgentSitemapConfig = ${JSON.stringify(ctx.sitemap)};
|
|
523
|
+
// Each page file's last change, read by the build (by farm dev when it starts).
|
|
524
|
+
const farmPageLastModified = ${JSON.stringify(ctx.pageLastModified ?? {})};
|
|
188
525
|
`;
|
|
189
526
|
}
|
|
190
527
|
if (ctx.actionsEnabled) {
|
|
@@ -257,19 +594,51 @@ function debug(...args) {
|
|
|
257
594
|
${debugLog}
|
|
258
595
|
}
|
|
259
596
|
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
597
|
+
// Directives a CDN reads in place of Cache-Control, as core's CDN_CACHE_CONTROL_HEADERS lists them.
|
|
598
|
+
const FARM_CDN_CACHE_CONTROL_HEADERS = [
|
|
599
|
+
'cdn-cache-control',
|
|
600
|
+
'vercel-cdn-cache-control',
|
|
601
|
+
'netlify-cdn-cache-control',
|
|
602
|
+
'cloudflare-cdn-cache-control',
|
|
603
|
+
];
|
|
604
|
+
const FARM_PRIVATE_CACHE_DIRECTIVE = /(?:^|,)\\s*(?:private|no-store)\\s*(?:[,=]|$)/i;
|
|
605
|
+
|
|
606
|
+
/**
|
|
607
|
+
* Store the deployment ID in the deployment cookie on a page document a browser loads, so a form
|
|
608
|
+
* posted from it before JavaScript runs names its deployment. Only a GET page document that names
|
|
609
|
+
* this deployment and stays out of shared caches carries it: a CDN does not cache a response that
|
|
610
|
+
* sets a cookie (and one that does would hand it to every visitor), so a publicly cached page is
|
|
611
|
+
* sent as it was. A request naming another deployment keeps its cookie, so its forms stay refused.
|
|
612
|
+
*
|
|
613
|
+
* These are the rules of core's _withFarmDeploymentCookie for its production server (deployment
|
|
614
|
+
* skew protection); reuse that helper here once core exports it. A Flight payload is fetched by
|
|
615
|
+
* the client router, which names its deployment in a header, so it never carries the cookie.
|
|
616
|
+
*/
|
|
617
|
+
function withFarmDeploymentCookie(request, response) {
|
|
618
|
+
if (request.method.toUpperCase() !== 'GET') return response;
|
|
619
|
+
if ((request.headers.get('accept') || '').includes('text/x-component')) return response;
|
|
620
|
+
if (response.headers.get('x-farm-deployment-id') !== farmDeploymentId) return response;
|
|
621
|
+
if (!FARM_PRIVATE_CACHE_DIRECTIVE.test(response.headers.get('cache-control') || '')) return response;
|
|
622
|
+
if (FARM_CDN_CACHE_CONTROL_HEADERS.some((name) => response.headers.has(name))) return response;
|
|
623
|
+
if (getFarmDeploymentMismatch(request, farmDeploymentId)) return response;
|
|
624
|
+
return _withFarmResponseHeaders(response, (headers) => {
|
|
267
625
|
headers.append('set-cookie', createFarmDeploymentCookie(
|
|
268
626
|
farmDeploymentId,
|
|
269
627
|
${JSON.stringify(ctx.basePath)},
|
|
270
628
|
new URL(request.url).protocol === 'https:',
|
|
271
629
|
));
|
|
272
|
-
}
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
function applyActionResponseHeaders(headers, request, pageCacheControl) {
|
|
634
|
+
// The same page URL serves HTML or Flight depending on Accept.
|
|
635
|
+
const vary = (headers.get('vary') || '').split(',').map(value => value.trim().toLowerCase());
|
|
636
|
+
if (!vary.includes('*') && !vary.includes('accept')) headers.append('vary', 'Accept');
|
|
637
|
+
// handler() sets the deployment cookie once the response's cache policy is final.
|
|
638
|
+
headers.set('x-farm-deployment-id', farmDeploymentId);
|
|
639
|
+
// A static or revalidating page's own policy (getFarmPageCacheControl) wins over a Cache-Control
|
|
640
|
+
// middleware set, as a page's own headers do in core's server.
|
|
641
|
+
if (pageCacheControl) headers.set('cache-control', pageCacheControl);
|
|
273
642
|
if (${ctx.actionsEnabled ? "true" : "false"} && request.method === 'POST') {
|
|
274
643
|
headers.set('cache-control', 'no-store');
|
|
275
644
|
headers.set('x-content-type-options', 'nosniff');
|
|
@@ -293,7 +662,15 @@ const routeDefinitionModules${index} = import.meta.glob(${JSON.stringify(root.so
|
|
|
293
662
|
: [
|
|
294
663
|
`${root.sourceGlob}/{farm.route,farm.routes,routes}.{tsx,jsx,ts,js}`,
|
|
295
664
|
`${root.glob}/{farm.route,farm.routes,routes}.{tsx,jsx,ts,js}`,
|
|
296
|
-
])}, { eager: true })
|
|
665
|
+
])}, { eager: true });${servesAppMetadataRoutes
|
|
666
|
+
? `\nconst appMetadataRoutes${index} = ${uiRouteGlob(`${root.glob}/**/{sitemap,robots,manifest,llms,llms-full}.{ts,js}`)};`
|
|
667
|
+
: ""}${generatedMetadataImages
|
|
668
|
+
? `\nconst metadataImageModules${index} = ${uiRouteGlob(`${root.glob}/**/{opengraph-image,twitter-image}.{tsx,jsx,ts,js}`)};`
|
|
669
|
+
: ""}${staticMetadataImages
|
|
670
|
+
? // Each file's dimensions, alt text, hash and bytes, read by the plugin's loader as core's
|
|
671
|
+
// router reads them (and inlined by a build, as core's build inlines them).
|
|
672
|
+
`\nconst metadataImageFiles${index} = import.meta.glob(${JSON.stringify(`${root.glob}/**/{opengraph-image,twitter-image}.{png,jpg,jpeg,gif,webp}`)}, { query: ${JSON.stringify(FARM_METADATA_IMAGE_QUERY)}, import: 'default', eager: true });`
|
|
673
|
+
: ""}`)
|
|
297
674
|
.join("\n")}
|
|
298
675
|
|
|
299
676
|
function mergeRouteModules(sources) {
|
|
@@ -532,7 +909,8 @@ const farmMiddlewareRunner = createProductionMiddlewareRunner({
|
|
|
532
909
|
i18n: ${JSON.stringify(ctx.i18n) ?? "undefined"},
|
|
533
910
|
server: ${JSON.stringify(ctx.server) ?? "undefined"},
|
|
534
911
|
apiBasePath: farmApiBasePath,
|
|
535
|
-
// matchRoute()
|
|
912
|
+
// matchRoute() can select a page by the path as received (a page under app/<basePath>/ or
|
|
913
|
+
// app/[lang]/) as well as by the route path, so middleware guards both.
|
|
536
914
|
rawPathRouting: true,
|
|
537
915
|
});
|
|
538
916
|
|
|
@@ -651,12 +1029,48 @@ const pageRoutes = Object.entries(pages)
|
|
|
651
1029
|
* Simple file-based router
|
|
652
1030
|
* Converts URL pathname to matching page component
|
|
653
1031
|
*/
|
|
654
|
-
|
|
1032
|
+
${routesBelowPrefix
|
|
1033
|
+
? `function matchRoute(pathname) {
|
|
655
1034
|
const normalized = pathname.replace(/\\/$/, '') || '/';
|
|
656
|
-
|
|
1035
|
+
const routePathname = getFarmRoutePathname(normalized);
|
|
1036
|
+
if (routePathname === normalized) return matchFarmPagePath(normalized);
|
|
1037
|
+
// Pages answer at their route path, as in core's renderers: app/about/page.tsx at
|
|
1038
|
+
// '/console/about' under basePath "/console", and at '/console/fr/about' with an 'fr' locale.
|
|
1039
|
+
// A page whose folders spell out the prefix the request carries (app/console/about, or
|
|
1040
|
+
// app/[lang]/about for the locale) keeps the URL it had when RSC matched the path as received,
|
|
1041
|
+
// and any other page matching only that path still answers there. Middleware runs for both
|
|
1042
|
+
// paths (rawPathRouting), so the page that renders keeps its guards.
|
|
1043
|
+
const asReceived = matchFarmPagePath(normalized);
|
|
1044
|
+
if (asReceived && farmPageSpellsRoutePrefix(asReceived.segments, normalized, routePathname)) {
|
|
1045
|
+
return asReceived;
|
|
1046
|
+
}
|
|
1047
|
+
return matchFarmPagePath(routePathname) ?? asReceived;
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
/**
|
|
1051
|
+
* Whether a page matched on the path as received takes the prefix with its own folders: a static
|
|
1052
|
+
* folder for each basePath segment, then any folder but a catch-all for the locale. A catch-all
|
|
1053
|
+
* or dynamic folder that merely absorbs the basePath ('[...slug]' at the root) does not.
|
|
1054
|
+
*/
|
|
1055
|
+
function farmPageSpellsRoutePrefix(segments, pathname, routePathname) {
|
|
1056
|
+
const count = (path) => path.split('/').filter(Boolean).length;
|
|
1057
|
+
const prefixLength = count(pathname) - count(routePathname);
|
|
1058
|
+
const basePathLength = count(pathname) - count(stripFarmBasePath(pathname, farmRouteI18n.basePath));
|
|
1059
|
+
for (let index = 0; index < prefixLength; index++) {
|
|
1060
|
+
const segment = segments[index];
|
|
1061
|
+
if (!segment || segment.isCatchAll || (index < basePathLength && segment.isDynamic)) return false;
|
|
1062
|
+
}
|
|
1063
|
+
return true;
|
|
1064
|
+
}
|
|
1065
|
+
`
|
|
1066
|
+
: `function matchRoute(pathname) {
|
|
1067
|
+
return matchFarmPagePath(pathname.replace(/\\/$/, '') || '/');
|
|
1068
|
+
}
|
|
1069
|
+
`}
|
|
1070
|
+
function matchFarmPagePath(normalized) {
|
|
657
1071
|
for (const { filePath, module, segments } of pageRoutes) {
|
|
658
1072
|
const match = matchFarmPageRoute(normalized, segments);
|
|
659
|
-
|
|
1073
|
+
|
|
660
1074
|
if (match.matches) {
|
|
661
1075
|
debug('Matched route:', filePath, 'for path:', normalized);
|
|
662
1076
|
return {
|
|
@@ -664,10 +1078,11 @@ function matchRoute(pathname) {
|
|
|
664
1078
|
pattern: filePath,
|
|
665
1079
|
params: match.params,
|
|
666
1080
|
module,
|
|
1081
|
+
segments,
|
|
667
1082
|
};
|
|
668
1083
|
}
|
|
669
1084
|
}
|
|
670
|
-
|
|
1085
|
+
|
|
671
1086
|
debug('No route matched for:', normalized);
|
|
672
1087
|
return null;
|
|
673
1088
|
}
|
|
@@ -675,7 +1090,37 @@ function matchRoute(pathname) {
|
|
|
675
1090
|
// Each page's parsed rendering directive and whether its source reads request state, baked by
|
|
676
1091
|
// the build because module exports cannot tell.
|
|
677
1092
|
const farmPageRenderingDirectives = ${JSON.stringify(ctx.pageRenderingDirectives ?? {})};
|
|
678
|
-
|
|
1093
|
+
${sharedPageCache
|
|
1094
|
+
? `
|
|
1095
|
+
/**
|
|
1096
|
+
* The Cache-Control of a page a shared cache may store (\`revalidate\`, or a static page this server
|
|
1097
|
+
* renders), as core's production server decides it: core's policy for the route, or
|
|
1098
|
+
* \`private, no-store\` when this render is one visitor's (a cookie other than the deployment
|
|
1099
|
+
* cookie, \`Authorization\`, middleware request data, or a request read since \`readsBefore\`).
|
|
1100
|
+
* Null for any other page, which keeps the default. Decided before the page streams, so its HTML
|
|
1101
|
+
* and its Flight payload get the same policy; middleware that let the request through makes it
|
|
1102
|
+
* private afterwards, as in core.
|
|
1103
|
+
*/
|
|
1104
|
+
function getFarmPageCacheControl(request, matched, readsBefore, middlewareData, middlewareContext) {
|
|
1105
|
+
const shared = resolveRouteSharedCacheControl(
|
|
1106
|
+
mergeRouteRenderingDirectiveConfig(farmPageRenderingDirectives[matched.pattern], matched.module),
|
|
1107
|
+
);
|
|
1108
|
+
if (!shared) return null;
|
|
1109
|
+
const method = request.method.toUpperCase();
|
|
1110
|
+
const perRequest =
|
|
1111
|
+
(method !== 'GET' && method !== 'HEAD') ||
|
|
1112
|
+
_hasPrivateFarmRequestHeaders(request${i18n
|
|
1113
|
+
? `, getLocaleSource() === 'url'
|
|
1114
|
+
? { name: farmRouteI18n.cookie.name, locales: farmRouteI18n.locales }
|
|
1115
|
+
: undefined`
|
|
1116
|
+
: ""}) ||
|
|
1117
|
+
middlewareData.size > 0 ||
|
|
1118
|
+
middlewareContext.size > 0 ||
|
|
1119
|
+
_getRequestReadCount(request) !== readsBefore;
|
|
1120
|
+
return perRequest ? 'private, no-store' : shared;
|
|
1121
|
+
}
|
|
1122
|
+
`
|
|
1123
|
+
: ""}
|
|
679
1124
|
/**
|
|
680
1125
|
* The URL paths the build prerenders, by core's SSG rules: a page asks to be static
|
|
681
1126
|
* (dynamic = "force-static", generateStaticParams, "use ssg"), does not read request
|
|
@@ -683,8 +1128,9 @@ const farmPageRenderingDirectives = ${JSON.stringify(ctx.pageRenderingDirectives
|
|
|
683
1128
|
* path any middleware may handle stays server-rendered.
|
|
684
1129
|
*/
|
|
685
1130
|
async function collectFarmStaticPages() {
|
|
686
|
-
${
|
|
687
|
-
?
|
|
1131
|
+
${i18n?.routing === "none"
|
|
1132
|
+
? `// As in core's SSG: one URL serves every locale, by the visitor's cookie or Accept-Language.
|
|
1133
|
+
console.info('[Farm.js] Prerendering is off: with i18n routing "none" one URL serves every locale.');
|
|
688
1134
|
return [];`
|
|
689
1135
|
: ""}
|
|
690
1136
|
const middlewareRoutes = Object.keys(middlewares)
|
|
@@ -721,12 +1167,69 @@ async function collectFarmStaticPages() {
|
|
|
721
1167
|
) {
|
|
722
1168
|
continue;
|
|
723
1169
|
}
|
|
724
|
-
|
|
1170
|
+
${i18n
|
|
1171
|
+
? `for (const publicPath of farmLocalizedStaticPaths(pagePath)) {
|
|
1172
|
+
// Only where the server would render this page, and no middleware may handle the URL.
|
|
1173
|
+
const routePath = getFarmRoutePathname(publicPath);
|
|
1174
|
+
if (
|
|
1175
|
+
matchRoute(publicPath)?.pattern !== filePath ||
|
|
1176
|
+
appMiddlewareMayHandlePath(middlewareRoutes, routePath) ||
|
|
1177
|
+
configMiddlewareMayHandlePath(farmConfigMiddleware, routePath) ||
|
|
1178
|
+
appMiddlewareMayHandlePath(middlewareRoutes, publicPath) ||
|
|
1179
|
+
configMiddlewareMayHandlePath(farmConfigMiddleware, publicPath)
|
|
1180
|
+
) {
|
|
1181
|
+
continue;
|
|
1182
|
+
}
|
|
1183
|
+
paths.add(publicPath);
|
|
1184
|
+
}`
|
|
1185
|
+
: hasBasePath
|
|
1186
|
+
? `// The platform serves a prerendered file only at the URL it was written for, below the
|
|
1187
|
+
// basePath, as core's build writes it. A page nested under app/<basePath>/ already is.
|
|
1188
|
+
const publicPath = applyFarmBasePath(pagePath, ${JSON.stringify(ctx.basePath)});
|
|
1189
|
+
paths.add(${ctx.trailingSlash
|
|
1190
|
+
? "normalizeFarmTrailingSlashPathname(publicPath, true)"
|
|
1191
|
+
: "publicPath.length > 1 ? publicPath.replace(/\\/$/, '') : publicPath"});`
|
|
1192
|
+
: ctx.trailingSlash
|
|
1193
|
+
? // With trailingSlash the page's URL is '/about/', which Nitro writes as about/index.html.
|
|
1194
|
+
"paths.add(normalizeFarmTrailingSlashPathname(pagePath, true));"
|
|
1195
|
+
: "paths.add(pagePath);"}
|
|
725
1196
|
}
|
|
726
1197
|
}
|
|
727
|
-
return [...paths];
|
|
1198
|
+
return [...paths]${configRoutes ? ".filter((path) => !farmConfigRouteMayHandlePath(path))" : ""};
|
|
1199
|
+
}
|
|
1200
|
+
${i18n
|
|
1201
|
+
? `/**
|
|
1202
|
+
* The URLs a static page prerenders at with i18n, as core's SSG lists them: the page at each
|
|
1203
|
+
* locale's URL below the basePath (localizeFarmPathname). A page whose folders name the locale
|
|
1204
|
+
* (app/[lang]/...) listed its URLs itself; one the server redirects to its canonical URL (the
|
|
1205
|
+
* default locale's prefix under "prefix-except-default") is left out. A URL without a locale (the
|
|
1206
|
+
* default locale's, under "prefix-except-default") answers by the visitor's cookie or
|
|
1207
|
+
* Accept-Language and redirects those that pick another locale, so it stays server-rendered while
|
|
1208
|
+
* the app detects either.
|
|
1209
|
+
*/
|
|
1210
|
+
function farmLocalizedStaticPaths(pagePath) {
|
|
1211
|
+
const namesLocale = (pathname) =>
|
|
1212
|
+
stripFarmLocaleFromPathname(pathname, farmRouteI18n) !==
|
|
1213
|
+
stripFarmBasePath(pathname, farmRouteI18n.basePath);
|
|
1214
|
+
const canonical = (pathname) =>
|
|
1215
|
+
farmRouteI18n.locales.some(
|
|
1216
|
+
(locale) => localizeFarmPathname(pathname, locale, farmRouteI18n) === pathname,
|
|
1217
|
+
);
|
|
1218
|
+
const detects = farmRouteI18n.detection.some((signal) => signal !== 'url');
|
|
1219
|
+
const urls = namesLocale(pagePath)
|
|
1220
|
+
? [${hasBasePath ? `applyFarmBasePath(pagePath, ${JSON.stringify(ctx.basePath)})` : "pagePath"}]
|
|
1221
|
+
: farmRouteI18n.locales.map((locale) => localizeFarmPathname(pagePath, locale, farmRouteI18n));
|
|
1222
|
+
return urls
|
|
1223
|
+
.map((url) => (url.length > 1 ? url.replace(/\\/$/, '') : url))
|
|
1224
|
+
.filter((url) => canonical(url) && (namesLocale(url) || !detects))${ctx.trailingSlash
|
|
1225
|
+
? `
|
|
1226
|
+
// With trailingSlash the page's URL is '/fr/about/', which Nitro writes as fr/about/index.html.
|
|
1227
|
+
.map((url) => normalizeFarmTrailingSlashPathname(url, true))`
|
|
1228
|
+
: ""};
|
|
728
1229
|
}
|
|
729
1230
|
|
|
1231
|
+
`
|
|
1232
|
+
: ""}
|
|
730
1233
|
// The route's metadata as core's server resolves it: layouts root to leaf, then the page, each
|
|
731
1234
|
// module's \`metadata\`, \`generateMetadata()\` and viewport exports merged in order.
|
|
732
1235
|
async function resolveFarmRouteMetadata(layoutModules, pageModule, pageProps) {
|
|
@@ -809,19 +1312,39 @@ function getMatchingBoundary(pageFilePath, modules, kind) {
|
|
|
809
1312
|
*/
|
|
810
1313
|
async function handleFarmRequest(request, context) {
|
|
811
1314
|
const farmCacheGuard = { guarded: false };
|
|
812
|
-
const response = await resolveFarmRequest(farmCacheGuard, request, context)
|
|
1315
|
+
const response = await resolveFarmRequest(farmCacheGuard, request, context);${configHeaders
|
|
1316
|
+
? `
|
|
1317
|
+
// Tells handler(), whose config headers() must not make this response shareable again.
|
|
1318
|
+
if (farmCacheGuard.guarded) context?.onGuardedResponse?.();`
|
|
1319
|
+
: ""}
|
|
813
1320
|
return farmCacheGuard.guarded ? _withFarmGuardedResponseCache(response) : response;
|
|
814
1321
|
}
|
|
815
1322
|
|
|
816
|
-
async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
1323
|
+
async function resolveFarmRequest(farmCacheGuard, request, context${configRoutes ? ", farmConfigRewritten = false" : ""}) {
|
|
817
1324
|
let url = new URL(request.url);
|
|
1325
|
+
const isFarmPayloadRequest = farmPayloadRequests.has(request);
|
|
818
1326
|
let matchedPage = null;
|
|
819
1327
|
let errorData = new Map();
|
|
820
1328
|
let errorContext = new Map();
|
|
821
1329
|
let errorHeaders = new Headers();
|
|
822
1330
|
try {
|
|
823
1331
|
debug('Handling request:', request.method, url.pathname);
|
|
824
|
-
|
|
1332
|
+
${configRoutes
|
|
1333
|
+
? `
|
|
1334
|
+
// Config redirects() answer before any route or middleware, and a config rewrite applies when
|
|
1335
|
+
// no route of this server answers the URL, once: its destination runs through middleware and
|
|
1336
|
+
// routing again, as in core's servers.
|
|
1337
|
+
if (!farmConfigRewritten) {
|
|
1338
|
+
const configRoute = await resolveFarmConfigRoute(request, isFarmPayloadRequest);
|
|
1339
|
+
if (configRoute instanceof Response) return configRoute;
|
|
1340
|
+
if (configRoute) {
|
|
1341
|
+
return await _runWithCurrentRequest(configRoute, () =>
|
|
1342
|
+
resolveFarmRequest(farmCacheGuard, configRoute, context, true)
|
|
1343
|
+
);
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
`
|
|
1347
|
+
: ""}
|
|
825
1348
|
const deploymentMismatch = getFarmDeploymentMismatch(request, farmDeploymentId);
|
|
826
1349
|
if (deploymentMismatch) {
|
|
827
1350
|
return createFarmDeploymentMismatchResponse(deploymentMismatch);
|
|
@@ -887,10 +1410,33 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
887
1410
|
if (apiResponse) {
|
|
888
1411
|
return applyProductionMiddlewareHeaders(apiResponse, middlewareHeaders);
|
|
889
1412
|
}
|
|
890
|
-
${
|
|
1413
|
+
${servesMetadataImages
|
|
1414
|
+
? `// opengraph-image and twitter-image: answered after middleware, as in core's servers.
|
|
1415
|
+
const metadataImageResponse = await handleFarmMetadataImageRequest(request);
|
|
1416
|
+
if (metadataImageResponse) return applyProductionMiddlewareHeaders(metadataImageResponse, middlewareHeaders);
|
|
1417
|
+
`
|
|
1418
|
+
: ""}${servesAppMetadataRoutes
|
|
1419
|
+
? `// sitemap.ts, robots.ts, manifest.ts, llms.ts and llms-full.ts: answered after middleware, as
|
|
1420
|
+
// in core's servers, and before the generated files they replace.
|
|
1421
|
+
const appMetadataResponse = await handleFarmAppMetadataRoute(request, context);
|
|
1422
|
+
if (appMetadataResponse) return applyProductionMiddlewareHeaders(appMetadataResponse, middlewareHeaders);
|
|
1423
|
+
`
|
|
1424
|
+
: ""}${ctx.llmsTxt?.enabled
|
|
891
1425
|
? `// agent.llmsTxt: answered after middleware, so its redirects and headers apply.
|
|
892
1426
|
const llmsResponse = await handleFarmLlmsTxtRequest(request, context);
|
|
893
1427
|
if (llmsResponse) return applyProductionMiddlewareHeaders(llmsResponse, middlewareHeaders);
|
|
1428
|
+
`
|
|
1429
|
+
: ""}${ctx.sitemap?.enabled
|
|
1430
|
+
? `// agent.sitemap: answered after middleware, as in core's servers.
|
|
1431
|
+
if (getFarmRoutePathname(url.pathname.replace(/\\/+$/, '') || '/') === '/sitemap.xml') {
|
|
1432
|
+
return applyProductionMiddlewareHeaders(createFarmAgentSitemapResponse(request), middlewareHeaders);
|
|
1433
|
+
}
|
|
1434
|
+
`
|
|
1435
|
+
: ""}${servesAgentRobots
|
|
1436
|
+
? `// agent.crawlers: answered after middleware, as in core's servers.
|
|
1437
|
+
if (getFarmRoutePathname(url.pathname.replace(/\\/+$/, '') || '/') === '/robots.txt') {
|
|
1438
|
+
return applyProductionMiddlewareHeaders(createFarmAgentRobotsResponse(request), middlewareHeaders);
|
|
1439
|
+
}
|
|
894
1440
|
`
|
|
895
1441
|
: ""}if (isFarmAPIPathname(url.pathname, farmApiBasePath) || isFarmAPIPathname(url.pathname)) {
|
|
896
1442
|
return applyProductionMiddlewareHeaders(new Response(
|
|
@@ -898,6 +1444,20 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
898
1444
|
{ status: 404, headers: { 'Content-Type': 'application/json' } },
|
|
899
1445
|
), middlewareHeaders);
|
|
900
1446
|
}
|
|
1447
|
+
|
|
1448
|
+
// A page answers at one spelling of its URL, as in core's servers: '/about/' with trailingSlash,
|
|
1449
|
+
// '/about' without. Any other spelling gets a 308 to it, before a server action runs, and a
|
|
1450
|
+
// '<page>.rsc' request is sent to the payload URL of that page.
|
|
1451
|
+
const trailingSlashLocation = resolveFarmTrailingSlashRedirect(url, ${JSON.stringify(ctx.trailingSlash === true)});
|
|
1452
|
+
if (trailingSlashLocation && matchRoute(url.pathname)) {
|
|
1453
|
+
const target = new URL(trailingSlashLocation, url);
|
|
1454
|
+
return applyProductionMiddlewareHeaders(new Response(null, {
|
|
1455
|
+
status: 308,
|
|
1456
|
+
headers: {
|
|
1457
|
+
location: isFarmPayloadRequest ? farmPayloadPath(target.pathname) + target.search : trailingSlashLocation,
|
|
1458
|
+
},
|
|
1459
|
+
}), middlewareHeaders);
|
|
1460
|
+
}
|
|
901
1461
|
`;
|
|
902
1462
|
// If actions enabled, add action handling before rendering
|
|
903
1463
|
if (ctx.actionsEnabled) {
|
|
@@ -972,7 +1532,7 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
972
1532
|
// sanitizeServerActionError untouched.
|
|
973
1533
|
const actionRedirect = getFarmRedirectError(e);
|
|
974
1534
|
if (actionRedirect) {
|
|
975
|
-
returnValue = { ok: false, redirect: { url: actionRedirect.url, status: actionRedirect.status } };
|
|
1535
|
+
returnValue = { ok: false, redirect: { url: ${i18n ? "localizeFarmRedirectUrl(actionRedirect.url)" : "actionRedirect.url"}, status: actionRedirect.status } };
|
|
976
1536
|
debug('Server action redirected:', actionId, actionRedirect.url);
|
|
977
1537
|
} else {
|
|
978
1538
|
const actionError = sanitizeServerActionError(e);
|
|
@@ -1019,7 +1579,7 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1019
1579
|
debug('Form action redirected:', formRedirect.url);
|
|
1020
1580
|
return new Response(null, {
|
|
1021
1581
|
status: 303,
|
|
1022
|
-
headers: { location: formRedirect.url, 'Cache-Control': 'no-store' },
|
|
1582
|
+
headers: { location: ${i18n ? "localizeFarmRedirectUrl(formRedirect.url)" : "formRedirect.url"}, 'Cache-Control': 'no-store' },
|
|
1023
1583
|
});
|
|
1024
1584
|
}
|
|
1025
1585
|
const actionError = sanitizeServerActionError(e);
|
|
@@ -1040,6 +1600,10 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1040
1600
|
}
|
|
1041
1601
|
`;
|
|
1042
1602
|
}
|
|
1603
|
+
// The nearest manifest.ts and metadata images join the route's metadata, as in core's servers.
|
|
1604
|
+
const routeMetadata = servesAppMetadataRoutes || servesMetadataImages
|
|
1605
|
+
? "addFarmMetadataFileReferences(await resolveFarmRouteMetadata(LayoutModules, pageModule, pageProps), url.pathname)"
|
|
1606
|
+
: "await resolveFarmRouteMetadata(LayoutModules, pageModule, pageProps)";
|
|
1043
1607
|
// Route matching and rendering
|
|
1044
1608
|
code += `
|
|
1045
1609
|
// Match the URL to a page component
|
|
@@ -1078,15 +1642,27 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1078
1642
|
// every non-RSC environment produces (see core's search-params.ts).
|
|
1079
1643
|
const searchParams = searchParamsToObject(url.searchParams);
|
|
1080
1644
|
|
|
1081
|
-
|
|
1645
|
+
${sharedPageCache
|
|
1646
|
+
? `// A request read from here on (metadata, the page, its layouts) makes the render one visitor's,
|
|
1647
|
+
// as in core's server; reads in middleware do not count.
|
|
1648
|
+
const farmReadsBeforeRender = _getRequestReadCount(request);
|
|
1649
|
+
`
|
|
1650
|
+
: ""}// Page props passed to components (includes middleware shared data)
|
|
1082
1651
|
const pageProps = { params, searchParams, middlewareData };
|
|
1083
|
-
|
|
1652
|
+
${ctx.markdown?.enabled
|
|
1653
|
+
? `// The head advertises the page's Markdown mirror as the Link header does, as in core's servers.
|
|
1654
|
+
const metadata = addMetadataMarkdownAlternate(
|
|
1655
|
+
${routeMetadata},
|
|
1656
|
+
getFarmMarkdownAlternatePath(farmMarkdownConfig, url.pathname, { routePathname: getFarmRoutePathname }),
|
|
1657
|
+
);`
|
|
1658
|
+
: `const metadata = ${routeMetadata};`}
|
|
1084
1659
|
const renderedHead = renderMetadataHead(metadata, { pathname: url.pathname });
|
|
1085
|
-
// Injected into <head> by the SSR entry
|
|
1660
|
+
// Injected into <head> by the SSR entry (React renders only the charset), and swapped in by the
|
|
1661
|
+
// browser entry on client navigation.
|
|
1086
1662
|
const metadataHead =
|
|
1087
1663
|
(renderedHead.hasExplicitTitle ? '<title>' + renderedHead.title + '</title>' : '') +
|
|
1088
1664
|
renderedHead.viewport +
|
|
1089
|
-
renderedHead.tags;
|
|
1665
|
+
renderedHead.tags${i18n ? " + renderFarmI18nAlternateLinks(request, url.pathname, metadata)" : ""};
|
|
1090
1666
|
const metadataTitle = resolveMetadataTitle(metadata.title);
|
|
1091
1667
|
|
|
1092
1668
|
debug('Rendering page:', pattern, 'with props:', pageProps);
|
|
@@ -1133,9 +1709,20 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1133
1709
|
const Layout = LayoutModules[index].default;
|
|
1134
1710
|
const layoutProps = { params: pageProps.params, children: layoutContent };
|
|
1135
1711
|
if (Layout.constructor.name === 'AsyncFunction') {
|
|
1136
|
-
layoutContent = await Layout(layoutProps)
|
|
1712
|
+
layoutContent = await Layout(layoutProps);${i18n
|
|
1713
|
+
? `
|
|
1714
|
+
if (index === 0 && farmDocumentLayoutModules.has(LayoutModules[0])) {
|
|
1715
|
+
layoutContent = withFarmDocumentLocale(layoutContent);
|
|
1716
|
+
}`
|
|
1717
|
+
: ""}
|
|
1137
1718
|
} else {
|
|
1138
|
-
layoutContent =
|
|
1719
|
+
layoutContent = ${i18n
|
|
1720
|
+
? `index === 0 &&
|
|
1721
|
+
farmDocumentLayoutModules.has(LayoutModules[0]) &&
|
|
1722
|
+
Layout.$$typeof !== Symbol.for('react.client.reference')
|
|
1723
|
+
? h(FarmLocaleDocument, { Layout, layoutProps })
|
|
1724
|
+
: `
|
|
1725
|
+
: ""}h(Layout, layoutProps);
|
|
1139
1726
|
}
|
|
1140
1727
|
}
|
|
1141
1728
|
|
|
@@ -1152,10 +1739,15 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1152
1739
|
layoutContent,
|
|
1153
1740
|
)
|
|
1154
1741
|
: h('div', { 'data-farm-root': 'true' }, layoutContent);
|
|
1155
|
-
|
|
1742
|
+
${i18n
|
|
1743
|
+
? `// The request's locale, as core's renderers serialize it for hydration: client components
|
|
1744
|
+
// (Link, useLocale(), useTranslations()) read it in the browser as they did during SSR.
|
|
1745
|
+
const farmI18nSnapshot = getFarmI18nClientSnapshot() ?? null;
|
|
1746
|
+
`
|
|
1747
|
+
: ""}// Build the full page. root = full document (for SSR). rootContent = what the browser hydrates.
|
|
1156
1748
|
const payload = {
|
|
1157
1749
|
ownsDocument,
|
|
1158
|
-
root: ownsDocument ? rootInner : h('html', null,
|
|
1750
|
+
root: ownsDocument ? rootInner : h('html', ${i18n ? "farmI18nSnapshot && { lang: farmI18nSnapshot.locale, dir: farmI18nSnapshot.direction }" : "null"},
|
|
1159
1751
|
h('head', null,
|
|
1160
1752
|
h('meta', { charSet: 'utf-8' }),
|
|
1161
1753
|
renderedHead.hasFavicon ? null : h('link', { rel: 'icon', href: 'data:,' }),
|
|
@@ -1166,11 +1758,8 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1166
1758
|
),
|
|
1167
1759
|
rootContent: rootInner,
|
|
1168
1760
|
metadataHead,
|
|
1169
|
-
metadata: {
|
|
1170
|
-
|
|
1171
|
-
description: typeof metadata.description === 'string' ? metadata.description : undefined,
|
|
1172
|
-
},
|
|
1173
|
-
`;
|
|
1761
|
+
metadata: { title: metadataTitle },
|
|
1762
|
+
${i18n ? " i18n: farmI18nSnapshot,\n" : ""}`;
|
|
1174
1763
|
// Include action results in payload if actions are enabled
|
|
1175
1764
|
if (ctx.actionsEnabled) {
|
|
1176
1765
|
code += ` returnValue,
|
|
@@ -1182,7 +1771,16 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1182
1771
|
// Check if this is a client-side navigation request
|
|
1183
1772
|
// Client sends Accept: text/x-component header for RSC requests
|
|
1184
1773
|
const acceptHeader = request.headers.get('accept') || '';
|
|
1185
|
-
|
|
1774
|
+
${sharedPageCache
|
|
1775
|
+
? `const farmPageCacheControl = getFarmPageCacheControl(
|
|
1776
|
+
request,
|
|
1777
|
+
matched,
|
|
1778
|
+
farmReadsBeforeRender,
|
|
1779
|
+
middlewareResult.data,
|
|
1780
|
+
middlewareContext,
|
|
1781
|
+
);
|
|
1782
|
+
`
|
|
1783
|
+
: ""}
|
|
1186
1784
|
if (renderToReadableStream) {
|
|
1187
1785
|
// Full RSC mode with streaming
|
|
1188
1786
|
debug('Using RSC streaming mode');
|
|
@@ -1194,7 +1792,7 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1194
1792
|
// Merge middleware headers with response headers
|
|
1195
1793
|
const responseHeaders = new Headers(middlewareHeaders);
|
|
1196
1794
|
responseHeaders.set('content-type', 'text/x-component');
|
|
1197
|
-
applyActionResponseHeaders(responseHeaders, request);
|
|
1795
|
+
applyActionResponseHeaders(responseHeaders, request${pageCacheArg});
|
|
1198
1796
|
return new Response(rscStream, { headers: responseHeaders });
|
|
1199
1797
|
}
|
|
1200
1798
|
|
|
@@ -1214,7 +1812,7 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1214
1812
|
// Merge middleware headers with response headers
|
|
1215
1813
|
const responseHeaders = new Headers(middlewareHeaders);
|
|
1216
1814
|
responseHeaders.set('content-type', 'text/html');
|
|
1217
|
-
applyActionResponseHeaders(responseHeaders, request);
|
|
1815
|
+
applyActionResponseHeaders(responseHeaders, request${pageCacheArg});
|
|
1218
1816
|
return new Response(html, { headers: responseHeaders });
|
|
1219
1817
|
}
|
|
1220
1818
|
}
|
|
@@ -1240,7 +1838,7 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1240
1838
|
// Merge middleware headers with response headers
|
|
1241
1839
|
const responseHeaders = new Headers(middlewareHeaders);
|
|
1242
1840
|
responseHeaders.set('content-type', 'text/html');
|
|
1243
|
-
applyActionResponseHeaders(responseHeaders, request);
|
|
1841
|
+
applyActionResponseHeaders(responseHeaders, request${pageCacheArg});
|
|
1244
1842
|
return new Response(html, { headers: responseHeaders });
|
|
1245
1843
|
})
|
|
1246
1844
|
)
|
|
@@ -1251,7 +1849,7 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1251
1849
|
if ([...farmRouteLoadErrors.values()].includes(err)) throw err;
|
|
1252
1850
|
`
|
|
1253
1851
|
: ""}const redirect = getFarmRedirectError(err);
|
|
1254
|
-
if (redirect) return new Response(null, { status: redirect.status, headers: { location: redirect.url, 'cache-control': 'no-store' } });
|
|
1852
|
+
if (redirect) return new Response(null, { status: redirect.status, headers: { location: ${i18n ? "localizeFarmRedirectUrl(redirect.url)" : "redirect.url"}, 'cache-control': 'no-store' } });
|
|
1255
1853
|
if (isFarmNotFoundError(err)) return new Response('Not Found', { status: 404, headers: { 'cache-control': 'no-store' } });
|
|
1256
1854
|
console.error('[RSC] Handler error:', err);
|
|
1257
1855
|
if (request.method === 'POST') {
|
|
@@ -1297,7 +1895,7 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1297
1895
|
h('head', null, h('meta', { charSet: 'utf-8' }), h('title', null, 'Error')),
|
|
1298
1896
|
h('body', null, h('div', { id: 'root' }, rootInner))),
|
|
1299
1897
|
rootContent: rootInner,
|
|
1300
|
-
metadata: { title: 'Error' },
|
|
1898
|
+
metadata: { title: 'Error' },${i18n ? "\n i18n: getFarmI18nClientSnapshot() ?? null," : ""}
|
|
1301
1899
|
};
|
|
1302
1900
|
const rscStream = renderToReadableStream(payload, { onError: farmRscOnError });
|
|
1303
1901
|
const headers = new Headers(errorHeaders);
|
|
@@ -1336,41 +1934,35 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1336
1934
|
}
|
|
1337
1935
|
}
|
|
1338
1936
|
|
|
1339
|
-
${
|
|
1937
|
+
${buildsLlmsTxt
|
|
1340
1938
|
? `/**
|
|
1341
1939
|
* agent.llmsTxt, built the same way as core's production server: /llms.txt
|
|
1342
1940
|
* lists the app's static pages and links to their Markdown mirrors, and
|
|
1343
1941
|
* /llms-full.txt inlines each mirror.
|
|
1344
1942
|
*/
|
|
1345
1943
|
function createFarmLlmsTxtContext(request, context, full) {
|
|
1346
|
-
const origin =
|
|
1347
|
-
//
|
|
1348
|
-
//
|
|
1349
|
-
const guard = {
|
|
1350
|
-
config: { middleware: farmConfigMiddleware },
|
|
1351
|
-
middlewareRoutes: Object.keys(middlewares)
|
|
1352
|
-
.map((filePath) => ({ path: middlewarePathToRoute(filePath) }))
|
|
1353
|
-
.filter((route) => route.path !== null),
|
|
1354
|
-
};
|
|
1944
|
+
const origin = getFarmAgentOrigin(request);
|
|
1945
|
+
// Each page links to its public URL below the basePath ('/console/index.md' for the home page),
|
|
1946
|
+
// and include and exclude match its route path, as in core's servers.
|
|
1355
1947
|
const pages = collectFarmLlmsTxtPages(
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
.map((part) => (part.isDynamic ? '[' + part.segment + ']' : part.segment))
|
|
1361
|
-
.join('/'),
|
|
1362
|
-
metadata: module && module.metadata,
|
|
1363
|
-
}))
|
|
1364
|
-
.filter((page) => page.pattern.includes('[') || !farmPathGuardCoversPage(guard, page.pattern)),
|
|
1948
|
+
getFarmAgentListedPages().map(({ pattern, module }) => ({
|
|
1949
|
+
pattern,
|
|
1950
|
+
metadata: module && module.metadata,
|
|
1951
|
+
})),
|
|
1365
1952
|
{
|
|
1366
1953
|
origin,
|
|
1954
|
+
basePath: ${JSON.stringify(ctx.basePath)},
|
|
1367
1955
|
markdown: farmMarkdownConfig,
|
|
1368
1956
|
include: farmLlmsTxtConfig.include,
|
|
1369
|
-
exclude: farmLlmsTxtConfig.exclude,
|
|
1957
|
+
exclude: farmLlmsTxtConfig.exclude,${ctx.trailingSlash ? "\n // A page without a mirror is linked at the URL it answers at ('/console/about/').\n trailingSlash: true," : ""}
|
|
1958
|
+
// With i18n, in the default locale's URL ('/en/about.md' under routing "prefix-always").
|
|
1959
|
+
i18n: farmRouteI18n,
|
|
1370
1960
|
},
|
|
1371
1961
|
);
|
|
1372
1962
|
const rootLayout = getRouteModules('/page.tsx', layouts, 'layout')[0];
|
|
1373
1963
|
return {
|
|
1964
|
+
origin,
|
|
1965
|
+
pages,
|
|
1374
1966
|
defaults: createFarmDefaultLlmsTxt({
|
|
1375
1967
|
origin,
|
|
1376
1968
|
pages,
|
|
@@ -1394,9 +1986,11 @@ function createFarmLlmsTxtContext(request, context, full) {
|
|
|
1394
1986
|
|
|
1395
1987
|
async function handleFarmLlmsTxtRequest(request, context) {
|
|
1396
1988
|
const { origin, pathname } = new URL(request.url);
|
|
1397
|
-
|
|
1989
|
+
// Served at the path routes see, as core serves it: /console/llms.txt under basePath "/console".
|
|
1990
|
+
const routePathname = getFarmRoutePathname(pathname.replace(/\\/+$/, '') || '/');
|
|
1991
|
+
const kind = routePathname === '/llms.txt'
|
|
1398
1992
|
? 'llms'
|
|
1399
|
-
: farmLlmsTxtConfig.full &&
|
|
1993
|
+
: farmLlmsTxtConfig.full && routePathname === '/llms-full.txt' ? 'llms-full' : null;
|
|
1400
1994
|
if (!kind) return null;
|
|
1401
1995
|
const method = request.method.toUpperCase();
|
|
1402
1996
|
if (method !== 'GET' && method !== 'HEAD') {
|
|
@@ -1407,7 +2001,7 @@ async function handleFarmLlmsTxtRequest(request, context) {
|
|
|
1407
2001
|
let complete = true;
|
|
1408
2002
|
const renderFull = (shared) =>
|
|
1409
2003
|
renderFarmLlmsFullTxt(llmsContext.defaults, {
|
|
1410
|
-
origin,
|
|
2004
|
+
origin: llmsContext.origin,
|
|
1411
2005
|
readMarkdown: llmsContext.markdown,
|
|
1412
2006
|
onIncomplete: () => {
|
|
1413
2007
|
complete = false;
|
|
@@ -1432,8 +2026,421 @@ async function handleFarmLlmsTxtRequest(request, context) {
|
|
|
1432
2026
|
return response;
|
|
1433
2027
|
}
|
|
1434
2028
|
|
|
2029
|
+
`
|
|
2030
|
+
: ""}${listsAgentPages
|
|
2031
|
+
? `/**
|
|
2032
|
+
* The static pages the generated agent files list, as core's servers pick them: each at its route
|
|
2033
|
+
* path, below the basePath and locale, leaving out a page a path-specific guard (a non-root
|
|
2034
|
+
* middleware.ts, a config middleware matcher naming the path) or a route guard covers, and one
|
|
2035
|
+
* that renders noindex through its own robots or, without one, its nearest layout's.
|
|
2036
|
+
*/
|
|
2037
|
+
function getFarmAgentListedPages() {
|
|
2038
|
+
const guard = {
|
|
2039
|
+
config: { middleware: farmConfigMiddleware },
|
|
2040
|
+
middlewareRoutes: Object.keys(middlewares)
|
|
2041
|
+
.map((filePath) => ({ path: middlewarePathToRoute(filePath) }))
|
|
2042
|
+
.filter((route) => route.path !== null),
|
|
2043
|
+
};
|
|
2044
|
+
const listed = new Map();
|
|
2045
|
+
for (const { filePath, module, segments } of pageRoutes) {
|
|
2046
|
+
// Dynamic routes have no single URL.
|
|
2047
|
+
if (segments.some((part) => part.isDynamic)) continue;
|
|
2048
|
+
const filePattern = '/' + segments.map((part) => part.segment).join('/');
|
|
2049
|
+
${routesBelowPrefix
|
|
2050
|
+
? `// A page nested under app/<basePath>/ answers at the path without it, and wins there, as
|
|
2051
|
+
// matchRoute() selects it.
|
|
2052
|
+
const routePathname = getFarmRoutePathname(filePattern);
|
|
2053
|
+
const nested = routePathname !== filePattern &&
|
|
2054
|
+
farmPageSpellsRoutePrefix(segments, filePattern, routePathname);
|
|
2055
|
+
const pattern = nested ? routePathname : filePattern;
|
|
2056
|
+
const current = listed.get(pattern);
|
|
2057
|
+
if (current && (current.nested || !nested)) continue;`
|
|
2058
|
+
: `const pattern = filePattern;
|
|
2059
|
+
const nested = false;
|
|
2060
|
+
if (listed.has(pattern)) continue;`}
|
|
2061
|
+
listed.set(pattern, { filePath, filePattern, pattern, module, nested });
|
|
2062
|
+
}
|
|
2063
|
+
// Middleware runs for both the path as received and the route path, so either may guard it.
|
|
2064
|
+
return [...listed.values()].filter(({ filePath, filePattern, pattern, module }) =>
|
|
2065
|
+
!farmPathGuardCoversPage(guard, filePattern) &&
|
|
2066
|
+
!farmPathGuardCoversPage(guard, pattern) &&
|
|
2067
|
+
!(module && module.__farmRouteGuard) &&
|
|
2068
|
+
!isFarmPageNoIndex(
|
|
2069
|
+
module && module.metadata,
|
|
2070
|
+
getRouteModules(filePath, layouts, 'layout').map((layout) => layout.metadata),
|
|
2071
|
+
),
|
|
2072
|
+
);
|
|
2073
|
+
}
|
|
2074
|
+
|
|
2075
|
+
${ctx.sitemap?.enabled
|
|
2076
|
+
? `/**
|
|
2077
|
+
* agent.sitemap, built the same way as core's servers build it: the pages llms.txt lists, each at
|
|
2078
|
+
* its URL below the basePath, on the root layout's metadataBase or the request's origin.
|
|
2079
|
+
*/
|
|
2080
|
+
function createFarmAgentSitemapResponse(request) {
|
|
2081
|
+
const rootLayout = getRouteModules('/page.tsx', layouts, 'layout')[0];
|
|
2082
|
+
return createFarmMetadataRouteResponse(
|
|
2083
|
+
'sitemap',
|
|
2084
|
+
createFarmDefaultSitemap(
|
|
2085
|
+
getFarmAgentListedPages().map(({ filePath, pattern, module }) => ({
|
|
2086
|
+
pattern,
|
|
2087
|
+
module,
|
|
2088
|
+
lastModified: farmPageLastModified[filePath],
|
|
2089
|
+
})),
|
|
2090
|
+
{
|
|
2091
|
+
origin: new URL(request.url).origin,
|
|
2092
|
+
config: farmAgentSitemapConfig,
|
|
2093
|
+
metadataBase: rootLayout && rootLayout.metadata ? rootLayout.metadata.metadataBase : undefined,
|
|
2094
|
+
basePath: ${JSON.stringify(ctx.basePath)},${ctx.trailingSlash ? "\n // Each page at the URL it answers at: '/console/about/'.\n trailingSlash: true," : ""}
|
|
2095
|
+
i18n: farmRouteI18n,
|
|
2096
|
+
},
|
|
2097
|
+
),
|
|
2098
|
+
{},
|
|
2099
|
+
{ method: request.method },
|
|
2100
|
+
);
|
|
2101
|
+
}
|
|
2102
|
+
|
|
2103
|
+
`
|
|
2104
|
+
: ""}// Agent files link to the root layout's metadataBase when it is an absolute URL, else to the
|
|
2105
|
+
// request's origin, as in core's servers.
|
|
2106
|
+
function getFarmAgentOrigin(request) {
|
|
2107
|
+
const rootLayout = getRouteModules('/page.tsx', layouts, 'layout')[0];
|
|
2108
|
+
return resolveFarmAgentOrigin(
|
|
2109
|
+
rootLayout && rootLayout.metadata ? rootLayout.metadata.metadataBase : undefined,
|
|
2110
|
+
new URL(request.url).origin,
|
|
2111
|
+
);
|
|
2112
|
+
}
|
|
2113
|
+
|
|
2114
|
+
`
|
|
2115
|
+
: ""}${servesAgentRobots
|
|
2116
|
+
? `/**
|
|
2117
|
+
* agent.crawlers, built the same way as core's servers build it: rules for AI search and training
|
|
2118
|
+
* crawlers, and a Sitemap line for the app's sitemap.xml below the basePath when the root layout
|
|
2119
|
+
* has a metadataBase (the request's host is not trusted in a file crawlers and CDNs cache).
|
|
2120
|
+
*/
|
|
2121
|
+
function createFarmAgentRobotsResponse(request) {
|
|
2122
|
+
const rootLayout = getRouteModules('/page.tsx', layouts, 'layout')[0];
|
|
2123
|
+
return createFarmMetadataRouteResponse(
|
|
2124
|
+
'robots',
|
|
2125
|
+
createFarmAgentRobots({
|
|
2126
|
+
crawlers: farmAgentCrawlers,
|
|
2127
|
+
sitemapPath: ${ctx.sitemap?.enabled
|
|
2128
|
+
? "'/sitemap.xml'"
|
|
2129
|
+
: servesAppMetadataRoutes
|
|
2130
|
+
? "farmAppMetadataRoutes.some((route) => route.kind === 'sitemap' && route.segments.length === 0)\n ? '/sitemap.xml'\n : undefined"
|
|
2131
|
+
: "undefined"},
|
|
2132
|
+
metadataBase: rootLayout && rootLayout.metadata ? rootLayout.metadata.metadataBase : undefined,
|
|
2133
|
+
basePath: ${JSON.stringify(ctx.basePath)},
|
|
2134
|
+
}),
|
|
2135
|
+
{},
|
|
2136
|
+
{ method: request.method },
|
|
2137
|
+
);
|
|
2138
|
+
}
|
|
2139
|
+
|
|
2140
|
+
`
|
|
2141
|
+
: ""}${servesAppMetadataRoutes
|
|
2142
|
+
? `const FARM_APP_METADATA_OUTPUTS = {
|
|
2143
|
+
sitemap: 'sitemap.xml',
|
|
2144
|
+
robots: 'robots.txt',
|
|
2145
|
+
manifest: 'manifest.webmanifest',
|
|
2146
|
+
llms: 'llms.txt',
|
|
2147
|
+
'llms-full': 'llms-full.txt',
|
|
2148
|
+
};
|
|
2149
|
+
|
|
2150
|
+
// The app's metadata route files, most specific first, as core's router ranks them.
|
|
2151
|
+
const farmAppMetadataRoutes = Object.entries(
|
|
2152
|
+
mergeRouteModules([${routeRoots
|
|
2153
|
+
.map((root, index) => `{ base: ${JSON.stringify(root.base)}, modules: appMetadataRoutes${index} }`)
|
|
2154
|
+
.join(", ")}]),
|
|
2155
|
+
)
|
|
2156
|
+
.map(([filePath, module]) => {
|
|
2157
|
+
const fileName = filePath.slice(filePath.lastIndexOf('/') + 1);
|
|
2158
|
+
const kind = fileName.slice(0, fileName.lastIndexOf('.'));
|
|
2159
|
+
return {
|
|
2160
|
+
filePath,
|
|
2161
|
+
module,
|
|
2162
|
+
kind,
|
|
2163
|
+
outputName: FARM_APP_METADATA_OUTPUTS[kind],
|
|
2164
|
+
segments: parseRoutePath(filePath).segments,
|
|
2165
|
+
specificity: getRoutePatternSpecificity(filePath.slice(0, filePath.lastIndexOf('/')) || '/'),
|
|
2166
|
+
};
|
|
2167
|
+
})
|
|
2168
|
+
.sort((left, right) => compareRouteSpecificity(left.specificity, right.specificity));
|
|
2169
|
+
|
|
2170
|
+
/**
|
|
2171
|
+
* A sitemap.ts, robots.ts, manifest.ts, llms.ts or llms-full.ts route file, served as core
|
|
2172
|
+
* serves it: at '<segment>/<file>' on the route path (below the basePath and locale), from its
|
|
2173
|
+
* default export, a value or a function given the request, params, search params and the
|
|
2174
|
+
* segment's path. llms.ts and llms-full.ts also receive the pages and defaults the generated llms.txt would use, and
|
|
2175
|
+
* llms-full.ts the Markdown reader; an llms-full.ts object inlines each page's Markdown.
|
|
2176
|
+
*/
|
|
2177
|
+
async function handleFarmAppMetadataRoute(request, context) {
|
|
2178
|
+
const url = new URL(request.url);
|
|
2179
|
+
const matched = matchFarmAppMetadataRoute(
|
|
2180
|
+
getFarmRoutePathname(url.pathname.replace(/\\/+$/, '') || '/'),
|
|
2181
|
+
);
|
|
2182
|
+
if (matched) {
|
|
2183
|
+
const { route, routePath, match } = matched;
|
|
2184
|
+
const method = request.method.toUpperCase();
|
|
2185
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
2186
|
+
return new Response(null, { status: 405, headers: { Allow: 'GET, HEAD' } });
|
|
2187
|
+
}
|
|
2188
|
+
try {
|
|
2189
|
+
const routeModule = route.module;
|
|
2190
|
+
if (!routeModule || routeModule.default === undefined) {
|
|
2191
|
+
throw new Error('Metadata route module does not export a default value or handler');
|
|
2192
|
+
}
|
|
2193
|
+
const full = route.kind === 'llms-full';
|
|
2194
|
+
const llms = route.kind === 'llms' || full
|
|
2195
|
+
? createFarmLlmsTxtContext(request, context, full)
|
|
2196
|
+
: undefined;
|
|
2197
|
+
const value = typeof routeModule.default === 'function'
|
|
2198
|
+
? await routeModule.default({
|
|
2199
|
+
request,
|
|
2200
|
+
params: match.params,
|
|
2201
|
+
searchParams: url.searchParams,
|
|
2202
|
+
path: routePath,
|
|
2203
|
+
...(llms ? { pages: llms.pages, defaults: llms.defaults } : {}),
|
|
2204
|
+
...(full ? { markdown: llms.markdown } : {}),
|
|
2205
|
+
})
|
|
2206
|
+
: routeModule.default;
|
|
2207
|
+
const body = full && !(value instanceof Response)
|
|
2208
|
+
? await renderFarmLlmsFullTxt(value, { origin: llms.origin, readMarkdown: llms.markdown })
|
|
2209
|
+
: value;
|
|
2210
|
+
return createFarmMetadataRouteResponse(route.kind, body, routeModule, { method, request });
|
|
2211
|
+
} catch (error) {
|
|
2212
|
+
console.error('[Farm.js] Metadata route ' + route.filePath + ' failed:', error);
|
|
2213
|
+
return new Response('Internal Server Error', {
|
|
2214
|
+
status: 500,
|
|
2215
|
+
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
|
|
2216
|
+
});
|
|
2217
|
+
}
|
|
2218
|
+
}
|
|
2219
|
+
return null;
|
|
2220
|
+
}
|
|
2221
|
+
|
|
2222
|
+
/** The route file that answers a route path ('<segment>/<file>'), most specific first, or null. */
|
|
2223
|
+
function matchFarmAppMetadataRoute(pathname) {
|
|
2224
|
+
for (const route of farmAppMetadataRoutes) {
|
|
2225
|
+
const suffix = '/' + route.outputName;
|
|
2226
|
+
if (pathname !== suffix && !pathname.endsWith(suffix)) continue;
|
|
2227
|
+
const routePath = pathname.slice(0, -suffix.length) || '/';
|
|
2228
|
+
const match = matchFarmPageRoute(routePath, route.segments);
|
|
2229
|
+
if (match.matches) return { route, routePath, match };
|
|
2230
|
+
}
|
|
2231
|
+
return null;
|
|
2232
|
+
}
|
|
2233
|
+
|
|
2234
|
+
`
|
|
2235
|
+
: ""}${servesMetadataImages
|
|
2236
|
+
? `const FARM_METADATA_IMAGE_KINDS = { 'opengraph-image': 'opengraph', 'twitter-image': 'twitter' };
|
|
2237
|
+
|
|
2238
|
+
/** A metadata image route from its file path ('/products/[id]/opengraph-image.png'). */
|
|
2239
|
+
function createFarmMetadataImageRoute(filePath, image) {
|
|
2240
|
+
const directory = filePath.slice(0, filePath.lastIndexOf('/'));
|
|
2241
|
+
const baseName = filePath.slice(directory.length + 1);
|
|
2242
|
+
const fileName = baseName.slice(0, baseName.indexOf('.'));
|
|
2243
|
+
return {
|
|
2244
|
+
...image,
|
|
2245
|
+
filePath,
|
|
2246
|
+
kind: FARM_METADATA_IMAGE_KINDS[fileName],
|
|
2247
|
+
fileName,
|
|
2248
|
+
segments: parseRoutePath(filePath).segments,
|
|
2249
|
+
specificity: getRoutePatternSpecificity(directory || '/'),
|
|
2250
|
+
};
|
|
2251
|
+
}
|
|
2252
|
+
|
|
2253
|
+
// The app's opengraph-image and twitter-image files, most specific first: generated modules and
|
|
2254
|
+
// static images, whose dimensions, alt text and hash were read as core's router reads them.
|
|
2255
|
+
const farmMetadataImages = [${generatedMetadataImages
|
|
2256
|
+
? `
|
|
2257
|
+
...Object.entries(mergeRouteModules([${routeRoots
|
|
2258
|
+
.map((root, index) => `{ base: ${JSON.stringify(root.base)}, modules: metadataImageModules${index} }`)
|
|
2259
|
+
.join(", ")}])).map(([filePath, module]) => createFarmMetadataImageRoute(filePath, { sourceType: 'module', module })),`
|
|
2260
|
+
: ""}${staticMetadataImages
|
|
2261
|
+
? `
|
|
2262
|
+
...Object.entries(mergeRouteModules([${routeRoots
|
|
2263
|
+
.map((root, index) => `{ base: ${JSON.stringify(root.base)}, modules: metadataImageFiles${index} }`)
|
|
2264
|
+
.join(", ")}])).map(([filePath, file]) => createFarmMetadataImageRoute(filePath, { sourceType: 'static', staticInfo: file.info, data: file.data })),`
|
|
2265
|
+
: ""}
|
|
2266
|
+
].sort((left, right) => compareRouteSpecificity(left.specificity, right.specificity));
|
|
2267
|
+
|
|
2268
|
+
/**
|
|
2269
|
+
* An opengraph-image or twitter-image request, served as core serves it: at '<segment>/<file>' on
|
|
2270
|
+
* the route path (below the basePath and locale), GET and HEAD only. A static image answers with
|
|
2271
|
+
* its bytes, an ETag, and immutable caching when the URL names its hash (the head's
|
|
2272
|
+
* '?v=<hash>'); a generated module renders through core's metadata image response, given the
|
|
2273
|
+
* segment's params, search params and path.
|
|
2274
|
+
*/
|
|
2275
|
+
async function handleFarmMetadataImageRequest(request) {
|
|
2276
|
+
const url = new URL(request.url);
|
|
2277
|
+
const matched = matchFarmMetadataImageRequest(
|
|
2278
|
+
getFarmRoutePathname(url.pathname.replace(/\\/+$/, '') || '/'),
|
|
2279
|
+
);
|
|
2280
|
+
if (matched) {
|
|
2281
|
+
const { image, match, pagePath } = matched;
|
|
2282
|
+
const method = request.method.toUpperCase();
|
|
2283
|
+
if (method !== 'GET' && method !== 'HEAD') {
|
|
2284
|
+
return new Response(null, { status: 405, headers: { Allow: 'GET, HEAD' } });
|
|
2285
|
+
}
|
|
2286
|
+
if (image.sourceType === 'static') {
|
|
2287
|
+
const etag = '"' + image.staticInfo.hash + '"';
|
|
2288
|
+
const headers = new Headers({
|
|
2289
|
+
'Content-Type': image.staticInfo.contentType,
|
|
2290
|
+
'Content-Length': String(image.staticInfo.byteLength),
|
|
2291
|
+
'Cache-Control': url.searchParams.get('v') === image.staticInfo.hash
|
|
2292
|
+
? 'public, max-age=31536000, immutable'
|
|
2293
|
+
: 'public, max-age=0, must-revalidate',
|
|
2294
|
+
ETag: etag,
|
|
2295
|
+
'X-Content-Type-Options': 'nosniff',
|
|
2296
|
+
});
|
|
2297
|
+
if (matchesFarmIfNoneMatch(request.headers.get('if-none-match'), etag)) {
|
|
2298
|
+
return new Response(null, { status: 304, headers });
|
|
2299
|
+
}
|
|
2300
|
+
if (!image.bytes) image.bytes = Uint8Array.from(atob(image.data), (char) => char.charCodeAt(0));
|
|
2301
|
+
return new Response(method === 'HEAD' ? null : image.bytes, { status: 200, headers });
|
|
2302
|
+
}
|
|
2303
|
+
${generatedMetadataImages
|
|
2304
|
+
? `try {
|
|
2305
|
+
const imageModule = image.module;
|
|
2306
|
+
if (!imageModule || !imageModule.default) {
|
|
2307
|
+
throw new Error('Metadata image module does not export a default component or handler');
|
|
2308
|
+
}
|
|
2309
|
+
const value = typeof imageModule.default === 'function'
|
|
2310
|
+
? await imageModule.default({
|
|
2311
|
+
params: match.params,
|
|
2312
|
+
searchParams: createFarmSearchParams(searchParamsToObject(url.searchParams)),
|
|
2313
|
+
path: pagePath,
|
|
2314
|
+
})
|
|
2315
|
+
: imageModule.default;
|
|
2316
|
+
return await createFarmMetadataImageResponse(value, imageModule, {
|
|
2317
|
+
method,
|
|
2318
|
+
ifNoneMatch: request.headers.get('if-none-match'),
|
|
2319
|
+
});
|
|
2320
|
+
} catch (error) {
|
|
2321
|
+
console.error('[Farm.js] Metadata image ' + image.filePath + ' failed:', error);
|
|
2322
|
+
return new Response('Internal Server Error', {
|
|
2323
|
+
status: 500,
|
|
2324
|
+
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
|
|
2325
|
+
});
|
|
2326
|
+
}`
|
|
2327
|
+
: ""}
|
|
2328
|
+
}
|
|
2329
|
+
return null;
|
|
2330
|
+
}
|
|
2331
|
+
|
|
2332
|
+
/** The image that answers a route path ('<segment>/opengraph-image'), most specific first, or null. */
|
|
2333
|
+
function matchFarmMetadataImageRequest(pathname) {
|
|
2334
|
+
const fileName = ['opengraph-image', 'twitter-image'].find(
|
|
2335
|
+
(candidate) => pathname === '/' + candidate || pathname.endsWith('/' + candidate),
|
|
2336
|
+
);
|
|
2337
|
+
if (!fileName) return null;
|
|
2338
|
+
const pagePath = pathname.slice(0, -fileName.length - 1) || '/';
|
|
2339
|
+
for (const image of farmMetadataImages) {
|
|
2340
|
+
if (image.fileName !== fileName) continue;
|
|
2341
|
+
const match = matchFarmPageRoute(pagePath, image.segments);
|
|
2342
|
+
if (match.matches) return { image, match, pagePath };
|
|
2343
|
+
}
|
|
2344
|
+
return null;
|
|
2345
|
+
}
|
|
2346
|
+
|
|
2347
|
+
`
|
|
2348
|
+
: ""}${servesAppMetadataRoutes || servesMetadataImages
|
|
2349
|
+
? `/**
|
|
2350
|
+
* The nearest file of a kind for a route path, as core's servers pick it for the head: the deepest
|
|
2351
|
+
* segment whose path prefixes the route path, with that prefix's params.
|
|
2352
|
+
*/
|
|
2353
|
+
function findFarmNearestMetadataFile(files, routePathname) {
|
|
2354
|
+
const segments = routePathname.split('/').filter(Boolean);
|
|
2355
|
+
let nearest = null;
|
|
2356
|
+
for (const file of files) {
|
|
2357
|
+
const depth = file.segments.length;
|
|
2358
|
+
if (depth > segments.length) continue;
|
|
2359
|
+
const routePath = depth === 0 ? '/' : '/' + segments.slice(0, depth).join('/');
|
|
2360
|
+
if (!matchFarmPageRoute(routePath, file.segments).matches) continue;
|
|
2361
|
+
if (!nearest || depth > nearest.file.segments.length) nearest = { file, routePath };
|
|
2362
|
+
}
|
|
2363
|
+
return nearest;
|
|
2364
|
+
}
|
|
2365
|
+
|
|
2366
|
+
/** A metadata file's URL in the head: below its segment, in the request's locale and basePath. */
|
|
2367
|
+
function farmMetadataFileHref(routePath, file) {
|
|
2368
|
+
const href = (routePath === '/' ? '' : routePath) + '/' + file;${i18n
|
|
2369
|
+
? `
|
|
2370
|
+
const snapshot = getFarmI18nClientSnapshot();
|
|
2371
|
+
const localized = snapshot ? localizeFarmHref(href, snapshot.locale, snapshot) : href;`
|
|
2372
|
+
: `
|
|
2373
|
+
const localized = href;`}
|
|
2374
|
+
return ${hasBasePath ? `applyFarmBasePath(localized, ${JSON.stringify(ctx.basePath)})` : "localized"};
|
|
2375
|
+
}
|
|
2376
|
+
|
|
2377
|
+
/**
|
|
2378
|
+
* The route's metadata with the nearest manifest.ts as its manifest and the nearest
|
|
2379
|
+
* opengraph-image and twitter-image as Open Graph and Twitter images, unless the metadata sets
|
|
2380
|
+
* them, as core's servers add them.
|
|
2381
|
+
*/
|
|
2382
|
+
function addFarmMetadataFileReferences(metadata, pathname) {
|
|
2383
|
+
const routePathname = getFarmRoutePathname(pathname.replace(/\\/+$/, '') || '/');${servesAppMetadataRoutes
|
|
2384
|
+
? `
|
|
2385
|
+
if (!metadata.manifest) {
|
|
2386
|
+
const manifest = findFarmNearestMetadataFile(
|
|
2387
|
+
farmAppMetadataRoutes.filter((route) => route.kind === 'manifest'),
|
|
2388
|
+
routePathname,
|
|
2389
|
+
);
|
|
2390
|
+
if (manifest) {
|
|
2391
|
+
metadata = { ...metadata, manifest: farmMetadataFileHref(manifest.routePath, 'manifest.webmanifest') };
|
|
2392
|
+
}
|
|
2393
|
+
}`
|
|
2394
|
+
: ""}${servesMetadataImages
|
|
2395
|
+
? `
|
|
2396
|
+
for (const kind of ['opengraph', 'twitter']) {
|
|
2397
|
+
const nearest = findFarmNearestMetadataFile(
|
|
2398
|
+
farmMetadataImages.filter((image) => image.kind === kind),
|
|
2399
|
+
routePathname,
|
|
2400
|
+
);
|
|
2401
|
+
if (!nearest) continue;
|
|
2402
|
+
const image = nearest.file;
|
|
2403
|
+
const info = image.sourceType === 'static' ? image.staticInfo : image.module;
|
|
2404
|
+
const version = image.sourceType === 'static' ? '?v=' + image.staticInfo.hash : '';
|
|
2405
|
+
metadata = addMetadataImageReference(metadata, {
|
|
2406
|
+
kind,
|
|
2407
|
+
href: farmMetadataFileHref(nearest.routePath, image.fileName + version),
|
|
2408
|
+
width: info?.width ?? info?.size?.width,
|
|
2409
|
+
height: info?.height ?? info?.size?.height,
|
|
2410
|
+
alt: info?.alt,
|
|
2411
|
+
contentType: info?.contentType,
|
|
2412
|
+
});
|
|
2413
|
+
}`
|
|
2414
|
+
: ""}
|
|
2415
|
+
return metadata;
|
|
2416
|
+
}
|
|
2417
|
+
|
|
1435
2418
|
`
|
|
1436
2419
|
: ""}/**
|
|
2420
|
+
* A Markdown request whose only cookie is the deployment cookie, without it. That cookie names a
|
|
2421
|
+
* release, never a visitor, so a browser holding it may still read (and fill) a mirror md.cache
|
|
2422
|
+
* shares; any other cookie keeps the mirror private. Core's withoutFarmDeploymentCookie applies
|
|
2423
|
+
* the same rule inside createMarkdownMirrorResponse with deployment skew protection; drop this
|
|
2424
|
+
* once that ships. The mirror renders the page with a GET, where the cookie is never read.
|
|
2425
|
+
*/
|
|
2426
|
+
function withoutLoneFarmDeploymentCookie(request) {
|
|
2427
|
+
const cookie = request.headers.get('cookie');
|
|
2428
|
+
if (!cookie || !cookie.includes('__farm_deployment')) return request;
|
|
2429
|
+
if (!farmRequestWantsMarkdown(new URL(request.url).pathname, request.headers.get('accept'))) {
|
|
2430
|
+
return request;
|
|
2431
|
+
}
|
|
2432
|
+
const otherCookie = cookie.split(';').some((part) => {
|
|
2433
|
+
const separator = part.indexOf('=');
|
|
2434
|
+
const name = (separator === -1 ? part : part.slice(0, separator)).trim();
|
|
2435
|
+
return name !== '' && name !== '__farm_deployment';
|
|
2436
|
+
});
|
|
2437
|
+
if (otherCookie) return request;
|
|
2438
|
+
const headers = new Headers(request.headers);
|
|
2439
|
+
headers.delete('cookie');
|
|
2440
|
+
return new Request(request, { headers });
|
|
2441
|
+
}
|
|
2442
|
+
|
|
2443
|
+
/**
|
|
1437
2444
|
* Serves a page's Markdown mirror (\`/page.md\` or \`Accept: text/markdown\`) by
|
|
1438
2445
|
* rendering the page through the normal request path, so middleware and sign-in
|
|
1439
2446
|
* gates apply; every other request renders as usual, and HTML pages advertise
|
|
@@ -1442,12 +2449,12 @@ async function handleFarmLlmsTxtRequest(request, context) {
|
|
|
1442
2449
|
async function handleFarmPageOrMarkdown(request, context) {
|
|
1443
2450
|
if (!farmMarkdownConfig.enabled) return handleFarmRequest(request, context);
|
|
1444
2451
|
const markdown = await createMarkdownMirrorResponse({
|
|
1445
|
-
request,
|
|
2452
|
+
request: withoutLoneFarmDeploymentCookie(request),
|
|
1446
2453
|
config: farmMarkdownConfig,
|
|
1447
2454
|
routePathname: getFarmRoutePathname,
|
|
1448
|
-
//
|
|
2455
|
+
// The page the render below selects for the mirrored URL, below the basePath and locale.
|
|
1449
2456
|
routeExists: (pathname) => Boolean(matchRoute(pathname)),
|
|
1450
|
-
renderPage: (pageRequest) => handleFarmRequest(pageRequest, context),
|
|
2457
|
+
renderPage: (pageRequest) => handleFarmRequest(${ctx.trailingSlash ? "toFarmTrailingSlashPageRequest(pageRequest)" : "pageRequest"}, context),
|
|
1451
2458
|
apiServerBasePath: farmApiBasePath,
|
|
1452
2459
|
});
|
|
1453
2460
|
if (markdown) return markdown;
|
|
@@ -1458,7 +2465,19 @@ async function handleFarmPageOrMarkdown(request, context) {
|
|
|
1458
2465
|
routePathname: getFarmRoutePathname,
|
|
1459
2466
|
});
|
|
1460
2467
|
}
|
|
1461
|
-
|
|
2468
|
+
${ctx.trailingSlash
|
|
2469
|
+
? `
|
|
2470
|
+
// The mirror reads the page at its canonical URL ('/about/'), so the trailing-slash redirect never
|
|
2471
|
+
// answers in its place.
|
|
2472
|
+
function toFarmTrailingSlashPageRequest(request) {
|
|
2473
|
+
const url = new URL(request.url);
|
|
2474
|
+
const pathname = normalizeFarmTrailingSlashPathname(url.pathname, true);
|
|
2475
|
+
if (pathname === url.pathname) return request;
|
|
2476
|
+
url.pathname = pathname;
|
|
2477
|
+
return new Request(url, request);
|
|
2478
|
+
}
|
|
2479
|
+
`
|
|
2480
|
+
: ""}
|
|
1462
2481
|
// Client navigation addresses a page's RSC payload as '<page>.rsc' ('<dir>/index.rsc' for a
|
|
1463
2482
|
// trailing slash), so a prerendered page can be a static HTML file next to a static payload file.
|
|
1464
2483
|
// 'Accept: text/x-component' on the page URL keeps working.
|
|
@@ -1466,6 +2485,9 @@ function farmPayloadPath(pathname) {
|
|
|
1466
2485
|
return pathname.endsWith('/') ? pathname + 'index.rsc' : pathname + '.rsc';
|
|
1467
2486
|
}
|
|
1468
2487
|
|
|
2488
|
+
// The requests made from a '<page>.rsc' URL, whose redirects name a payload URL too.
|
|
2489
|
+
const farmPayloadRequests = new WeakSet();
|
|
2490
|
+
|
|
1469
2491
|
function toFarmPayloadRequest(request) {
|
|
1470
2492
|
if (request.method !== 'GET' && request.method !== 'HEAD') return request;
|
|
1471
2493
|
const url = new URL(request.url);
|
|
@@ -1475,9 +2497,11 @@ function toFarmPayloadRequest(request) {
|
|
|
1475
2497
|
url.pathname = page.endsWith('/index') ? page.slice(0, -'index'.length) : page;
|
|
1476
2498
|
const headers = new Headers(request.headers);
|
|
1477
2499
|
headers.set('accept', 'text/x-component');
|
|
1478
|
-
|
|
2500
|
+
const payloadRequest = new Request(url, { method: request.method, headers, signal: request.signal });
|
|
2501
|
+
farmPayloadRequests.add(payloadRequest);
|
|
2502
|
+
return payloadRequest;
|
|
1479
2503
|
}
|
|
1480
|
-
|
|
2504
|
+
${generateConfigRoutesRuntime(ctx, configRoutes, localRouteCheck)}
|
|
1481
2505
|
// The build's prerender pass (Nitro) runs this server with FARM_RSC_PRERENDER set. It seeds one
|
|
1482
2506
|
// route that lists the static pages, and each prerendered page queues its payload, both through
|
|
1483
2507
|
// Nitro's x-nitro-prerender response header. Production servers never answer either.
|
|
@@ -1541,8 +2565,30 @@ ${ctx.mobileClient
|
|
|
1541
2565
|
});
|
|
1542
2566
|
}
|
|
1543
2567
|
`
|
|
1544
|
-
: ""} const pageRequest = toFarmPayloadRequest(request)
|
|
1545
|
-
|
|
2568
|
+
: ""} const pageRequest = toFarmPayloadRequest(request);${configHeaders
|
|
2569
|
+
? `
|
|
2570
|
+
// Config headers() apply to whatever answers the URL as requested (a payload's page), redirects
|
|
2571
|
+
// included, after middleware let it through, so a guarded response stays private.
|
|
2572
|
+
const farmConfigHeaders = matchFarmConfigHeaders(new URL(pageRequest.url));
|
|
2573
|
+
let farmGuardedResponse = false;
|
|
2574
|
+
if (farmConfigHeaders.length > 0) {
|
|
2575
|
+
const adapterContext = context;
|
|
2576
|
+
context = {
|
|
2577
|
+
...adapterContext,
|
|
2578
|
+
onGuardedResponse() {
|
|
2579
|
+
farmGuardedResponse = true;
|
|
2580
|
+
adapterContext?.onGuardedResponse?.();
|
|
2581
|
+
},
|
|
2582
|
+
};
|
|
2583
|
+
}`
|
|
2584
|
+
: ""}
|
|
2585
|
+
${configHeaders ? "let" : "const"} response = await handleFarmRequestWithRuntime(pageRequest, context${i18n ? ", pageRequest !== request" : ""});${configHeaders
|
|
2586
|
+
? `
|
|
2587
|
+
if (farmConfigHeaders.length > 0) {
|
|
2588
|
+
response = applyConfigResponseHeaders(response, farmConfigHeaders);
|
|
2589
|
+
if (farmGuardedResponse) response = _withFarmGuardedResponseCache(response);
|
|
2590
|
+
}`
|
|
2591
|
+
: ""}
|
|
1546
2592
|
if (
|
|
1547
2593
|
prerendering &&
|
|
1548
2594
|
pageRequest === request &&
|
|
@@ -1553,7 +2599,9 @@ ${ctx.mobileClient
|
|
|
1553
2599
|
headers.set('x-nitro-prerender', encodeURIComponent(farmPayloadPath(new URL(request.url).pathname)));
|
|
1554
2600
|
return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
|
|
1555
2601
|
}
|
|
1556
|
-
|
|
2602
|
+
const finalResponse = ${ctx.mobileClient === "entry" ? "_applyFarmMobileShellClient(request, response, farmMobileShellClient)" : "response"};
|
|
2603
|
+
// A prerendered page is a file served to every visitor, so it never sets the cookie.
|
|
2604
|
+
return prerendering ? finalResponse : withFarmDeploymentCookie(pageRequest, finalResponse);
|
|
1557
2605
|
}
|
|
1558
2606
|
${ctx.mobileClient === "entry"
|
|
1559
2607
|
? `
|
|
@@ -1579,14 +2627,18 @@ const farmNativeStylesheets = (() => {
|
|
|
1579
2627
|
`
|
|
1580
2628
|
: ""}
|
|
1581
2629
|
|
|
1582
|
-
|
|
1583
|
-
|
|
2630
|
+
${i18n
|
|
2631
|
+
? `async function handleFarmRequestWithRuntime(request, context, payloadRequested) {
|
|
2632
|
+
// Outermost, so middleware, after() callbacks and local API calls read the locale too.
|
|
2633
|
+
return runFarmLocalizedRequest(request, payloadRequested, () => _runWithAPIRequestRuntime({`
|
|
2634
|
+
: `async function handleFarmRequestWithRuntime(request, context) {
|
|
2635
|
+
return _runWithAPIRequestRuntime({`}
|
|
1584
2636
|
basePath: farmApiBasePath,
|
|
1585
2637
|
dispatch: async (localRequest) =>
|
|
1586
2638
|
(await handleAPIRequest(localRequest)) ?? Response.json({ error: 'Not Found' }, { status: 404 }),
|
|
1587
2639
|
}, () => _runWithCurrentRequest(request, () =>
|
|
1588
2640
|
_runWithAfterRequest(request, () => handleFarmPageOrMarkdown(request, context), context)
|
|
1589
|
-
));
|
|
2641
|
+
))${i18n ? ")" : ""};
|
|
1590
2642
|
}
|
|
1591
2643
|
|
|
1592
2644
|
export default { fetch: handler };
|