@farm.js/plugin 0.1.69 → 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.
@@ -3,6 +3,11 @@ import { createRequire } from "node:module";
3
3
  import path from "node:path";
4
4
  import { FARM_RSC_MOBILE_SHELL_CLIENT_PLACEHOLDER, FARM_RSC_NATIVE_STYLESHEETS_PLACEHOLDER, } from "../mobile-client.js";
5
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";
6
11
  /** Core's production source for the \`mcp\` plugin, so both servers merge config the same way. */
7
12
  function generateMCPPluginSource() {
8
13
  const { generateNativeMCPPluginSource } = require_("@farm.js/core/internal/production-runtime");
@@ -43,6 +48,8 @@ import {
43
48
  getFarmLocaleVaryHeaders,
44
49
  localizeFarmHref,
45
50
  localizeFarmPathname,
51
+ renderFarmLocaleAlternateLinks,
52
+ resolveFarmWebRequestOrigin as resolveFarmI18nRequestOrigin,
46
53
  } from '@farm.js/core/internal/production-runtime';
47
54
  ${catalogs}
48
55
  // createTranslator(locale) and runWithLocale() outside a request.
@@ -53,8 +60,8 @@ _setDefaultFarmI18nRuntime(farmI18nRuntime);
53
60
  * visitor's cookie or Accept-Language picks is redirected to it (307), and a payload request to
54
61
  * that page's payload; a response that depends on those signals varies on them and stays out of
55
62
  * shared caches. API routes keep their URLs, as in core, and so does the image optimizer, which
56
- * this server answers only at its path. llms.txt and sitemap.xml answer at their localized URLs
57
- * too (they match the route path), so they redirect as in core.
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.
58
65
  */
59
66
  async function runFarmLocalizedRequest(request, payloadRequested, render) {
60
67
  const { pathname } = new URL(request.url);
@@ -95,6 +102,43 @@ function localizeFarmRedirectUrl(url) {
95
102
  : url;
96
103
  }
97
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
+
98
142
  function applyFarmI18nResponse(response, resolution) {
99
143
  const varyHeaders = getFarmLocaleVaryHeaders(farmRouteI18n, resolution);
100
144
  if (!resolution.persist && varyHeaders.length === 0) return response;
@@ -112,6 +156,106 @@ function applyFarmI18nResponse(response, resolution) {
112
156
  }
113
157
  `;
114
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
+ }
115
259
  /**
116
260
  * Generates the terminal middleware-result handling shared by the RSC entry
117
261
  * and its executable contract tests.
@@ -147,6 +291,15 @@ export function generateRscEntry(ctx) {
147
291
  const hasBasePath = !["", "/"].includes(ctx.basePath.trim());
148
292
  const i18n = ctx.i18n?.enabled === true ? ctx.i18n : undefined;
149
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;
150
303
  // Build the glob pattern for discovering routes (Farm convention: src/app when routesDir unset)
151
304
  const appSegment = ctx.routesDir === undefined ? "app" : ctx.routesDir.trim();
152
305
  const glob = appSegment ? `/${ctx.srcDir}/${appSegment}` : `/${ctx.srcDir}`;
@@ -205,7 +358,7 @@ import {
205
358
  applyProductionMiddlewareHeaders,
206
359
  createProductionMiddlewareRunner,
207
360
  } from '@farm.js/core/middleware';
208
- import { _withFarmGuardedResponseCache } from '@farm.js/core/internal/production-runtime';
361
+ import { _withFarmGuardedResponseCache, _withFarmResponseHeaders } from '@farm.js/core/internal/production-runtime';
209
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 {
210
363
  getAllowedAPIRouteMethods,
211
364
  invokeAPIRouteEndpoint,
@@ -231,7 +384,14 @@ import {
231
384
  renderMetadataHead,
232
385
  resolveMetadataTitle,
233
386
  } from '@farm.js/core/internal/production-runtime';
234
-
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
+ : ""}
235
395
  import {
236
396
  FARM_MARKDOWN_CONTENT_TYPE,
237
397
  applyMarkdownNegotiationHeaders,
@@ -301,18 +461,48 @@ function getFarmRoutePathname(pathname) {
301
461
  : stripFarmBasePath(pathname, farmRouteI18n.basePath);
302
462
  }
303
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;
304
468
  // The generated agent files list the app's static pages.
305
- const listsAgentPages = ctx.llmsTxt?.enabled === true || ctx.sitemap?.enabled === true;
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
+ }
306
497
  if (listsAgentPages) {
307
498
  code += `import {
308
- createFarmMetadataRouteResponse,
309
499
  farmPathGuardCoversPage,
310
500
  isFarmPageNoIndex,
311
501
  resolveFarmAgentOrigin,
312
502
  } from '@farm.js/core/internal/production-runtime';
313
503
  `;
314
504
  }
315
- if (ctx.llmsTxt?.enabled) {
505
+ if (buildsLlmsTxt) {
316
506
  code += `import {
317
507
  collectFarmLlmsTxtPages,
318
508
  createFarmDefaultLlmsTxt,
@@ -322,7 +512,7 @@ ${i18n ? generateI18nRuntime(ctx, i18n) : ""}`;
322
512
  } from '@farm.js/core/internal/production-runtime';
323
513
  import { FARM_MARKDOWN_ANONYMOUS_CLIENT_ADDRESS } from '@farm.js/core/internal/app-markdown-runtime';
324
514
 
325
- const farmLlmsTxtConfig = ${JSON.stringify(ctx.llmsTxt)};
515
+ const farmLlmsTxtConfig = ${JSON.stringify(ctx.llmsTxt ?? { enabled: false, include: [], exclude: [], full: false })};
326
516
  const farmLlmsFullRenderer = createFarmLlmsFullRenderer({ revalidate: farmLlmsTxtConfig.revalidate });
327
517
  `;
328
518
  }
@@ -404,19 +594,51 @@ function debug(...args) {
404
594
  ${debugLog}
405
595
  }
406
596
 
407
- function applyActionResponseHeaders(headers, request) {
408
- // The same page URL serves HTML or Flight depending on Accept.
409
- const vary = (headers.get('vary') || '').split(',').map(value => value.trim().toLowerCase());
410
- if (!vary.includes('*') && !vary.includes('accept')) headers.append('vary', 'Accept');
411
- headers.set('x-farm-deployment-id', farmDeploymentId);
412
- const accept = request.headers.get('accept') || '';
413
- if (request.method === 'GET' && !accept.includes('text/x-component')) {
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) => {
414
625
  headers.append('set-cookie', createFarmDeploymentCookie(
415
626
  farmDeploymentId,
416
627
  ${JSON.stringify(ctx.basePath)},
417
628
  new URL(request.url).protocol === 'https:',
418
629
  ));
419
- }
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);
420
642
  if (${ctx.actionsEnabled ? "true" : "false"} && request.method === 'POST') {
421
643
  headers.set('cache-control', 'no-store');
422
644
  headers.set('x-content-type-options', 'nosniff');
@@ -440,7 +662,15 @@ const routeDefinitionModules${index} = import.meta.glob(${JSON.stringify(root.so
440
662
  : [
441
663
  `${root.sourceGlob}/{farm.route,farm.routes,routes}.{tsx,jsx,ts,js}`,
442
664
  `${root.glob}/{farm.route,farm.routes,routes}.{tsx,jsx,ts,js}`,
443
- ])}, { 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
+ : ""}`)
444
674
  .join("\n")}
445
675
 
446
676
  function mergeRouteModules(sources) {
@@ -860,7 +1090,37 @@ function matchFarmPagePath(normalized) {
860
1090
  // Each page's parsed rendering directive and whether its source reads request state, baked by
861
1091
  // the build because module exports cannot tell.
862
1092
  const farmPageRenderingDirectives = ${JSON.stringify(ctx.pageRenderingDirectives ?? {})};
863
-
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
+ : ""}
864
1124
  /**
865
1125
  * The URL paths the build prerenders, by core's SSG rules: a page asks to be static
866
1126
  * (dynamic = "force-static", generateStaticParams, "use ssg"), does not read request
@@ -935,7 +1195,7 @@ async function collectFarmStaticPages() {
935
1195
  : "paths.add(pagePath);"}
936
1196
  }
937
1197
  }
938
- return [...paths];
1198
+ return [...paths]${configRoutes ? ".filter((path) => !farmConfigRouteMayHandlePath(path))" : ""};
939
1199
  }
940
1200
  ${i18n
941
1201
  ? `/**
@@ -1052,11 +1312,15 @@ function getMatchingBoundary(pageFilePath, modules, kind) {
1052
1312
  */
1053
1313
  async function handleFarmRequest(request, context) {
1054
1314
  const farmCacheGuard = { guarded: false };
1055
- 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
+ : ""}
1056
1320
  return farmCacheGuard.guarded ? _withFarmGuardedResponseCache(response) : response;
1057
1321
  }
1058
1322
 
1059
- async function resolveFarmRequest(farmCacheGuard, request, context) {
1323
+ async function resolveFarmRequest(farmCacheGuard, request, context${configRoutes ? ", farmConfigRewritten = false" : ""}) {
1060
1324
  let url = new URL(request.url);
1061
1325
  const isFarmPayloadRequest = farmPayloadRequests.has(request);
1062
1326
  let matchedPage = null;
@@ -1065,7 +1329,22 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
1065
1329
  let errorHeaders = new Headers();
1066
1330
  try {
1067
1331
  debug('Handling request:', request.method, url.pathname);
1068
-
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
+ : ""}
1069
1348
  const deploymentMismatch = getFarmDeploymentMismatch(request, farmDeploymentId);
1070
1349
  if (deploymentMismatch) {
1071
1350
  return createFarmDeploymentMismatchResponse(deploymentMismatch);
@@ -1131,7 +1410,18 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
1131
1410
  if (apiResponse) {
1132
1411
  return applyProductionMiddlewareHeaders(apiResponse, middlewareHeaders);
1133
1412
  }
1134
- ${ctx.llmsTxt?.enabled
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
1135
1425
  ? `// agent.llmsTxt: answered after middleware, so its redirects and headers apply.
1136
1426
  const llmsResponse = await handleFarmLlmsTxtRequest(request, context);
1137
1427
  if (llmsResponse) return applyProductionMiddlewareHeaders(llmsResponse, middlewareHeaders);
@@ -1141,6 +1431,12 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
1141
1431
  if (getFarmRoutePathname(url.pathname.replace(/\\/+$/, '') || '/') === '/sitemap.xml') {
1142
1432
  return applyProductionMiddlewareHeaders(createFarmAgentSitemapResponse(request), middlewareHeaders);
1143
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
+ }
1144
1440
  `
1145
1441
  : ""}if (isFarmAPIPathname(url.pathname, farmApiBasePath) || isFarmAPIPathname(url.pathname)) {
1146
1442
  return applyProductionMiddlewareHeaders(new Response(
@@ -1304,6 +1600,10 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
1304
1600
  }
1305
1601
  `;
1306
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)";
1307
1607
  // Route matching and rendering
1308
1608
  code += `
1309
1609
  // Match the URL to a page component
@@ -1342,21 +1642,27 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
1342
1642
  // every non-RSC environment produces (see core's search-params.ts).
1343
1643
  const searchParams = searchParamsToObject(url.searchParams);
1344
1644
 
1345
- // Page props passed to components (includes middleware shared data)
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)
1346
1651
  const pageProps = { params, searchParams, middlewareData };
1347
1652
  ${ctx.markdown?.enabled
1348
1653
  ? `// The head advertises the page's Markdown mirror as the Link header does, as in core's servers.
1349
1654
  const metadata = addMetadataMarkdownAlternate(
1350
- await resolveFarmRouteMetadata(LayoutModules, pageModule, pageProps),
1655
+ ${routeMetadata},
1351
1656
  getFarmMarkdownAlternatePath(farmMarkdownConfig, url.pathname, { routePathname: getFarmRoutePathname }),
1352
1657
  );`
1353
- : "const metadata = await resolveFarmRouteMetadata(LayoutModules, pageModule, pageProps);"}
1658
+ : `const metadata = ${routeMetadata};`}
1354
1659
  const renderedHead = renderMetadataHead(metadata, { pathname: url.pathname });
1355
- // Injected into <head> by the SSR entry; React renders only the charset.
1660
+ // Injected into <head> by the SSR entry (React renders only the charset), and swapped in by the
1661
+ // browser entry on client navigation.
1356
1662
  const metadataHead =
1357
1663
  (renderedHead.hasExplicitTitle ? '<title>' + renderedHead.title + '</title>' : '') +
1358
1664
  renderedHead.viewport +
1359
- renderedHead.tags;
1665
+ renderedHead.tags${i18n ? " + renderFarmI18nAlternateLinks(request, url.pathname, metadata)" : ""};
1360
1666
  const metadataTitle = resolveMetadataTitle(metadata.title);
1361
1667
 
1362
1668
  debug('Rendering page:', pattern, 'with props:', pageProps);
@@ -1403,9 +1709,20 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
1403
1709
  const Layout = LayoutModules[index].default;
1404
1710
  const layoutProps = { params: pageProps.params, children: layoutContent };
1405
1711
  if (Layout.constructor.name === 'AsyncFunction') {
1406
- 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
+ : ""}
1407
1718
  } else {
1408
- layoutContent = h(Layout, layoutProps);
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);
1409
1726
  }
1410
1727
  }
1411
1728
 
@@ -1441,10 +1758,7 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
1441
1758
  ),
1442
1759
  rootContent: rootInner,
1443
1760
  metadataHead,
1444
- metadata: {
1445
- title: metadataTitle,
1446
- description: typeof metadata.description === 'string' ? metadata.description : undefined,
1447
- },
1761
+ metadata: { title: metadataTitle },
1448
1762
  ${i18n ? " i18n: farmI18nSnapshot,\n" : ""}`;
1449
1763
  // Include action results in payload if actions are enabled
1450
1764
  if (ctx.actionsEnabled) {
@@ -1457,7 +1771,16 @@ ${i18n ? " i18n: farmI18nSnapshot,\n" : ""}`;
1457
1771
  // Check if this is a client-side navigation request
1458
1772
  // Client sends Accept: text/x-component header for RSC requests
1459
1773
  const acceptHeader = request.headers.get('accept') || '';
1460
-
1774
+ ${sharedPageCache
1775
+ ? `const farmPageCacheControl = getFarmPageCacheControl(
1776
+ request,
1777
+ matched,
1778
+ farmReadsBeforeRender,
1779
+ middlewareResult.data,
1780
+ middlewareContext,
1781
+ );
1782
+ `
1783
+ : ""}
1461
1784
  if (renderToReadableStream) {
1462
1785
  // Full RSC mode with streaming
1463
1786
  debug('Using RSC streaming mode');
@@ -1469,7 +1792,7 @@ ${i18n ? " i18n: farmI18nSnapshot,\n" : ""}`;
1469
1792
  // Merge middleware headers with response headers
1470
1793
  const responseHeaders = new Headers(middlewareHeaders);
1471
1794
  responseHeaders.set('content-type', 'text/x-component');
1472
- applyActionResponseHeaders(responseHeaders, request);
1795
+ applyActionResponseHeaders(responseHeaders, request${pageCacheArg});
1473
1796
  return new Response(rscStream, { headers: responseHeaders });
1474
1797
  }
1475
1798
 
@@ -1489,7 +1812,7 @@ ${i18n ? " i18n: farmI18nSnapshot,\n" : ""}`;
1489
1812
  // Merge middleware headers with response headers
1490
1813
  const responseHeaders = new Headers(middlewareHeaders);
1491
1814
  responseHeaders.set('content-type', 'text/html');
1492
- applyActionResponseHeaders(responseHeaders, request);
1815
+ applyActionResponseHeaders(responseHeaders, request${pageCacheArg});
1493
1816
  return new Response(html, { headers: responseHeaders });
1494
1817
  }
1495
1818
  }
@@ -1515,7 +1838,7 @@ ${i18n ? " i18n: farmI18nSnapshot,\n" : ""}`;
1515
1838
  // Merge middleware headers with response headers
1516
1839
  const responseHeaders = new Headers(middlewareHeaders);
1517
1840
  responseHeaders.set('content-type', 'text/html');
1518
- applyActionResponseHeaders(responseHeaders, request);
1841
+ applyActionResponseHeaders(responseHeaders, request${pageCacheArg});
1519
1842
  return new Response(html, { headers: responseHeaders });
1520
1843
  })
1521
1844
  )
@@ -1611,7 +1934,7 @@ ${i18n ? " i18n: farmI18nSnapshot,\n" : ""}`;
1611
1934
  }
1612
1935
  }
