@farm.js/plugin 0.1.60 → 0.1.61
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/middleware/index.d.ts +1 -8
- package/dist/middleware/index.d.ts.map +1 -1
- package/dist/middleware/index.js +10 -16
- package/dist/middleware/matching.d.ts +2 -4
- package/dist/middleware/matching.d.ts.map +1 -1
- package/dist/middleware/matching.js +47 -7
- package/dist/rsc/entries/client.d.ts.map +1 -1
- package/dist/rsc/entries/client.js +15 -85
- package/dist/rsc/entries/rsc.d.ts.map +1 -1
- package/dist/rsc/entries/rsc.js +45 -563
- package/dist/rsc/entries/ssr.d.ts.map +1 -1
- package/dist/rsc/entries/ssr.js +6 -7
- package/dist/rsc/index.d.ts +3 -38
- package/dist/rsc/index.d.ts.map +1 -1
- package/dist/rsc/index.js +292 -279
- package/dist/rsc/middleware-config-module.d.ts +0 -3
- package/dist/rsc/middleware-config-module.d.ts.map +1 -1
- package/dist/rsc/middleware-config-module.js +28 -41
- package/dist/rsc/nitro-build.d.ts.map +1 -1
- package/dist/rsc/nitro-build.js +81 -268
- package/dist/rsc/server-fn-transform.d.ts +5 -1
- package/dist/rsc/server-fn-transform.d.ts.map +1 -1
- package/dist/rsc/server-fn-transform.js +338 -3
- package/dist/rsc/types.d.ts +0 -39
- package/dist/rsc/types.d.ts.map +1 -1
- package/dist/rsc/vite-plugin-nitro.d.ts +0 -2
- package/dist/rsc/vite-plugin-nitro.d.ts.map +1 -1
- package/dist/rsc/vite-plugin-nitro.js +2 -12
- package/package.json +3 -3
- package/dist/rsc/client-sourcemaps.d.ts +0 -13
- package/dist/rsc/client-sourcemaps.d.ts.map +0 -1
- package/dist/rsc/client-sourcemaps.js +0 -52
- package/dist/rsc/document-layouts.d.ts +0 -16
- package/dist/rsc/document-layouts.d.ts.map +0 -1
- package/dist/rsc/document-layouts.js +0 -82
- package/dist/rsc/mobile-client.d.ts +0 -67
- package/dist/rsc/mobile-client.d.ts.map +0 -1
- package/dist/rsc/mobile-client.js +0 -148
package/dist/rsc/entries/rsc.js
CHANGED
|
@@ -1,11 +1,3 @@
|
|
|
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
|
-
}
|
|
9
1
|
/**
|
|
10
2
|
* Generates the terminal middleware-result handling shared by the RSC entry
|
|
11
3
|
* and its executable contract tests.
|
|
@@ -54,17 +46,11 @@ export function generateRscEntry(ctx) {
|
|
|
54
46
|
const middlewareConfigImports = (ctx.middlewareConfigPaths ?? [])
|
|
55
47
|
.map((configPath, index) => `import * as FarmMiddlewareConfigModule${index} from ${JSON.stringify(configPath.replace(/\\/g, "/"))};`)
|
|
56
48
|
.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;
|
|
61
49
|
const middlewareConfigValues = (ctx.middlewareConfigPaths ?? []).map((_configPath, index) => `(FarmMiddlewareConfigModule${index}.default || FarmMiddlewareConfigModule${index})`);
|
|
62
50
|
let code = `
|
|
63
51
|
import React from 'react';
|
|
64
52
|
import ServerErrorFallback from '/.farm/rsc-entries/error-fallback.tsx';
|
|
65
53
|
${middlewareConfigImports}
|
|
66
|
-
${mcpConfigImports}
|
|
67
|
-
${mcpSource ? `${mcpSource.importSource}\nimport { mergePluginAPIRoutes } from '@farm.js/core/api/runtime';` : ""}
|
|
68
54
|
import { registerAPIRouteShape } from '@farm.js/core/api/runtime';
|
|
69
55
|
import {
|
|
70
56
|
renderToReadableStream,
|
|
@@ -90,8 +76,7 @@ import {
|
|
|
90
76
|
applyProductionMiddlewareHeaders,
|
|
91
77
|
createProductionMiddlewareRunner,
|
|
92
78
|
} from '@farm.js/core/middleware';
|
|
93
|
-
import {
|
|
94
|
-
${ctx.mobileClient === "entry" ? "import { _applyFarmMobileShellClient } from '@farm.js/core/internal/production-runtime';\n" : ""}import {
|
|
79
|
+
import {
|
|
95
80
|
getAllowedAPIRouteMethods,
|
|
96
81
|
invokeAPIRouteEndpoint,
|
|
97
82
|
isFarmAPIPathname,
|
|
@@ -106,69 +91,10 @@ import {
|
|
|
106
91
|
compareRouteSpecificity,
|
|
107
92
|
getRoutePatternSpecificity,
|
|
108
93
|
} 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';
|
|
127
94
|
|
|
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
|
-
: ""}
|
|
152
95
|
const farmDeploymentId = ${JSON.stringify(ctx.deploymentId)};
|
|
153
96
|
const farmApiBasePath = ${JSON.stringify(ctx.apiBasePath ?? "/api")};
|
|
154
|
-
const farmMarkdownConfig = ${JSON.stringify(ctx.markdown ?? { enabled: false, expose: [], cache: false, includeMetadata: true })};
|
|
155
97
|
`;
|
|
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
|
-
}
|
|
172
98
|
if (ctx.actionsEnabled) {
|
|
173
99
|
code += `import {
|
|
174
100
|
createServerActionRequestErrorResponse,
|
|
@@ -180,56 +106,6 @@ const farmLlmsFullRenderer = createFarmLlmsFullRenderer({ revalidate: farmLlmsTx
|
|
|
180
106
|
} from '@farm.js/core/server-action-security';
|
|
181
107
|
|
|
182
108
|
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
|
-
}
|
|
233
109
|
`;
|
|
234
110
|
}
|
|
235
111
|
// Auto-discover pages, layouts, and middleware using Vite's glob import
|
|
@@ -256,18 +132,14 @@ function applyActionResponseHeaders(headers, request) {
|
|
|
256
132
|
headers.set('cache-control', 'no-store');
|
|
257
133
|
headers.set('x-content-type-options', 'nosniff');
|
|
258
134
|
}
|
|
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');
|
|
263
135
|
}
|
|
264
136
|
|
|
265
137
|
// Auto-discover all route modules. Every glob remains a literal so Vite can analyze it.
|
|
266
138
|
${routeSourceRoots
|
|
267
|
-
.map((root, index) => `const pages${index} = ${
|
|
268
|
-
const layouts${index} = ${
|
|
269
|
-
const loadings${index} = ${
|
|
270
|
-
const errors${index} = ${
|
|
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 });
|
|
271
143
|
const middlewares${index} = import.meta.glob(${JSON.stringify(`${root.glob}/**/middleware.{tsx,jsx,ts,js}`)}, { eager: true });
|
|
272
144
|
const apiRouteModules${index} = import.meta.glob(${JSON.stringify(`${root.glob}/api/**/route.{tsx,jsx,ts,js}`)}, { eager: true });
|
|
273
145
|
const routeDefinitionModules${index} = import.meta.glob(${JSON.stringify(root.sourceGlob === root.glob
|
|
@@ -320,14 +192,6 @@ const pages = mergeRouteModules([${routeRoots
|
|
|
320
192
|
const layouts = mergeRouteModules([${routeRoots
|
|
321
193
|
.map((root, index) => `{ base: ${JSON.stringify(root.base)}, modules: layouts${index} }`)
|
|
322
194
|
.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
|
-
|
|
331
195
|
const loadings = mergeRouteModules([${routeRoots
|
|
332
196
|
.map((root, index) => `{ base: ${JSON.stringify(root.base)}, modules: loadings${index} }`)
|
|
333
197
|
.join(", ")}]);
|
|
@@ -419,42 +283,7 @@ function registerApiRouteSources(fileModules, definitionModules, sourceCount) {
|
|
|
419
283
|
}
|
|
420
284
|
|
|
421
285
|
registerApiRouteSources(apiRouteModules, routeDefinitionModules, ${routeSourceRoots.length});
|
|
422
|
-
|
|
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
|
-
: ""}
|
|
286
|
+
|
|
458
287
|
async function handleAPIRequest(request) {
|
|
459
288
|
const url = new URL(request.url);
|
|
460
289
|
const match = matchAPIRouteAtBasePath(apiRouteMap, url.pathname, farmApiBasePath);
|
|
@@ -502,20 +331,9 @@ const farmMiddlewareRunner = createProductionMiddlewareRunner({
|
|
|
502
331
|
.filter((entry) => entry.path !== null)
|
|
503
332
|
// Root first, as core runs them: a nested guard can rely on what its
|
|
504
333
|
// parent middleware set, and glob order is alphabetical, not by depth.
|
|
505
|
-
|
|
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
|
-
),
|
|
334
|
+
.sort((left, right) => middlewareRouteDepth(left.path) - middlewareRouteDepth(right.path)),
|
|
514
335
|
i18n: ${JSON.stringify(ctx.i18n) ?? "undefined"},
|
|
515
336
|
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,
|
|
519
337
|
});
|
|
520
338
|
|
|
521
339
|
debug('Discovered pages:', Object.keys(pages));
|
|
@@ -528,37 +346,22 @@ debug('Discovered API routes:', Array.from(apiRouteMap.keys()));
|
|
|
528
346
|
/**
|
|
529
347
|
* Convert an app-relative middleware file path to the route it guards, with the
|
|
530
348
|
* same rules as core's middleware discovery: a route group such as
|
|
531
|
-
* '(protected)'
|
|
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
|
|
349
|
+
* '(protected)' adds no URL segment, and a '_private' or dot-prefixed folder
|
|
534
350
|
* holds no routes, so its middleware never runs (null).
|
|
535
351
|
* e.g., '/middleware.ts' -> '/'
|
|
536
352
|
* 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'
|
|
539
353
|
*/
|
|
540
354
|
function middlewarePathToRoute(filePath) {
|
|
541
355
|
const segments = filePath
|
|
542
356
|
.replace(/\\/middleware\\.[tj]sx?$/, '')
|
|
543
357
|
.split('/')
|
|
544
358
|
.filter(Boolean);
|
|
545
|
-
if (segments.some((segment) => segment.startsWith('.'))) {
|
|
359
|
+
if (segments.some((segment) => segment.startsWith('_') || segment.startsWith('.'))) {
|
|
546
360
|
return null;
|
|
547
361
|
}
|
|
548
|
-
const routeSegments =
|
|
549
|
-
|
|
550
|
-
|
|
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
|
-
}
|
|
362
|
+
const routeSegments = segments.filter(
|
|
363
|
+
(segment) => !(segment.startsWith('(') && segment.endsWith(')')),
|
|
364
|
+
);
|
|
562
365
|
return routeSegments.length === 0 ? '/' : '/' + routeSegments.join('/');
|
|
563
366
|
}
|
|
564
367
|
|
|
@@ -617,12 +420,7 @@ const RouteErrorBoundary = React.Component
|
|
|
617
420
|
|
|
618
421
|
// Parse and rank once per entry initialization, not on every request. Use the
|
|
619
422
|
// same validation, decoding and specificity rules as Farm's ordinary router.
|
|
620
|
-
|
|
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]) => ({
|
|
423
|
+
const pageRoutes = Object.entries(pages).map(([filePath, module]) => ({
|
|
626
424
|
filePath,
|
|
627
425
|
module,
|
|
628
426
|
segments: parseRoutePath(filePath).segments,
|
|
@@ -645,7 +443,7 @@ function matchRoute(pathname) {
|
|
|
645
443
|
Page: module.default,
|
|
646
444
|
pattern: filePath,
|
|
647
445
|
params: match.params,
|
|
648
|
-
module,
|
|
446
|
+
pageMetadata: module.metadata,
|
|
649
447
|
};
|
|
650
448
|
}
|
|
651
449
|
}
|
|
@@ -654,77 +452,13 @@ function matchRoute(pathname) {
|
|
|
654
452
|
return null;
|
|
655
453
|
}
|
|
656
454
|
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
const
|
|
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 });
|
|
722
|
-
}
|
|
723
|
-
metadata = mergeMetadata(metadata, pageModule?.metadata);
|
|
724
|
-
if (typeof pageModule?.generateMetadata === 'function') {
|
|
725
|
-
metadata = mergeMetadata(metadata, await pageModule.generateMetadata(pageProps));
|
|
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;
|
|
726
460
|
}
|
|
727
|
-
return
|
|
461
|
+
return metadata;
|
|
728
462
|
}
|
|
729
463
|
|
|
730
464
|
/**
|
|
@@ -765,14 +499,6 @@ function getLayoutModules(pageFilePath) {
|
|
|
765
499
|
return getRouteModules(pageFilePath, layouts, 'layout');
|
|
766
500
|
}
|
|
767
501
|
|
|
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
|
-
|
|
776
502
|
function getMatchingBoundary(pageFilePath, modules, kind) {
|
|
777
503
|
// Before page selection (for example, middleware failure), only the root
|
|
778
504
|
// boundary applies. Do not guess a route from a partially processed URL.
|
|
@@ -783,19 +509,8 @@ function getMatchingBoundary(pageFilePath, modules, kind) {
|
|
|
783
509
|
/**
|
|
784
510
|
* Main request handler - entry point for both dev and production (Nitro).
|
|
785
511
|
* 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.
|
|
791
512
|
*/
|
|
792
513
|
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) {
|
|
799
514
|
let url = new URL(request.url);
|
|
800
515
|
let matchedPage = null;
|
|
801
516
|
let errorData = new Map();
|
|
@@ -835,7 +550,6 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
835
550
|
// Execute middleware first
|
|
836
551
|
const middlewareResult = await executeMiddleware(request, context);
|
|
837
552
|
${generateRscMiddlewareResultHandling()}
|
|
838
|
-
if (middlewareResult.guarded) farmCacheGuard.guarded = true;
|
|
839
553
|
|
|
840
554
|
request = middlewareResult.request;
|
|
841
555
|
url = new URL(request.url);
|
|
@@ -858,21 +572,11 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
858
572
|
_runWithMiddlewareContext(middlewareContext, async () => {
|
|
859
573
|
const glob = '';
|
|
860
574
|
|
|
861
|
-
if (farmImageHandler && url.pathname === farmImagePath) {
|
|
862
|
-
const imageResponse = await farmImageHandler(request);
|
|
863
|
-
if (imageResponse) return imageResponse;
|
|
864
|
-
}
|
|
865
|
-
|
|
866
575
|
const apiResponse = await handleAPIRequest(request.clone());
|
|
867
576
|
if (apiResponse) {
|
|
868
577
|
return applyProductionMiddlewareHeaders(apiResponse, middlewareHeaders);
|
|
869
578
|
}
|
|
870
|
-
|
|
871
|
-
? `// agent.llmsTxt: answered after middleware, so its redirects and headers apply.
|
|
872
|
-
const llmsResponse = await handleFarmLlmsTxtRequest(request, context);
|
|
873
|
-
if (llmsResponse) return applyProductionMiddlewareHeaders(llmsResponse, middlewareHeaders);
|
|
874
|
-
`
|
|
875
|
-
: ""}if (isFarmAPIPathname(url.pathname, farmApiBasePath) || isFarmAPIPathname(url.pathname)) {
|
|
579
|
+
if (isFarmAPIPathname(url.pathname, farmApiBasePath) || isFarmAPIPathname(url.pathname)) {
|
|
876
580
|
return applyProductionMiddlewareHeaders(new Response(
|
|
877
581
|
JSON.stringify({ error: 'API route not found', pathname: url.pathname }),
|
|
878
582
|
{ status: 404, headers: { 'Content-Type': 'application/json' } },
|
|
@@ -992,13 +696,12 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
992
696
|
return new Response(null, { status: 499, headers: { 'Cache-Control': 'no-store' } });
|
|
993
697
|
}
|
|
994
698
|
// No client router here, so the redirect has to be a real HTTP
|
|
995
|
-
// redirect the browser follows on its own.
|
|
996
|
-
// answers: a 307 or 308 would post the form again to the target.
|
|
699
|
+
// redirect the browser follows on its own.
|
|
997
700
|
const formRedirect = getFarmRedirectError(e);
|
|
998
701
|
if (formRedirect) {
|
|
999
702
|
debug('Form action redirected:', formRedirect.url);
|
|
1000
703
|
return new Response(null, {
|
|
1001
|
-
status:
|
|
704
|
+
status: formRedirect.status,
|
|
1002
705
|
headers: { location: formRedirect.url, 'Cache-Control': 'no-store' },
|
|
1003
706
|
});
|
|
1004
707
|
}
|
|
@@ -1028,26 +731,15 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1028
731
|
|
|
1029
732
|
if (!matched) {
|
|
1030
733
|
debug('404 - No route found for:', url.pathname);
|
|
1031
|
-
// Agents that read in Markdown get a Markdown 404, as in core's server.
|
|
1032
|
-
if (farmMarkdownConfig.enabled && farmRequestWantsMarkdown(url.pathname, request.headers.get('accept'))) {
|
|
1033
|
-
return new Response(createFarmMarkdownErrorBody(404, url.pathname), {
|
|
1034
|
-
status: 404,
|
|
1035
|
-
headers: {
|
|
1036
|
-
'Content-Type': FARM_MARKDOWN_CONTENT_TYPE,
|
|
1037
|
-
'X-Farm-Markdown-Error': '404',
|
|
1038
|
-
'Cache-Control': 'no-store',
|
|
1039
|
-
},
|
|
1040
|
-
});
|
|
1041
|
-
}
|
|
1042
734
|
return new Response('Not Found', { status: 404 });
|
|
1043
735
|
}
|
|
1044
736
|
|
|
1045
|
-
const { Page, pattern, params,
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
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
|
+
);
|
|
1051
743
|
const configuredRoutesDir = ${ctx.routesDir === undefined ? "undefined" : JSON.stringify(ctx.routesDir)};
|
|
1052
744
|
const routesDir = configuredRoutesDir === undefined ? 'app' : configuredRoutesDir.trim();
|
|
1053
745
|
const routesPath = routesDir ? '/' + routesDir : '';
|
|
@@ -1060,14 +752,6 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1060
752
|
|
|
1061
753
|
// Page props passed to components (includes middleware shared data)
|
|
1062
754
|
const pageProps = { params, searchParams, middlewareData };
|
|
1063
|
-
const metadata = await resolveFarmRouteMetadata(LayoutModules, pageModule, pageProps);
|
|
1064
|
-
const renderedHead = renderMetadataHead(metadata, { pathname: url.pathname });
|
|
1065
|
-
// Injected into <head> by the SSR entry; React renders only the charset.
|
|
1066
|
-
const metadataHead =
|
|
1067
|
-
(renderedHead.hasExplicitTitle ? '<title>' + renderedHead.title + '</title>' : '') +
|
|
1068
|
-
renderedHead.viewport +
|
|
1069
|
-
renderedHead.tags;
|
|
1070
|
-
const metadataTitle = resolveMetadataTitle(metadata.title);
|
|
1071
755
|
|
|
1072
756
|
debug('Rendering page:', pattern, 'with props:', pageProps);
|
|
1073
757
|
|
|
@@ -1113,36 +797,26 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1113
797
|
}
|
|
1114
798
|
}
|
|
1115
799
|
|
|
1116
|
-
//
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
LayoutModules.length > 0 && farmDocumentLayoutModules.has(LayoutModules[0]);
|
|
1120
|
-
// Otherwise a single wrapper, so #root has exactly one child (avoids a duplicate block in the DOM).
|
|
1121
|
-
const rootInner = ownsDocument
|
|
1122
|
-
? h(
|
|
1123
|
-
React.Fragment,
|
|
1124
|
-
null,
|
|
1125
|
-
h('meta', { charSet: 'utf-8' }),
|
|
1126
|
-
layoutContent,
|
|
1127
|
-
)
|
|
1128
|
-
: h('div', { 'data-farm-root': 'true' }, layoutContent);
|
|
1129
|
-
// Build the full page. root = full document (for SSR). rootContent = what the browser hydrates.
|
|
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).
|
|
1130
803
|
const payload = {
|
|
1131
|
-
|
|
1132
|
-
root: ownsDocument ? rootInner : h('html', null,
|
|
804
|
+
root: h('html', null,
|
|
1133
805
|
h('head', null,
|
|
1134
806
|
h('meta', { charSet: 'utf-8' }),
|
|
1135
|
-
|
|
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
|
|
1136
811
|
),
|
|
1137
812
|
h('body', null,
|
|
1138
813
|
h('div', { id: 'root' }, rootInner)
|
|
1139
814
|
)
|
|
1140
815
|
),
|
|
1141
816
|
rootContent: rootInner,
|
|
1142
|
-
metadataHead,
|
|
1143
817
|
metadata: {
|
|
1144
|
-
title:
|
|
1145
|
-
description: typeof metadata
|
|
818
|
+
title: typeof metadata?.title === 'string' ? metadata.title : undefined,
|
|
819
|
+
description: typeof metadata?.description === 'string' ? metadata.description : undefined,
|
|
1146
820
|
},
|
|
1147
821
|
`;
|
|
1148
822
|
// Include action results in payload if actions are enabled
|
|
@@ -1161,7 +835,7 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1161
835
|
// Full RSC mode with streaming
|
|
1162
836
|
debug('Using RSC streaming mode');
|
|
1163
837
|
|
|
1164
|
-
const rscStream = renderToReadableStream(payload
|
|
838
|
+
const rscStream = renderToReadableStream(payload${ctx.actionsEnabled ? ", { temporaryReferences }" : ""});
|
|
1165
839
|
|
|
1166
840
|
if (acceptHeader.includes('text/x-component')) {
|
|
1167
841
|
debug('Returning RSC stream for client navigation');
|
|
@@ -1200,8 +874,8 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1200
874
|
h('meta', { charSet: 'utf-8' }),
|
|
1201
875
|
h('meta', { name: 'viewport', content: 'width=device-width, initial-scale=1' }),
|
|
1202
876
|
h('link', { rel: 'icon', href: 'data:,' }),
|
|
1203
|
-
|
|
1204
|
-
|
|
877
|
+
metadata?.title ? h('title', null, metadata.title) : null,
|
|
878
|
+
metadata?.description ? h('meta', { name: 'description', content: metadata.description }) : null,
|
|
1205
879
|
h('link', { rel: 'stylesheet', href: globalsCssPath, as: 'style', precedence: 'default' }),
|
|
1206
880
|
h('script', { type: 'module', src: '/@vite/client' })
|
|
1207
881
|
),
|
|
@@ -1220,11 +894,7 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1220
894
|
)
|
|
1221
895
|
);
|
|
1222
896
|
} catch (err) {
|
|
1223
|
-
|
|
1224
|
-
? `// A file that failed to load: show the dev error page, not error.tsx.
|
|
1225
|
-
if ([...farmRouteLoadErrors.values()].includes(err)) throw err;
|
|
1226
|
-
`
|
|
1227
|
-
: ""}const redirect = getFarmRedirectError(err);
|
|
897
|
+
const redirect = getFarmRedirectError(err);
|
|
1228
898
|
if (redirect) return new Response(null, { status: redirect.status, headers: { location: redirect.url, 'cache-control': 'no-store' } });
|
|
1229
899
|
if (isFarmNotFoundError(err)) return new Response('Not Found', { status: 404, headers: { 'cache-control': 'no-store' } });
|
|
1230
900
|
console.error('[RSC] Handler error:', err);
|
|
@@ -1273,7 +943,7 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1273
943
|
rootContent: rootInner,
|
|
1274
944
|
metadata: { title: 'Error' },
|
|
1275
945
|
};
|
|
1276
|
-
const rscStream = renderToReadableStream(payload
|
|
946
|
+
const rscStream = renderToReadableStream(payload);
|
|
1277
947
|
const headers = new Headers(errorHeaders);
|
|
1278
948
|
headers.set('cache-control', 'private, no-store');
|
|
1279
949
|
headers.set('x-content-type-options', 'nosniff');
|
|
@@ -1310,201 +980,13 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1310
980
|
}
|
|
1311
981
|
}
|
|
1312
982
|
|
|
1313
|
-
${ctx.llmsTxt?.enabled
|
|
1314
|
-
? `/**
|
|
1315
|
-
* agent.llmsTxt, built the same way as core's production server: /llms.txt
|
|
1316
|
-
* lists the app's static pages and links to their Markdown mirrors, and
|
|
1317
|
-
* /llms-full.txt inlines each mirror.
|
|
1318
|
-
*/
|
|
1319
|
-
function createFarmLlmsTxtContext(request, context, full) {
|
|
1320
|
-
const origin = new URL(request.url).origin;
|
|
1321
|
-
// A page a path-specific guard covers (a non-root middleware.ts, a config
|
|
1322
|
-
// middleware matcher naming the path) is left out, as core's server does.
|
|
1323
|
-
const guard = {
|
|
1324
|
-
config: { middleware: farmConfigMiddleware },
|
|
1325
|
-
middlewareRoutes: Object.keys(middlewares)
|
|
1326
|
-
.map((filePath) => ({ path: middlewarePathToRoute(filePath) }))
|
|
1327
|
-
.filter((route) => route.path !== null),
|
|
1328
|
-
};
|
|
1329
|
-
const pages = collectFarmLlmsTxtPages(
|
|
1330
|
-
pageRoutes
|
|
1331
|
-
.map(({ module, segments }) => ({
|
|
1332
|
-
// Dynamic routes have no single URL, so the collector skips them.
|
|
1333
|
-
pattern: '/' + segments
|
|
1334
|
-
.map((part) => (part.isDynamic ? '[' + part.segment + ']' : part.segment))
|
|
1335
|
-
.join('/'),
|
|
1336
|
-
metadata: module && module.metadata,
|
|
1337
|
-
}))
|
|
1338
|
-
.filter((page) => page.pattern.includes('[') || !farmPathGuardCoversPage(guard, page.pattern)),
|
|
1339
|
-
{
|
|
1340
|
-
origin,
|
|
1341
|
-
markdown: farmMarkdownConfig,
|
|
1342
|
-
include: farmLlmsTxtConfig.include,
|
|
1343
|
-
exclude: farmLlmsTxtConfig.exclude,
|
|
1344
|
-
},
|
|
1345
|
-
);
|
|
1346
|
-
const rootLayout = getRouteModules('/page.tsx', layouts, 'layout')[0];
|
|
1347
|
-
return {
|
|
1348
|
-
defaults: createFarmDefaultLlmsTxt({
|
|
1349
|
-
origin,
|
|
1350
|
-
pages,
|
|
1351
|
-
config: farmLlmsTxtConfig,
|
|
1352
|
-
rootMetadata: rootLayout && rootLayout.metadata,
|
|
1353
|
-
}),
|
|
1354
|
-
// Pages are read in-process through the full handler as an anonymous
|
|
1355
|
-
// visitor: a fresh request, so the caller's cookies never shape the file,
|
|
1356
|
-
// and a neutral client address, so an IP allowlist never admits the read.
|
|
1357
|
-
// The body is shared across callers. HEAD reads nothing.
|
|
1358
|
-
markdown: full && request.method.toUpperCase() !== 'HEAD'
|
|
1359
|
-
? createFarmLlmsMarkdownReader((page) =>
|
|
1360
|
-
handler(page, {
|
|
1361
|
-
waitUntil: context && context.waitUntil,
|
|
1362
|
-
clientAddress: FARM_MARKDOWN_ANONYMOUS_CLIENT_ADDRESS,
|
|
1363
|
-
}),
|
|
1364
|
-
)
|
|
1365
|
-
: async () => null,
|
|
1366
|
-
};
|
|
1367
|
-
}
|
|
1368
|
-
|
|
1369
|
-
async function handleFarmLlmsTxtRequest(request, context) {
|
|
1370
|
-
const { origin, pathname } = new URL(request.url);
|
|
1371
|
-
const kind = pathname === '/llms.txt'
|
|
1372
|
-
? 'llms'
|
|
1373
|
-
: farmLlmsTxtConfig.full && pathname === '/llms-full.txt' ? 'llms-full' : null;
|
|
1374
|
-
if (!kind) return null;
|
|
1375
|
-
const method = request.method.toUpperCase();
|
|
1376
|
-
if (method !== 'GET' && method !== 'HEAD') {
|
|
1377
|
-
return new Response(null, { status: 405, headers: { Allow: 'GET, HEAD' } });
|
|
1378
|
-
}
|
|
1379
|
-
const llmsContext = createFarmLlmsTxtContext(request, context, kind === 'llms-full');
|
|
1380
|
-
// A page that times out is left out, and that response is neither reused nor cached.
|
|
1381
|
-
let complete = true;
|
|
1382
|
-
const renderFull = (shared) =>
|
|
1383
|
-
renderFarmLlmsFullTxt(llmsContext.defaults, {
|
|
1384
|
-
origin,
|
|
1385
|
-
readMarkdown: llmsContext.markdown,
|
|
1386
|
-
onIncomplete: () => {
|
|
1387
|
-
complete = false;
|
|
1388
|
-
if (shared) shared.incomplete();
|
|
1389
|
-
},
|
|
1390
|
-
});
|
|
1391
|
-
// HEAD reads no pages, so it neither waits for nor fills the shared render.
|
|
1392
|
-
const body = kind === 'llms'
|
|
1393
|
-
? llmsContext.defaults
|
|
1394
|
-
: method === 'HEAD'
|
|
1395
|
-
? await renderFull()
|
|
1396
|
-
: await farmLlmsFullRenderer(origin, renderFull, (settled) => {
|
|
1397
|
-
complete = settled;
|
|
1398
|
-
});
|
|
1399
|
-
const response = createFarmMetadataRouteResponse(
|
|
1400
|
-
kind,
|
|
1401
|
-
body,
|
|
1402
|
-
{ revalidate: complete ? farmLlmsTxtConfig.revalidate : 0 },
|
|
1403
|
-
{ method, request },
|
|
1404
|
-
);
|
|
1405
|
-
if (!complete) response.headers.set('cache-control', 'no-store');
|
|
1406
|
-
return response;
|
|
1407
|
-
}
|
|
1408
|
-
|
|
1409
|
-
`
|
|
1410
|
-
: ""}/**
|
|
1411
|
-
* Serves a page's Markdown mirror (\`/page.md\` or \`Accept: text/markdown\`) by
|
|
1412
|
-
* rendering the page through the normal request path, so middleware and sign-in
|
|
1413
|
-
* gates apply; every other request renders as usual, and HTML pages advertise
|
|
1414
|
-
* their mirror with a Link header.
|
|
1415
|
-
*/
|
|
1416
|
-
async function handleFarmPageOrMarkdown(request, context) {
|
|
1417
|
-
if (!farmMarkdownConfig.enabled) return handleFarmRequest(request, context);
|
|
1418
|
-
const markdown = await createMarkdownMirrorResponse({
|
|
1419
|
-
request,
|
|
1420
|
-
config: farmMarkdownConfig,
|
|
1421
|
-
routeExists: (pathname) => Boolean(matchRoute(pathname)),
|
|
1422
|
-
renderPage: (pageRequest) => handleFarmRequest(pageRequest, context),
|
|
1423
|
-
apiServerBasePath: farmApiBasePath,
|
|
1424
|
-
});
|
|
1425
|
-
if (markdown) return markdown;
|
|
1426
|
-
const response = await handleFarmRequest(request, context);
|
|
1427
|
-
return applyMarkdownNegotiationHeaders(response, {
|
|
1428
|
-
config: farmMarkdownConfig,
|
|
1429
|
-
pathname: new URL(request.url).pathname,
|
|
1430
|
-
});
|
|
1431
|
-
}
|
|
1432
|
-
|
|
1433
|
-
// Client navigation addresses a page's RSC payload as '<page>.rsc' ('<dir>/index.rsc' for a
|
|
1434
|
-
// trailing slash), so a prerendered page can be a static HTML file next to a static payload file.
|
|
1435
|
-
// 'Accept: text/x-component' on the page URL keeps working.
|
|
1436
|
-
function farmPayloadPath(pathname) {
|
|
1437
|
-
return pathname.endsWith('/') ? pathname + 'index.rsc' : pathname + '.rsc';
|
|
1438
|
-
}
|
|
1439
|
-
|
|
1440
|
-
function toFarmPayloadRequest(request) {
|
|
1441
|
-
if (request.method !== 'GET' && request.method !== 'HEAD') return request;
|
|
1442
|
-
const url = new URL(request.url);
|
|
1443
|
-
if (!url.pathname.endsWith('.rsc')) return request;
|
|
1444
|
-
if (isFarmAPIPathname(url.pathname, farmApiBasePath) || isFarmAPIPathname(url.pathname)) return request;
|
|
1445
|
-
const page = url.pathname.slice(0, -'.rsc'.length);
|
|
1446
|
-
url.pathname = page.endsWith('/index') ? page.slice(0, -'index'.length) : page;
|
|
1447
|
-
const headers = new Headers(request.headers);
|
|
1448
|
-
headers.set('accept', 'text/x-component');
|
|
1449
|
-
return new Request(url, { method: request.method, headers, signal: request.signal });
|
|
1450
|
-
}
|
|
1451
|
-
|
|
1452
|
-
// The build's prerender pass (Nitro) runs this server with FARM_RSC_PRERENDER set. It seeds one
|
|
1453
|
-
// route that lists the static pages, and each prerendered page queues its payload, both through
|
|
1454
|
-
// Nitro's x-nitro-prerender response header. Production servers never answer either.
|
|
1455
|
-
const FARM_PRERENDER_ROUTES_PATH = '/__farm/rsc-prerender-routes';
|
|
1456
|
-
function isFarmPrerenderRequest(request) {
|
|
1457
|
-
return globalThis.process?.env?.FARM_RSC_PRERENDER === '1' && request.headers.has('x-nitro-prerender');
|
|
1458
|
-
}
|
|
1459
|
-
|
|
1460
983
|
async function handler(request, context) {
|
|
1461
|
-
const prerendering = isFarmPrerenderRequest(request);
|
|
1462
|
-
if (prerendering && new URL(request.url).pathname === FARM_PRERENDER_ROUTES_PATH) {
|
|
1463
|
-
const pages = await collectFarmStaticPages();
|
|
1464
|
-
return new Response('<!doctype html>', {
|
|
1465
|
-
headers: {
|
|
1466
|
-
'content-type': 'text/html; charset=utf-8',
|
|
1467
|
-
'x-nitro-prerender': pages.map(encodeURIComponent).join(','),
|
|
1468
|
-
},
|
|
1469
|
-
});
|
|
1470
|
-
}
|
|
1471
|
-
const pageRequest = toFarmPayloadRequest(request);
|
|
1472
|
-
const response = await handleFarmRequestWithRuntime(pageRequest, context);
|
|
1473
|
-
if (
|
|
1474
|
-
prerendering &&
|
|
1475
|
-
pageRequest === request &&
|
|
1476
|
-
response.status === 200 &&
|
|
1477
|
-
(response.headers.get('content-type') || '').includes('text/html')
|
|
1478
|
-
) {
|
|
1479
|
-
const headers = new Headers(response.headers);
|
|
1480
|
-
headers.set('x-nitro-prerender', encodeURIComponent(farmPayloadPath(new URL(request.url).pathname)));
|
|
1481
|
-
return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
|
|
1482
|
-
}
|
|
1483
|
-
return ${ctx.mobileClient === "entry" ? "_applyFarmMobileShellClient(request, response, farmMobileShellClient)" : "response"};
|
|
1484
|
-
}
|
|
1485
|
-
${ctx.mobileClient === "entry"
|
|
1486
|
-
? `
|
|
1487
|
-
// The mobile client (RFC 0004): the documents a mobile shell asks for (X-Farm-Shell) load its
|
|
1488
|
-
// entry instead of the web one, privately, and every HTML response varies on the header. The
|
|
1489
|
-
// Nitro build fills this in once the client is built; null leaves responses as they are.
|
|
1490
|
-
function readFarmMobileShellClient() {
|
|
1491
|
-
try {
|
|
1492
|
-
return JSON.parse("${FARM_RSC_MOBILE_SHELL_CLIENT_PLACEHOLDER}");
|
|
1493
|
-
} catch {
|
|
1494
|
-
return null;
|
|
1495
|
-
}
|
|
1496
|
-
}
|
|
1497
|
-
const farmMobileShellClient = readFarmMobileShellClient();
|
|
1498
|
-
`
|
|
1499
|
-
: ""}
|
|
1500
|
-
|
|
1501
|
-
async function handleFarmRequestWithRuntime(request, context) {
|
|
1502
984
|
return _runWithAPIRequestRuntime({
|
|
1503
985
|
basePath: farmApiBasePath,
|
|
1504
986
|
dispatch: async (localRequest) =>
|
|
1505
987
|
(await handleAPIRequest(localRequest)) ?? Response.json({ error: 'Not Found' }, { status: 404 }),
|
|
1506
988
|
}, () => _runWithCurrentRequest(request, () =>
|
|
1507
|
-
_runWithAfterRequest(request, () =>
|
|
989
|
+
_runWithAfterRequest(request, () => handleFarmRequest(request, context), context)
|
|
1508
990
|
));
|
|
1509
991
|
}
|
|
1510
992
|
|