@farm.js/plugin 0.1.61 → 0.1.63

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.js +1 -1
  3. package/dist/middleware/index.d.ts +8 -1
  4. package/dist/middleware/index.d.ts.map +1 -1
  5. package/dist/middleware/index.js +16 -10
  6. package/dist/middleware/matching.d.ts +4 -2
  7. package/dist/middleware/matching.d.ts.map +1 -1
  8. package/dist/middleware/matching.js +7 -47
  9. package/dist/rsc/client-sourcemaps.d.ts +13 -0
  10. package/dist/rsc/client-sourcemaps.d.ts.map +1 -0
  11. package/dist/rsc/client-sourcemaps.js +52 -0
  12. package/dist/rsc/document-layouts.d.ts +16 -0
  13. package/dist/rsc/document-layouts.d.ts.map +1 -0
  14. package/dist/rsc/document-layouts.js +82 -0
  15. package/dist/rsc/entries/client.d.ts.map +1 -1
  16. package/dist/rsc/entries/client.js +92 -16
  17. package/dist/rsc/entries/rsc.d.ts.map +1 -1
  18. package/dist/rsc/entries/rsc.js +567 -47
  19. package/dist/rsc/entries/ssr.d.ts.map +1 -1
  20. package/dist/rsc/entries/ssr.js +27 -10
  21. package/dist/rsc/index.d.ts +38 -3
  22. package/dist/rsc/index.d.ts.map +1 -1
  23. package/dist/rsc/index.js +300 -292
  24. package/dist/rsc/middleware-config-module.d.ts +3 -0
  25. package/dist/rsc/middleware-config-module.d.ts.map +1 -1
  26. package/dist/rsc/middleware-config-module.js +41 -28
  27. package/dist/rsc/mobile-client.d.ts +67 -0
  28. package/dist/rsc/mobile-client.d.ts.map +1 -0
  29. package/dist/rsc/mobile-client.js +148 -0
  30. package/dist/rsc/nitro-build.d.ts.map +1 -1
  31. package/dist/rsc/nitro-build.js +268 -81
  32. package/dist/rsc/server-fn-transform.d.ts +1 -5
  33. package/dist/rsc/server-fn-transform.d.ts.map +1 -1
  34. package/dist/rsc/server-fn-transform.js +3 -338
  35. package/dist/rsc/types.d.ts +39 -0
  36. package/dist/rsc/types.d.ts.map +1 -1
  37. package/dist/rsc/vite-plugin-nitro.d.ts +2 -0
  38. package/dist/rsc/vite-plugin-nitro.d.ts.map +1 -1
  39. package/dist/rsc/vite-plugin-nitro.js +12 -2
  40. package/package.json +3 -3