1613
1936
 
1614
- ${ctx.llmsTxt?.enabled
1937
+ ${buildsLlmsTxt
1615
1938
  ? `/**
1616
1939
  * agent.llmsTxt, built the same way as core's production server: /llms.txt
1617
1940
  * lists the app's static pages and links to their Markdown mirrors, and
@@ -1631,12 +1954,15 @@ function createFarmLlmsTxtContext(request, context, full) {
1631
1954
  basePath: ${JSON.stringify(ctx.basePath)},
1632
1955
  markdown: farmMarkdownConfig,
1633
1956
  include: farmLlmsTxtConfig.include,
1634
- 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,
1635
1960
  },
1636
1961
  );
1637
1962
  const rootLayout = getRouteModules('/page.tsx', layouts, 'layout')[0];
1638
1963
  return {
1639
1964
  origin,
1965
+ pages,
1640
1966
  defaults: createFarmDefaultLlmsTxt({
1641
1967
  origin,
1642
1968
  pages,
@@ -1765,7 +2091,8 @@ function createFarmAgentSitemapResponse(request) {
1765
2091
  origin: new URL(request.url).origin,
1766
2092
  config: farmAgentSitemapConfig,
1767
2093
  metadataBase: rootLayout && rootLayout.metadata ? rootLayout.metadata.metadataBase : undefined,
1768
- basePath: ${JSON.stringify(ctx.basePath)},
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,
1769
2096
  },
1770
2097
  ),
1771
2098
  {},
@@ -1784,8 +2111,336 @@ function getFarmAgentOrigin(request) {
1784
2111
  );
1785
2112
  }
1786
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
+
1787
2418
  `
1788
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
+ /**
1789
2444
  * Serves a page's Markdown mirror (\`/page.md\` or \`Accept: text/markdown\`) by
1790
2445
  * rendering the page through the normal request path, so middleware and sign-in
1791
2446
  * gates apply; every other request renders as usual, and HTML pages advertise
@@ -1794,7 +2449,7 @@ function getFarmAgentOrigin(request) {
1794
2449
  async function handleFarmPageOrMarkdown(request, context) {
1795
2450
  if (!farmMarkdownConfig.enabled) return handleFarmRequest(request, context);
1796
2451
  const markdown = await createMarkdownMirrorResponse({
1797
- request,
2452
+ request: withoutLoneFarmDeploymentCookie(request),
1798
2453
  config: farmMarkdownConfig,
1799
2454
  routePathname: getFarmRoutePathname,
1800
2455
  // The page the render below selects for the mirrored URL, below the basePath and locale.
@@ -1846,7 +2501,7 @@ function toFarmPayloadRequest(request) {
1846
2501
  farmPayloadRequests.add(payloadRequest);
1847
2502
  return payloadRequest;
1848
2503
  }
1849
-
2504
+ ${generateConfigRoutesRuntime(ctx, configRoutes, localRouteCheck)}
1850
2505
  // The build's prerender pass (Nitro) runs this server with FARM_RSC_PRERENDER set. It seeds one
1851
2506
  // route that lists the static pages, and each prerendered page queues its payload, both through
1852
2507
  // Nitro's x-nitro-prerender response header. Production servers never answer either.
@@ -1910,8 +2565,30 @@ ${ctx.mobileClient
1910
2565
  });
1911
2566
  }
1912
2567
  `
1913
- : ""} const pageRequest = toFarmPayloadRequest(request);
1914
- const response = await handleFarmRequestWithRuntime(pageRequest, context${i18n ? ", pageRequest !== request" : ""});
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
+ : ""}
1915
2592
  if (
1916
2593
  prerendering &&
1917
2594
  pageRequest === request &&
@@ -1922,7 +2599,9 @@ ${ctx.mobileClient
1922
2599
  headers.set('x-nitro-prerender', encodeURIComponent(farmPayloadPath(new URL(request.url).pathname)));
1923
2600
  return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
1924
2601
  }
1925
- return ${ctx.mobileClient === "entry" ? "_applyFarmMobileShellClient(request, response, farmMobileShellClient)" : "response"};
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);
1926
2605
  }
1927
2606
  ${ctx.mobileClient === "entry"
1928
2607
  ? `