@@ -1,3 +1,11 @@
1
+ import { createRequire } from "node:module";
2
+ import { FARM_RSC_MOBILE_SHELL_CLIENT_PLACEHOLDER } from "../mobile-client.js";
3
+ const require_ = createRequire(import.meta.url);
4
+ /** Core's production source for the \`mcp\` plugin, so both servers merge config the same way. */
5
+ function generateMCPPluginSource() {
6
+ const { generateNativeMCPPluginSource } = require_("@farm.js/core/internal/production-runtime");
7
+ return generateNativeMCPPluginSource({ enabled: true });
8
+ }
1
9
  /**
2
10
  * Generates the terminal middleware-result handling shared by the RSC entry
3
11
  * and its executable contract tests.
@@ -46,11 +54,17 @@ export function generateRscEntry(ctx) {
46
54
  const middlewareConfigImports = (ctx.middlewareConfigPaths ?? [])
47
55
  .map((configPath, index) => `import * as FarmMiddlewareConfigModule${index} from ${JSON.stringify(configPath.replace(/\\/g, "/"))};`)
48
56
  .join("\n");
57
+ const mcpConfigImports = (ctx.mcpConfigPaths ?? [])
58
+ .map((configPath, index) => `import * as FarmMCPConfigModule${index} from ${JSON.stringify(configPath.replace(/\\/g, "/"))};`)
59
+ .join("\n");
60
+ const mcpSource = ctx.mcpConfigPaths?.length ? generateMCPPluginSource() : null;
49
61
  const middlewareConfigValues = (ctx.middlewareConfigPaths ?? []).map((_configPath, index) => `(FarmMiddlewareConfigModule${index}.default || FarmMiddlewareConfigModule${index})`);
50
62
  let code = `
51
63
  import React from 'react';
52
64
  import ServerErrorFallback from '/.farm/rsc-entries/error-fallback.tsx';
53
65
  ${middlewareConfigImports}
66
+ ${mcpConfigImports}
67
+ ${mcpSource ? `${mcpSource.importSource}\nimport { mergePluginAPIRoutes } from '@farm.js/core/api/runtime';` : ""}
54
68
  import { registerAPIRouteShape } from '@farm.js/core/api/runtime';
55
69
  import {
56
70
  renderToReadableStream,
@@ -76,14 +90,15 @@ import {
76
90
  applyProductionMiddlewareHeaders,
77
91
  createProductionMiddlewareRunner,
78
92
  } from '@farm.js/core/middleware';
79
- import {
93
+ import { _withFarmGuardedResponseCache } from '@farm.js/core/internal/production-runtime';
94
+ ${ctx.mobileClient === "entry" ? "import { _applyFarmMobileShellClient } from '@farm.js/core/internal/production-runtime';\n" : ""}import {
80
95
  getAllowedAPIRouteMethods,
81
96
  invokeAPIRouteEndpoint,
82
97
  isFarmAPIPathname,
83
98
  matchAPIRouteAtBasePath,
84
99
  } from '@farm.js/core/api/runtime';
85
100
  import { _runWithAfterRequest } from '@farm.js/core/after';
86
- import { _runWithAPIRequestRuntime, _runWithCurrentRequest, searchParamsToObject } from '@farm.js/core/internal/production-runtime';
101
+ import { _runWithAPIRequestRuntime, _runWithCurrentRequest, cloneFarmRequestWithContext, searchParamsToObject } from '@farm.js/core/internal/production-runtime';
87
102
  import { getFarmRedirectError, isFarmNotFoundError } from '@farm.js/core/internal/production-runtime';
88
103
  import {
89
104
  parseRoutePath,
@@ -91,10 +106,69 @@ import {
91
106
  compareRouteSpecificity,
92
107
  getRoutePatternSpecificity,
93
108
  } from '@farm.js/core/internal/production-runtime';
109
+ import {
110
+ appMiddlewareMayHandlePath,
111
+ configMiddlewareMayHandlePath,
112
+ materializeSSGRoutePath,
113
+ mergeMetadata,
114
+ mergeModuleViewport,
115
+ mergeRouteRenderingDirectiveConfig,
116
+ renderMetadataHead,
117
+ resolveMetadataTitle,
118
+ } from '@farm.js/core/internal/production-runtime';
119
+
120
+ import {
121
+ FARM_MARKDOWN_CONTENT_TYPE,
122
+ applyMarkdownNegotiationHeaders,
123
+ createFarmMarkdownErrorBody,
124
+ createMarkdownMirrorResponse,
125
+ farmRequestWantsMarkdown,
126
+ } from '@farm.js/core/markdown';
94
127
 
128
+ ${ctx.images && ctx.images.runtime !== "none"
129
+ ? `import { createCloudflareImageTransformer, createFarmImageHandler } from '@farm.js/core/image/server';
130
+ ${ctx.images.runtime === "node"
131
+ ? "import { createNodeImageFetcher, createNodeImageUrlValidator, createSharpImageTransformer } from '@farm.js/core/image/sharp';"
132
+ : ""}
133
+ const farmImageConfig = ${JSON.stringify(ctx.images.config)};
134
+ const farmImageHandler = createFarmImageHandler(farmImageConfig, ${ctx.images.runtime === "cloudflare"
135
+ ? `{
136
+ transform: createCloudflareImageTransformer(),
137
+ onError(error) { console.error('[Farm Image]', error); },
138
+ }`
139
+ : `{
140
+ transform: createSharpImageTransformer(),
141
+ fetchRemote: createNodeImageFetcher(farmImageConfig),
142
+ validateRemoteUrl: createNodeImageUrlValidator(farmImageConfig),
143
+ onError(error) { console.error('[Farm Image]', error); },
144
+ }`});`
145
+ : "const farmImageHandler = null;"}
146
+ const farmImagePath = ${JSON.stringify(ctx.images?.path ?? "/_farm/image")};
147
+ ${ctx.images
148
+ ? `// <Image> reads this when @farm.js/core/image is not bundled (dev, or an external dependency),
149
+ // where the __FARM_IMAGE_CONFIG__ define never reaches it. The SSR environment shares the process.
150
+ globalThis.__FARM_IMAGE_CONFIG__ = ${JSON.stringify(ctx.images.public)};`
151
+ : ""}
95
152
  const farmDeploymentId = ${JSON.stringify(ctx.deploymentId)};
96
153
  const farmApiBasePath = ${JSON.stringify(ctx.apiBasePath ?? "/api")};
154
+ const farmMarkdownConfig = ${JSON.stringify(ctx.markdown ?? { enabled: false, expose: [], cache: false, includeMetadata: true })};
97
155
  `;
156
+ if (ctx.llmsTxt?.enabled) {
157
+ code += `import {
158
+ collectFarmLlmsTxtPages,
159
+ createFarmDefaultLlmsTxt,
160
+ createFarmLlmsFullRenderer,
161
+ createFarmLlmsMarkdownReader,
162
+ createFarmMetadataRouteResponse,
163
+ farmPathGuardCoversPage,
164
+ renderFarmLlmsFullTxt,
165
+ } from '@farm.js/core/internal/production-runtime';
166
+ import { FARM_MARKDOWN_ANONYMOUS_CLIENT_ADDRESS } from '@farm.js/core/internal/app-markdown-runtime';
167
+
168
+ const farmLlmsTxtConfig = ${JSON.stringify(ctx.llmsTxt)};
169
+ const farmLlmsFullRenderer = createFarmLlmsFullRenderer({ revalidate: farmLlmsTxtConfig.revalidate });
170
+ `;
171
+ }
98
172
  if (ctx.actionsEnabled) {
99
173
  code += `import {
100
174
  createServerActionRequestErrorResponse,
@@ -106,6 +180,56 @@ const farmApiBasePath = ${JSON.stringify(ctx.apiBasePath ?? "/api")};
106
180
  } from '@farm.js/core/server-action-security';
107
181
 
108
182
  const serverActionSecurity = ${JSON.stringify(ctx.serverActions)};
183
+ `;
184
+ }
185
+ // In development, a page, layout, loading or error file that fails to load
186
+ // fails only the routes that use it. Eager globs would fail the whole entry,
187
+ // so every route returned the same error until the file was fixed. The
188
+ // modules still load once, in order, before the first request. Middleware
189
+ // and API routes stay eager: skipping a broken auth middleware would leave
190
+ // its routes unprotected. Production keeps eager globs, where a broken
191
+ // import already fails the build.
192
+ const isolateRouteModules = ctx.development === true;
193
+ const uiRouteGlob = (pattern) => isolateRouteModules
194
+ ? `await loadFarmDevRouteModules(import.meta.glob(${JSON.stringify(pattern)}))`
195
+ : `import.meta.glob(${JSON.stringify(pattern)}, { eager: true })`;
196
+ if (isolateRouteModules) {
197
+ code += `
198
+ const farmRouteLoadErrors = new Map();
199
+
200
+ async function loadFarmDevRouteModules(loaders) {
201
+ const modules = {};
202
+ for (const [filePath, load] of Object.entries(loaders)) {
203
+ try {
204
+ modules[filePath] = await load();
205
+ } catch (error) {
206
+ console.error('[Farm.js] Could not load ' + filePath + ':', error);
207
+ const failed = {
208
+ default: function FarmRouteLoadFailure() {
209
+ throw error;
210
+ },
211
+ };
212
+ farmRouteLoadErrors.set(failed, error);
213
+ modules[filePath] = failed;
214
+ }
215
+ }
216
+ return modules;
217
+ }
218
+
219
+ /** The load error of a module the matched route renders with, if any. */
220
+ function findFarmRouteLoadError(matched) {
221
+ if (farmRouteLoadErrors.size === 0) return undefined;
222
+ const routeModules = [
223
+ pages[matched.pattern],
224
+ ...getRouteModules(matched.pattern, layouts, 'layout'),
225
+ ...getRouteModules(matched.pattern, loadings, 'loading'),
226
+ ...getRouteModules(matched.pattern, errors, 'error'),
227
+ ];
228
+ for (const module of routeModules) {
229
+ if (farmRouteLoadErrors.has(module)) return farmRouteLoadErrors.get(module);
230
+ }
231
+ return undefined;
232
+ }
109
233
  `;
110
234
  }
111
235
  // Auto-discover pages, layouts, and middleware using Vite's glob import
@@ -132,14 +256,18 @@ function applyActionResponseHeaders(headers, request) {
132
256
  headers.set('cache-control', 'no-store');
133
257
  headers.set('x-content-type-options', 'nosniff');
134
258
  }
259
+ // A page renders per request (cookies, headers, client address), so a shared
260
+ // cache must not keep its HTML or Flight payload unless middleware chose a
261
+ // policy. Core's server defaults pages the same way.
262
+ if (!headers.has('cache-control')) headers.set('cache-control', 'private, no-store');
135
263
  }
136
264
 
137
265
  // Auto-discover all route modules. Every glob remains a literal so Vite can analyze it.
138
266
  ${routeSourceRoots
139
- .map((root, index) => `const pages${index} = import.meta.glob(${JSON.stringify(`${root.glob}/**/page.{tsx,jsx,ts,js}`)}, { eager: true });
140
- const layouts${index} = import.meta.glob(${JSON.stringify(`${root.glob}/**/layout.{tsx,jsx,ts,js}`)}, { eager: true });
141
- const loadings${index} = import.meta.glob(${JSON.stringify(`${root.glob}/**/loading.{tsx,jsx,ts,js}`)}, { eager: true });
142
- const errors${index} = import.meta.glob(${JSON.stringify(`${root.glob}/**/error.{tsx,jsx,ts,js}`)}, { eager: true });
267
+ .map((root, index) => `const pages${index} = ${uiRouteGlob(`${root.glob}/**/page.{tsx,jsx,ts,js}`)};
268
+ const layouts${index} = ${uiRouteGlob(`${root.glob}/**/layout.{tsx,jsx,ts,js}`)};
269
+ const loadings${index} = ${uiRouteGlob(`${root.glob}/**/loading.{tsx,jsx,ts,js}`)};
270
+ const errors${index} = ${uiRouteGlob(`${root.glob}/**/error.{tsx,jsx,ts,js}`)};
143
271
  const middlewares${index} = import.meta.glob(${JSON.stringify(`${root.glob}/**/middleware.{tsx,jsx,ts,js}`)}, { eager: true });
144
272
  const apiRouteModules${index} = import.meta.glob(${JSON.stringify(`${root.glob}/api/**/route.{tsx,jsx,ts,js}`)}, { eager: true });
145
273
  const routeDefinitionModules${index} = import.meta.glob(${JSON.stringify(root.sourceGlob === root.glob
@@ -192,6 +320,14 @@ const pages = mergeRouteModules([${routeRoots
192
320
  const layouts = mergeRouteModules([${routeRoots
193
321
  .map((root, index) => `{ base: ${JSON.stringify(root.base)}, modules: layouts${index} }`)
194
322
  .join(", ")}]);
323
+ // Root layouts that render <html> themselves own the document, as in Next.js.
324
+ const farmDocumentLayoutKeys = new Set(${JSON.stringify(ctx.documentLayouts ?? [])});
325
+ const farmDocumentLayoutModules = new Set(
326
+ Object.entries(layouts)
327
+ .filter(([key]) => farmDocumentLayoutKeys.has(key))
328
+ .map(([, module]) => module),
329
+ );
330
+
195
331
  const loadings = mergeRouteModules([${routeRoots
196
332
  .map((root, index) => `{ base: ${JSON.stringify(root.base)}, modules: loadings${index} }`)
197
333
  .join(", ")}]);
@@ -283,7 +419,42 @@ function registerApiRouteSources(fileModules, definitionModules, sourceCount) {
283
419
  }
284
420
 
285
421
  registerApiRouteSources(apiRouteModules, routeDefinitionModules, ${routeSourceRoots.length});
286
-
422
+ ${mcpSource
423
+ ? `
424
+ // mcp: the same plugin core's production server mounts, built from the mcp
425
+ // config read from each config file, layers first.
426
+ const farmNativeMCPPlugin = (() => {
427
+ const farmRuntimeConfigs = [${(ctx.mcpConfigPaths ?? [])
428
+ .map((_path, index) => `(FarmMCPConfigModule${index}.default || FarmMCPConfigModule${index})`)
429
+ .join(", ")}];
430
+ ${mcpSource.registerSource}
431
+ return farmNativeMCPPlugin;
432
+ })();
433
+ if (farmNativeMCPPlugin) {
434
+ const mountedRoutes = [...apiRouteMap.values()].map((route) => ({
435
+ path: route.path,
436
+ methods: [...route.methods],
437
+ endpoints: { ...route.handlers },
438
+ }));
439
+ // Rejects a plugin route that would replace an app endpoint. An MCP tool calls its
440
+ // endpoint through handler(), so the middleware guarding that path runs for it.
441
+ for (const route of mergePluginAPIRoutes(mountedRoutes, [farmNativeMCPPlugin], undefined, {
442
+ dispatch: (request) => handler(request),
443
+ })) {
444
+ for (const method of route.pluginMethods ?? []) {
445
+ let target = apiRouteMap.get(route.path);
446
+ if (!target) {
447
+ target = { path: route.path, methods: [], handlers: {}, files: {}, sources: {} };
448
+ apiRouteMap.set(route.path, target);
449
+ }
450
+ target.methods.push(method);
451
+ target.handlers[method] = route.endpoints[method];
452
+ target.files[method] = 'plugin:' + farmNativeMCPPlugin.name;
453
+ }
454
+ }
455
+ }
456
+ `
457
+ : ""}
287
458
  async function handleAPIRequest(request) {
288
459
  const url = new URL(request.url);
289
460
  const match = matchAPIRouteAtBasePath(apiRouteMap, url.pathname, farmApiBasePath);
@@ -331,9 +502,20 @@ const farmMiddlewareRunner = createProductionMiddlewareRunner({
331
502
  .filter((entry) => entry.path !== null)
332
503
  // Root first, as core runs them: a nested guard can rely on what its
333
504
  // parent middleware set, and glob order is alphabetical, not by depth.
334
- .sort((left, right) => middlewareRouteDepth(left.path) - middlewareRouteDepth(right.path)),
505
+ // Route groups share a URL path; the shallower file runs first, so
506
+ // '/middleware.ts' precedes '/(app)/middleware.ts'.
507
+ .sort(
508
+ (left, right) =>
509
+ middlewareRouteDepth(left.path) - middlewareRouteDepth(right.path) ||
510
+ left.path.localeCompare(right.path) ||
511
+ middlewareRouteDepth(left.filePath) - middlewareRouteDepth(right.filePath) ||
512
+ left.filePath.localeCompare(right.filePath),
513
+ ),
335
514
  i18n: ${JSON.stringify(ctx.i18n) ?? "undefined"},
336
515
  server: ${JSON.stringify(ctx.server) ?? "undefined"},
516
+ apiBasePath: farmApiBasePath,
517
+ // matchRoute() reads url.pathname as received, so middleware guards that path too.
518
+ rawPathRouting: true,
337
519
  });
338
520
 
339
521
  debug('Discovered pages:', Object.keys(pages));
@@ -346,22 +528,37 @@ debug('Discovered API routes:', Array.from(apiRouteMap.keys()));
346
528
  /**
347
529
  * Convert an app-relative middleware file path to the route it guards, with the
348
530
  * same rules as core's middleware discovery: a route group such as
349
- * '(protected)' adds no URL segment, and a '_private' or dot-prefixed folder
531
+ * '(protected)' or a parallel route slot such as '@team' adds no URL segment,
532
+ * an intercepting folder guards the URL it intercepts, a '_private' folder
533
+ * routes its pages so its middleware guards them, and a dot-prefixed folder
350
534
  * holds no routes, so its middleware never runs (null).
351
535
  * e.g., '/middleware.ts' -> '/'
352
536
  * e.g., '/(protected)/dashboard/middleware.ts' -> '/dashboard'
537
+ * e.g., '/dashboard/@team/middleware.ts' -> '/dashboard'
538
+ * e.g., '/feed/@modal/(.)photo/middleware.ts' -> '/feed/photo'
353
539
  */
354
540
  function middlewarePathToRoute(filePath) {
355
541
  const segments = filePath
356
542
  .replace(/\\/middleware\\.[tj]sx?$/, '')
357
543
  .split('/')
358
544
  .filter(Boolean);
359
- if (segments.some((segment) => segment.startsWith('_') || segment.startsWith('.'))) {
545
+ if (segments.some((segment) => segment.startsWith('.'))) {
360
546
  return null;
361
547
  }
362
- const routeSegments = segments.filter(
363
- (segment) => !(segment.startsWith('(') && segment.endsWith(')')),
364
- );
548
+ const routeSegments = [];
549
+ for (const segment of segments) {
550
+ const marker = /^((?:\\(\\.\\.\\))+|\\(\\.\\.\\.\\)|\\(\\.\\))(.*)$/.exec(segment);
551
+ if (marker) {
552
+ if (marker[1] === '(...)') routeSegments.length = 0;
553
+ else if (marker[1] !== '(.)') routeSegments.splice(-(marker[1].length / 4));
554
+ if (marker[2]) routeSegments.push(marker[2]);
555
+ continue;
556
+ }
557
+ if ((segment.startsWith('(') && segment.endsWith(')')) || /^@[A-Za-z][A-Za-z0-9_-]*$/.test(segment)) {
558
+ continue;
559
+ }
560
+ routeSegments.push(segment);
561
+ }
365
562
  return routeSegments.length === 0 ? '/' : '/' + routeSegments.join('/');
366
563
  }
367
564
 
@@ -420,7 +617,12 @@ const RouteErrorBoundary = React.Component
420
617
 
421
618
  // Parse and rank once per entry initialization, not on every request. Use the
422
619
  // same validation, decoding and specificity rules as Farm's ordinary router.
423
- const pageRoutes = Object.entries(pages).map(([filePath, module]) => ({
620
+ // RSC renders no parallel route slots, so a page inside '@modal/...' would otherwise
621
+ // answer at its literal folder path ('/feed/@modal/(.)photo/1'), past the middleware
622
+ // that guards the URL it intercepts.
623
+ const pageRoutes = Object.entries(pages)
624
+ .filter(([filePath]) => !filePath.split('/').some((segment) => /^@[A-Za-z][A-Za-z0-9_-]*$/.test(segment)))
625
+ .map(([filePath, module]) => ({
424
626
  filePath,
425
627
  module,
426
628
  segments: parseRoutePath(filePath).segments,
@@ -443,7 +645,7 @@ function matchRoute(pathname) {
443
645
  Page: module.default,
444
646
  pattern: filePath,
445
647
  params: match.params,
446
- pageMetadata: module.metadata,
648
+ module,
447
649
  };
448
650
  }
449
651
  }
@@ -452,13 +654,77 @@ function matchRoute(pathname) {
452
654
  return null;
453
655
  }
454
656
 
455
- function mergeDocumentMetadata(...sources) {
456
- const metadata = {};
457
- for (const source of sources) {
458
- if (typeof source?.title === 'string') metadata.title = source.title;
459
- if (typeof source?.description === 'string') metadata.description = source.description;
657
+ // Each page's parsed rendering directive and whether its source reads request state, baked by
658
+ // the build because module exports cannot tell.
659
+ const farmPageRenderingDirectives = ${JSON.stringify(ctx.pageRenderingDirectives ?? {})};
660
+
661
+ /**
662
+ * The URL paths the build prerenders, by core's SSG rules: a page asks to be static
663
+ * (dynamic = "force-static", generateStaticParams, "use ssg"), does not read request
664
+ * state, and does not revalidate. A prerendered page is a static file the server never sees, so a
665
+ * path any middleware may handle stays server-rendered.
666
+ */
667
+ async function collectFarmStaticPages() {
668
+ ${ctx.i18n?.enabled
669
+ ? `console.info('[Farm.js] Prerendering is off: i18n resolves the locale per request.');
670
+ return [];`
671
+ : ""}
672
+ const middlewareRoutes = Object.keys(middlewares)
673
+ .map((filePath) => ({ path: middlewarePathToRoute(filePath) }))
674
+ .filter((route) => route.path !== null);
675
+ const paths = new Set();
676
+ for (const { filePath, module, segments } of pageRoutes) {
677
+ const rendering = mergeRouteRenderingDirectiveConfig(farmPageRenderingDirectives[filePath], module);
678
+ if (!rendering.ssg || rendering.revalidate !== undefined) continue;
679
+ const pattern = '/' + segments
680
+ .map((part) => part.isCatchAll
681
+ ? (part.isOptional ? '[[...' + part.segment + ']]' : '[...' + part.segment + ']')
682
+ : part.isDynamic ? '[' + part.segment + ']' : part.segment)
683
+ .join('/');
684
+ let pagePaths;
685
+ try {
686
+ if (!segments.some((part) => part.isDynamic)) {
687
+ pagePaths = [pattern];
688
+ } else {
689
+ const getStaticPaths = module.getStaticPaths || module.generateStaticParams;
690
+ if (typeof getStaticPaths !== 'function') {
691
+ throw new Error('a static route with dynamic segments needs generateStaticParams()');
692
+ }
693
+ pagePaths = (await getStaticPaths()).map((params) => materializeSSGRoutePath(pattern, params));
694
+ }
695
+ } catch (error) {
696
+ console.error('[Farm.js] Rendering ' + filePath + ' on each request: could not list its static paths.', error);
697
+ continue;
698
+ }
699
+ for (const pagePath of pagePaths) {
700
+ if (
701
+ appMiddlewareMayHandlePath(middlewareRoutes, pagePath) ||
702
+ configMiddlewareMayHandlePath(farmConfigMiddleware, pagePath)
703
+ ) {
704
+ continue;
705
+ }
706
+ paths.add(pagePath);
707
+ }
708
+ }
709
+ return [...paths];
710
+ }
711
+
712
+ // The route's metadata as core's server resolves it: layouts root to leaf, then the page, each
713
+ // module's \`metadata\`, \`generateMetadata()\` and viewport exports merged in order.
714
+ async function resolveFarmRouteMetadata(layoutModules, pageModule, pageProps) {
715
+ let metadata = {};
716
+ for (const layoutModule of layoutModules) {
717
+ metadata = mergeMetadata(metadata, layoutModule.metadata);
718
+ if (typeof layoutModule.generateMetadata === 'function') {
719
+ metadata = mergeMetadata(metadata, await layoutModule.generateMetadata({ params: pageProps.params }));
720
+ }
721
+ metadata = await mergeModuleViewport(metadata, layoutModule, { params: pageProps.params });
460
722
  }
461
- return metadata;
723
+ metadata = mergeMetadata(metadata, pageModule?.metadata);
724
+ if (typeof pageModule?.generateMetadata === 'function') {
725
+ metadata = mergeMetadata(metadata, await pageModule.generateMetadata(pageProps));
726
+ }
727
+ return mergeModuleViewport(metadata, pageModule ?? {}, pageProps);
462
728
  }
463
729
 
464
730
  /**
@@ -499,6 +765,14 @@ function getLayoutModules(pageFilePath) {
499
765
  return getRouteModules(pageFilePath, layouts, 'layout');
500
766
  }
501
767
 
768
+ // Flight keeps only the digest onError returns for a server error. A notFound() or redirect() keeps
769
+ // its own, so the request handler still answers 404 or the redirect; other errors are logged as
770
+ // React's default handler logs them.
771
+ function farmRscOnError(error) {
772
+ if (getFarmRedirectError(error) || isFarmNotFoundError(error)) return error.digest;
773
+ console.error(error);
774
+ }
775
+
502
776
  function getMatchingBoundary(pageFilePath, modules, kind) {
503
777
  // Before page selection (for example, middleware failure), only the root
504
778
  // boundary applies. Do not guess a route from a partially processed URL.
@@ -509,8 +783,19 @@ function getMatchingBoundary(pageFilePath, modules, kind) {
509
783
  /**
510
784
  * Main request handler - entry point for both dev and production (Nitro).
511
785
  * Exported as { fetch: handler } for the RSC/Nitro contract (see vite-plugin-rsc-deploy-example).
786
+ *
787
+ * Middleware that let a request through may have been a guard: an IP allowlist, an API key
788
+ * header, a VPN header. A CDN keys its copy by URL and never runs the guard on a hit, so
789
+ * whatever such a request answers stays out of shared caches, as in core's server. Only
790
+ * middleware declaring cache: "public" leaves the policy alone.
512
791
  */
513
792
  async function handleFarmRequest(request, context) {
793
+ const farmCacheGuard = { guarded: false };
794
+ const response = await resolveFarmRequest(farmCacheGuard, request, context);
795
+ return farmCacheGuard.guarded ? _withFarmGuardedResponseCache(response) : response;
796
+ }
797
+
798
+ async function resolveFarmRequest(farmCacheGuard, request, context) {
514
799
  let url = new URL(request.url);
515
800
  let matchedPage = null;
516
801
  let errorData = new Map();
@@ -550,6 +835,7 @@ async function handleFarmRequest(request, context) {
550
835
  // Execute middleware first
551
836
  const middlewareResult = await executeMiddleware(request, context);
552
837
  ${generateRscMiddlewareResultHandling()}
838
+ if (middlewareResult.guarded) farmCacheGuard.guarded = true;
553
839
 
554
840
  request = middlewareResult.request;
555
841
  url = new URL(request.url);
@@ -572,11 +858,23 @@ async function handleFarmRequest(request, context) {
572
858
  _runWithMiddlewareContext(middlewareContext, async () => {
573
859
  const glob = '';
574
860
 
575
- const apiResponse = await handleAPIRequest(request.clone());
861
+ if (farmImageHandler && url.pathname === farmImagePath) {
862
+ const imageResponse = await farmImageHandler(request);
863
+ if (imageResponse) return imageResponse;
864
+ }
865
+
866
+ // A plain clone of the request would let some undici versions cancel the original's body when the
867
+ // declined clone is collected, before a server action reads it.
868
+ const apiResponse = await handleAPIRequest(cloneFarmRequestWithContext(request));
576
869
  if (apiResponse) {
577
870
  return applyProductionMiddlewareHeaders(apiResponse, middlewareHeaders);
578
871
  }
579
- if (isFarmAPIPathname(url.pathname, farmApiBasePath) || isFarmAPIPathname(url.pathname)) {
872
+ ${ctx.llmsTxt?.enabled
873
+ ? `// agent.llmsTxt: answered after middleware, so its redirects and headers apply.
874
+ const llmsResponse = await handleFarmLlmsTxtRequest(request, context);
875
+ if (llmsResponse) return applyProductionMiddlewareHeaders(llmsResponse, middlewareHeaders);
876
+ `
877
+ : ""}if (isFarmAPIPathname(url.pathname, farmApiBasePath) || isFarmAPIPathname(url.pathname)) {
580
878
  return applyProductionMiddlewareHeaders(new Response(
581
879
  JSON.stringify({ error: 'API route not found', pathname: url.pathname }),
582
880
  { status: 404, headers: { 'Content-Type': 'application/json' } },
@@ -696,12 +994,13 @@ async function handleFarmRequest(request, context) {
696
994
  return new Response(null, { status: 499, headers: { 'Cache-Control': 'no-store' } });
697
995
  }
698
996
  // No client router here, so the redirect has to be a real HTTP
699
- // redirect the browser follows on its own.
997
+ // redirect the browser follows on its own. 303 makes it a GET, as islands mode
998
+ // answers: a 307 or 308 would post the form again to the target.
700
999
  const formRedirect = getFarmRedirectError(e);
701
1000
  if (formRedirect) {
702
1001
  debug('Form action redirected:', formRedirect.url);
703
1002
  return new Response(null, {
704
- status: formRedirect.status,
1003
+ status: 303,
705
1004
  headers: { location: formRedirect.url, 'Cache-Control': 'no-store' },
706
1005
  });
707
1006
  }
@@ -731,15 +1030,26 @@ async function handleFarmRequest(request, context) {
731
1030
 
732
1031
  if (!matched) {
733
1032
  debug('404 - No route found for:', url.pathname);
1033
+ // Agents that read in Markdown get a Markdown 404, as in core's server.
1034
+ if (farmMarkdownConfig.enabled && farmRequestWantsMarkdown(url.pathname, request.headers.get('accept'))) {
1035
+ return new Response(createFarmMarkdownErrorBody(404, url.pathname), {
1036
+ status: 404,
1037
+ headers: {
1038
+ 'Content-Type': FARM_MARKDOWN_CONTENT_TYPE,
1039
+ 'X-Farm-Markdown-Error': '404',
1040
+ 'Cache-Control': 'no-store',
1041
+ },
1042
+ });
1043
+ }
734
1044
  return new Response('Not Found', { status: 404 });
735
1045
  }
736
1046
 
737
- const { Page, pattern, params, pageMetadata } = matched;
738
- const LayoutModules = getLayoutModules(pattern);
739
- const metadata = mergeDocumentMetadata(
740
- ...LayoutModules.map((layoutModule) => layoutModule.metadata),
741
- pageMetadata,
742
- );
1047
+ const { Page, pattern, params, module: pageModule } = matched;
1048
+ ${isolateRouteModules
1049
+ ? `const routeLoadError = findFarmRouteLoadError(matched);
1050
+ if (routeLoadError) throw routeLoadError;
1051
+ `
1052
+ : ""}const LayoutModules = getLayoutModules(pattern);
743
1053
  const configuredRoutesDir = ${ctx.routesDir === undefined ? "undefined" : JSON.stringify(ctx.routesDir)};
744
1054
  const routesDir = configuredRoutesDir === undefined ? 'app' : configuredRoutesDir.trim();
745
1055
  const routesPath = routesDir ? '/' + routesDir : '';
@@ -752,6 +1062,14 @@ async function handleFarmRequest(request, context) {
752
1062
 
753
1063
  // Page props passed to components (includes middleware shared data)
754
1064
  const pageProps = { params, searchParams, middlewareData };
1065
+ const metadata = await resolveFarmRouteMetadata(LayoutModules, pageModule, pageProps);
1066
+ const renderedHead = renderMetadataHead(metadata, { pathname: url.pathname });
1067
+ // Injected into <head> by the SSR entry; React renders only the charset.
1068
+ const metadataHead =
1069
+ (renderedHead.hasExplicitTitle ? '<title>' + renderedHead.title + '</title>' : '') +
1070
+ renderedHead.viewport +
1071
+ renderedHead.tags;
1072
+ const metadataTitle = resolveMetadataTitle(metadata.title);
755
1073
 
756
1074
  debug('Rendering page:', pattern, 'with props:', pageProps);
757
1075
 
@@ -797,26 +1115,36 @@ async function handleFarmRequest(request, context) {
797
1115
  }
798
1116
  }
799
1117
 
800
- // Single wrapper so #root has exactly one child (avoids duplicate block / "two pages" in DOM).
801
- const rootInner = h('div', { 'data-farm-root': 'true' }, layoutContent);
802
- // Build the full page. root = full document (for SSR). rootContent = single wrapper + layout (for client hydration).
1118
+ // A root layout that renders <html> owns the document, as in Next.js: the head elements below
1119
+ // are hoisted into its <head> by React, and the browser hydrates the whole document.
1120
+ const ownsDocument =
1121
+ LayoutModules.length > 0 && farmDocumentLayoutModules.has(LayoutModules[0]);
1122
+ // Otherwise a single wrapper, so #root has exactly one child (avoids a duplicate block in the DOM).
1123
+ const rootInner = ownsDocument
1124
+ ? h(
1125
+ React.Fragment,
1126
+ null,
1127
+ h('meta', { charSet: 'utf-8' }),
1128
+ layoutContent,
1129
+ )
1130
+ : h('div', { 'data-farm-root': 'true' }, layoutContent);
1131
+ // Build the full page. root = full document (for SSR). rootContent = what the browser hydrates.
803
1132
  const payload = {
804
- root: h('html', null,
1133
+ ownsDocument,
1134
+ root: ownsDocument ? rootInner : h('html', null,
805
1135
  h('head', null,
806
1136
  h('meta', { charSet: 'utf-8' }),
807
- h('meta', { name: 'viewport', content: 'width=device-width, initial-scale=1' }),
808
- h('link', { rel: 'icon', href: 'data:,' }),
809
- metadata?.title ? h('title', null, metadata.title) : null,
810
- metadata?.description ? h('meta', { name: 'description', content: metadata.description }) : null
1137
+ renderedHead.hasFavicon ? null : h('link', { rel: 'icon', href: 'data:,' }),
811
1138
  ),
812
1139
  h('body', null,
813
1140
  h('div', { id: 'root' }, rootInner)
814
1141
  )
815
1142
  ),
816
1143
  rootContent: rootInner,
1144
+ metadataHead,
817
1145
  metadata: {
818
- title: typeof metadata?.title === 'string' ? metadata.title : undefined,
819
- description: typeof metadata?.description === 'string' ? metadata.description : undefined,
1146
+ title: metadataTitle,
1147
+ description: typeof metadata.description === 'string' ? metadata.description : undefined,
820
1148
  },
821
1149
  `;
822
1150
  // Include action results in payload if actions are enabled
@@ -835,7 +1163,7 @@ async function handleFarmRequest(request, context) {
835
1163
  // Full RSC mode with streaming
836
1164
  debug('Using RSC streaming mode');
837
1165
 
838
- const rscStream = renderToReadableStream(payload${ctx.actionsEnabled ? ", { temporaryReferences }" : ""});
1166
+ const rscStream = renderToReadableStream(payload, { onError: farmRscOnError${ctx.actionsEnabled ? ", temporaryReferences" : ""} });
839
1167
 
840
1168
  if (acceptHeader.includes('text/x-component')) {
841
1169
  debug('Returning RSC stream for client navigation');
@@ -874,8 +1202,8 @@ async function handleFarmRequest(request, context) {
874
1202
  h('meta', { charSet: 'utf-8' }),
875
1203
  h('meta', { name: 'viewport', content: 'width=device-width, initial-scale=1' }),
876
1204
  h('link', { rel: 'icon', href: 'data:,' }),
877
- metadata?.title ? h('title', null, metadata.title) : null,
878
- metadata?.description ? h('meta', { name: 'description', content: metadata.description }) : null,
1205
+ metadataTitle ? h('title', null, metadataTitle) : null,
1206
+ typeof metadata.description === 'string' ? h('meta', { name: 'description', content: metadata.description }) : null,
879
1207
  h('link', { rel: 'stylesheet', href: globalsCssPath, as: 'style', precedence: 'default' }),
880
1208
  h('script', { type: 'module', src: '/@vite/client' })
881
1209
  ),
@@ -894,7 +1222,11 @@ async function handleFarmRequest(request, context) {
894
1222
  )
895
1223
  );
896
1224
  } catch (err) {
897
- const redirect = getFarmRedirectError(err);
1225
+ ${isolateRouteModules
1226
+ ? `// A file that failed to load: show the dev error page, not error.tsx.
1227
+ if ([...farmRouteLoadErrors.values()].includes(err)) throw err;
1228
+ `
1229
+ : ""}const redirect = getFarmRedirectError(err);
898
1230
  if (redirect) return new Response(null, { status: redirect.status, headers: { location: redirect.url, 'cache-control': 'no-store' } });
899
1231
  if (isFarmNotFoundError(err)) return new Response('Not Found', { status: 404, headers: { 'cache-control': 'no-store' } });
900
1232
  console.error('[RSC] Handler error:', err);
@@ -943,7 +1275,7 @@ async function handleFarmRequest(request, context) {
943
1275
  rootContent: rootInner,
944
1276
  metadata: { title: 'Error' },
945
1277
  };
946
- const rscStream = renderToReadableStream(payload);
1278
+ const rscStream = renderToReadableStream(payload, { onError: farmRscOnError });
947
1279
  const headers = new Headers(errorHeaders);
948
1280
  headers.set('cache-control', 'private, no-store');
949
1281
  headers.set('x-content-type-options', 'nosniff');
@@ -980,13 +1312,201 @@ async function handleFarmRequest(request, context) {
980
1312
  }
981
1313
  }
982
1314
 
1315
+ ${ctx.llmsTxt?.enabled
1316
+ ? `/**
1317
+ * agent.llmsTxt, built the same way as core's production server: /llms.txt
1318
+ * lists the app's static pages and links to their Markdown mirrors, and
1319
+ * /llms-full.txt inlines each mirror.
1320
+ */
1321
+ function createFarmLlmsTxtContext(request, context, full) {
1322
+ const origin = new URL(request.url).origin;
1323
+ // A page a path-specific guard covers (a non-root middleware.ts, a config
1324
+ // middleware matcher naming the path) is left out, as core's server does.
1325
+ const guard = {
1326
+ config: { middleware: farmConfigMiddleware },
1327
+ middlewareRoutes: Object.keys(middlewares)
1328
+ .map((filePath) => ({ path: middlewarePathToRoute(filePath) }))
1329
+ .filter((route) => route.path !== null),
1330
+ };
1331
+ const pages = collectFarmLlmsTxtPages(
1332
+ pageRoutes
1333
+ .map(({ module, segments }) => ({
1334
+ // Dynamic routes have no single URL, so the collector skips them.
1335
+ pattern: '/' + segments
1336
+ .map((part) => (part.isDynamic ? '[' + part.segment + ']' : part.segment))
1337
+ .join('/'),
1338
+ metadata: module && module.metadata,
1339
+ }))
1340
+ .filter((page) => page.pattern.includes('[') || !farmPathGuardCoversPage(guard, page.pattern)),
1341
+ {
1342
+ origin,
1343
+ markdown: farmMarkdownConfig,
1344
+ include: farmLlmsTxtConfig.include,
1345
+ exclude: farmLlmsTxtConfig.exclude,
1346
+ },
1347
+ );
1348
+ const rootLayout = getRouteModules('/page.tsx', layouts, 'layout')[0];
1349
+ return {
1350
+ defaults: createFarmDefaultLlmsTxt({
1351
+ origin,
1352
+ pages,
1353
+ config: farmLlmsTxtConfig,
1354
+ rootMetadata: rootLayout && rootLayout.metadata,
1355
+ }),
1356
+ // Pages are read in-process through the full handler as an anonymous
1357
+ // visitor: a fresh request, so the caller's cookies never shape the file,
1358
+ // and a neutral client address, so an IP allowlist never admits the read.
1359
+ // The body is shared across callers. HEAD reads nothing.
1360
+ markdown: full && request.method.toUpperCase() !== 'HEAD'
1361
+ ? createFarmLlmsMarkdownReader((page) =>
1362
+ handler(page, {
1363
+ waitUntil: context && context.waitUntil,
1364
+ clientAddress: FARM_MARKDOWN_ANONYMOUS_CLIENT_ADDRESS,
1365
+ }),
1366
+ )
1367
+ : async () => null,
1368
+ };
1369
+ }
1370
+
1371
+ async function handleFarmLlmsTxtRequest(request, context) {
1372
+ const { origin, pathname } = new URL(request.url);
1373
+ const kind = pathname === '/llms.txt'
1374
+ ? 'llms'
1375
+ : farmLlmsTxtConfig.full && pathname === '/llms-full.txt' ? 'llms-full' : null;
1376
+ if (!kind) return null;
1377
+ const method = request.method.toUpperCase();
1378
+ if (method !== 'GET' && method !== 'HEAD') {
1379
+ return new Response(null, { status: 405, headers: { Allow: 'GET, HEAD' } });
1380
+ }
1381
+ const llmsContext = createFarmLlmsTxtContext(request, context, kind === 'llms-full');
1382
+ // A page that times out is left out, and that response is neither reused nor cached.
1383
+ let complete = true;
1384
+ const renderFull = (shared) =>
1385
+ renderFarmLlmsFullTxt(llmsContext.defaults, {
1386
+ origin,
1387
+ readMarkdown: llmsContext.markdown,
1388
+ onIncomplete: () => {
1389
+ complete = false;
1390
+ if (shared) shared.incomplete();
1391
+ },
1392
+ });
1393
+ // HEAD reads no pages, so it neither waits for nor fills the shared render.
1394
+ const body = kind === 'llms'
1395
+ ? llmsContext.defaults
1396
+ : method === 'HEAD'
1397
+ ? await renderFull()
1398
+ : await farmLlmsFullRenderer(origin, renderFull, (settled) => {
1399
+ complete = settled;
1400
+ });
1401
+ const response = createFarmMetadataRouteResponse(
1402
+ kind,
1403
+ body,
1404
+ { revalidate: complete ? farmLlmsTxtConfig.revalidate : 0 },
1405
+ { method, request },
1406
+ );
1407
+ if (!complete) response.headers.set('cache-control', 'no-store');
1408
+ return response;
1409
+ }
1410
+
1411
+ `
1412
+ : ""}/**
1413
+ * Serves a page's Markdown mirror (\`/page.md\` or \`Accept: text/markdown\`) by
1414
+ * rendering the page through the normal request path, so middleware and sign-in
1415
+ * gates apply; every other request renders as usual, and HTML pages advertise
1416
+ * their mirror with a Link header.
1417
+ */
1418
+ async function handleFarmPageOrMarkdown(request, context) {
1419
+ if (!farmMarkdownConfig.enabled) return handleFarmRequest(request, context);
1420
+ const markdown = await createMarkdownMirrorResponse({
1421
+ request,
1422
+ config: farmMarkdownConfig,
1423
+ routeExists: (pathname) => Boolean(matchRoute(pathname)),
1424
+ renderPage: (pageRequest) => handleFarmRequest(pageRequest, context),
1425
+ apiServerBasePath: farmApiBasePath,
1426
+ });
1427
+ if (markdown) return markdown;
1428
+ const response = await handleFarmRequest(request, context);
1429
+ return applyMarkdownNegotiationHeaders(response, {
1430
+ config: farmMarkdownConfig,
1431
+ pathname: new URL(request.url).pathname,
1432
+ });
1433
+ }
1434
+
1435
+ // Client navigation addresses a page's RSC payload as '<page>.rsc' ('<dir>/index.rsc' for a
1436
+ // trailing slash), so a prerendered page can be a static HTML file next to a static payload file.
1437
+ // 'Accept: text/x-component' on the page URL keeps working.
1438
+ function farmPayloadPath(pathname) {
1439
+ return pathname.endsWith('/') ? pathname + 'index.rsc' : pathname + '.rsc';
1440
+ }
1441
+
1442
+ function toFarmPayloadRequest(request) {
1443
+ if (request.method !== 'GET' && request.method !== 'HEAD') return request;
1444
+ const url = new URL(request.url);
1445
+ if (!url.pathname.endsWith('.rsc')) return request;
1446
+ if (isFarmAPIPathname(url.pathname, farmApiBasePath) || isFarmAPIPathname(url.pathname)) return request;
1447
+ const page = url.pathname.slice(0, -'.rsc'.length);
1448
+ url.pathname = page.endsWith('/index') ? page.slice(0, -'index'.length) : page;
1449
+ const headers = new Headers(request.headers);
1450
+ headers.set('accept', 'text/x-component');
1451
+ return new Request(url, { method: request.method, headers, signal: request.signal });
1452
+ }
1453
+
1454
+ // The build's prerender pass (Nitro) runs this server with FARM_RSC_PRERENDER set. It seeds one
1455
+ // route that lists the static pages, and each prerendered page queues its payload, both through
1456
+ // Nitro's x-nitro-prerender response header. Production servers never answer either.
1457
+ const FARM_PRERENDER_ROUTES_PATH = '/__farm/rsc-prerender-routes';
1458
+ function isFarmPrerenderRequest(request) {
1459
+ return globalThis.process?.env?.FARM_RSC_PRERENDER === '1' && request.headers.has('x-nitro-prerender');
1460
+ }
1461
+
983
1462
  async function handler(request, context) {
1463
+ const prerendering = isFarmPrerenderRequest(request);
1464
+ if (prerendering && new URL(request.url).pathname === FARM_PRERENDER_ROUTES_PATH) {
1465
+ const pages = await collectFarmStaticPages();
1466
+ return new Response('<!doctype html>', {
1467
+ headers: {
1468
+ 'content-type': 'text/html; charset=utf-8',
1469
+ 'x-nitro-prerender': pages.map(encodeURIComponent).join(','),
1470
+ },
1471
+ });
1472
+ }
1473
+ const pageRequest = toFarmPayloadRequest(request);
1474
+ const response = await handleFarmRequestWithRuntime(pageRequest, context);
1475
+ if (
1476
+ prerendering &&
1477
+ pageRequest === request &&
1478
+ response.status === 200 &&
1479
+ (response.headers.get('content-type') || '').includes('text/html')
1480
+ ) {
1481
+ const headers = new Headers(response.headers);
1482
+ headers.set('x-nitro-prerender', encodeURIComponent(farmPayloadPath(new URL(request.url).pathname)));
1483
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
1484
+ }
1485
+ return ${ctx.mobileClient === "entry" ? "_applyFarmMobileShellClient(request, response, farmMobileShellClient)" : "response"};
1486
+ }
1487
+ ${ctx.mobileClient === "entry"
1488
+ ? `
1489
+ // The mobile client (RFC 0004): the documents a mobile shell asks for (X-Farm-Shell) load its
1490
+ // entry instead of the web one, privately, and every HTML response varies on the header. The
1491
+ // Nitro build fills this in once the client is built; null leaves responses as they are.
1492
+ function readFarmMobileShellClient() {
1493
+ try {
1494
+ return JSON.parse("${FARM_RSC_MOBILE_SHELL_CLIENT_PLACEHOLDER}");
1495
+ } catch {
1496
+ return null;
1497
+ }
1498
+ }
1499
+ const farmMobileShellClient = readFarmMobileShellClient();
1500
+ `
1501
+ : ""}
1502
+
1503
+ async function handleFarmRequestWithRuntime(request, context) {
984
1504
  return _runWithAPIRequestRuntime({
985
1505
  basePath: farmApiBasePath,
986
1506
  dispatch: async (localRequest) =>
987
1507
  (await handleAPIRequest(localRequest)) ?? Response.json({ error: 'Not Found' }, { status: 404 }),
988
1508
  }, () => _runWithCurrentRequest(request, () =>
989
- _runWithAfterRequest(request, () => handleFarmRequest(request, context), context)
1509
+ _runWithAfterRequest(request, () => handleFarmPageOrMarkdown(request, context), context)
990
1510
  ));
991
1511
  }
992
1512