@farm.js/plugin 0.1.51-beta.3 → 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.d.ts.map +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 +9 -22
- package/dist/rsc/entries/rsc.d.ts.map +1 -1
- package/dist/rsc/entries/rsc.js +40 -533
- package/dist/rsc/entries/ssr.d.ts.map +1 -1
- package/dist/rsc/entries/ssr.js +6 -7
- package/dist/rsc/index.d.ts +2 -35
- package/dist/rsc/index.d.ts.map +1 -1
- package/dist/rsc/index.js +290 -238
- 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 -259
- 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 -28
- 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/entries/rsc.js
CHANGED
|
@@ -1,10 +1,3 @@
|
|
|
1
|
-
import { createRequire } from "node:module";
|
|
2
|
-
const require_ = createRequire(import.meta.url);
|
|
3
|
-
/** Core's production source for the \`mcp\` plugin, so both servers merge config the same way. */
|
|
4
|
-
function generateMCPPluginSource() {
|
|
5
|
-
const { generateNativeMCPPluginSource } = require_("@farm.js/core/internal/production-runtime");
|
|
6
|
-
return generateNativeMCPPluginSource({ enabled: true });
|
|
7
|
-
}
|
|
8
1
|
/**
|
|
9
2
|
* Generates the terminal middleware-result handling shared by the RSC entry
|
|
10
3
|
* and its executable contract tests.
|
|
@@ -53,17 +46,11 @@ export function generateRscEntry(ctx) {
|
|
|
53
46
|
const middlewareConfigImports = (ctx.middlewareConfigPaths ?? [])
|
|
54
47
|
.map((configPath, index) => `import * as FarmMiddlewareConfigModule${index} from ${JSON.stringify(configPath.replace(/\\/g, "/"))};`)
|
|
55
48
|
.join("\n");
|
|
56
|
-
const mcpConfigImports = (ctx.mcpConfigPaths ?? [])
|
|
57
|
-
.map((configPath, index) => `import * as FarmMCPConfigModule${index} from ${JSON.stringify(configPath.replace(/\\/g, "/"))};`)
|
|
58
|
-
.join("\n");
|
|
59
|
-
const mcpSource = ctx.mcpConfigPaths?.length ? generateMCPPluginSource() : null;
|
|
60
49
|
const middlewareConfigValues = (ctx.middlewareConfigPaths ?? []).map((_configPath, index) => `(FarmMiddlewareConfigModule${index}.default || FarmMiddlewareConfigModule${index})`);
|
|
61
50
|
let code = `
|
|
62
51
|
import React from 'react';
|
|
63
52
|
import ServerErrorFallback from '/.farm/rsc-entries/error-fallback.tsx';
|
|
64
53
|
${middlewareConfigImports}
|
|
65
|
-
${mcpConfigImports}
|
|
66
|
-
${mcpSource ? `${mcpSource.importSource}\nimport { mergePluginAPIRoutes } from '@farm.js/core/api/runtime';` : ""}
|
|
67
54
|
import { registerAPIRouteShape } from '@farm.js/core/api/runtime';
|
|
68
55
|
import {
|
|
69
56
|
renderToReadableStream,
|
|
@@ -89,7 +76,6 @@ import {
|
|
|
89
76
|
applyProductionMiddlewareHeaders,
|
|
90
77
|
createProductionMiddlewareRunner,
|
|
91
78
|
} from '@farm.js/core/middleware';
|
|
92
|
-
import { _withFarmGuardedResponseCache } from '@farm.js/core/internal/production-runtime';
|
|
93
79
|
import {
|
|
94
80
|
getAllowedAPIRouteMethods,
|
|
95
81
|
invokeAPIRouteEndpoint,
|
|
@@ -105,69 +91,10 @@ import {
|
|
|
105
91
|
compareRouteSpecificity,
|
|
106
92
|
getRoutePatternSpecificity,
|
|
107
93
|
} from '@farm.js/core/internal/production-runtime';
|
|
108
|
-
import {
|
|
109
|
-
appMiddlewareMayHandlePath,
|
|
110
|
-
configMiddlewareMayHandlePath,
|
|
111
|
-
materializeSSGRoutePath,
|
|
112
|
-
mergeMetadata,
|
|
113
|
-
mergeModuleViewport,
|
|
114
|
-
mergeRouteRenderingDirectiveConfig,
|
|
115
|
-
renderMetadataHead,
|
|
116
|
-
resolveMetadataTitle,
|
|
117
|
-
} from '@farm.js/core/internal/production-runtime';
|
|
118
94
|
|
|
119
|
-
import {
|
|
120
|
-
FARM_MARKDOWN_CONTENT_TYPE,
|
|
121
|
-
applyMarkdownNegotiationHeaders,
|
|
122
|
-
createFarmMarkdownErrorBody,
|
|
123
|
-
createMarkdownMirrorResponse,
|
|
124
|
-
farmRequestWantsMarkdown,
|
|
125
|
-
} from '@farm.js/core/markdown';
|
|
126
|
-
|
|
127
|
-
${ctx.images && ctx.images.runtime !== "none"
|
|
128
|
-
? `import { createCloudflareImageTransformer, createFarmImageHandler } from '@farm.js/core/image/server';
|
|
129
|
-
${ctx.images.runtime === "node"
|
|
130
|
-
? "import { createNodeImageFetcher, createNodeImageUrlValidator, createSharpImageTransformer } from '@farm.js/core/image/sharp';"
|
|
131
|
-
: ""}
|
|
132
|
-
const farmImageConfig = ${JSON.stringify(ctx.images.config)};
|
|
133
|
-
const farmImageHandler = createFarmImageHandler(farmImageConfig, ${ctx.images.runtime === "cloudflare"
|
|
134
|
-
? `{
|
|
135
|
-
transform: createCloudflareImageTransformer(),
|
|
136
|
-
onError(error) { console.error('[Farm Image]', error); },
|
|
137
|
-
}`
|
|
138
|
-
: `{
|
|
139
|
-
transform: createSharpImageTransformer(),
|
|
140
|
-
fetchRemote: createNodeImageFetcher(farmImageConfig),
|
|
141
|
-
validateRemoteUrl: createNodeImageUrlValidator(farmImageConfig),
|
|
142
|
-
onError(error) { console.error('[Farm Image]', error); },
|
|
143
|
-
}`});`
|
|
144
|
-
: "const farmImageHandler = null;"}
|
|
145
|
-
const farmImagePath = ${JSON.stringify(ctx.images?.path ?? "/_farm/image")};
|
|
146
|
-
${ctx.images
|
|
147
|
-
? `// <Image> reads this when @farm.js/core/image is not bundled (dev, or an external dependency),
|
|
148
|
-
// where the __FARM_IMAGE_CONFIG__ define never reaches it. The SSR environment shares the process.
|
|
149
|
-
globalThis.__FARM_IMAGE_CONFIG__ = ${JSON.stringify(ctx.images.public)};`
|
|
150
|
-
: ""}
|
|
151
95
|
const farmDeploymentId = ${JSON.stringify(ctx.deploymentId)};
|
|
152
96
|
const farmApiBasePath = ${JSON.stringify(ctx.apiBasePath ?? "/api")};
|
|
153
|
-
const farmMarkdownConfig = ${JSON.stringify(ctx.markdown ?? { enabled: false, expose: [], cache: false, includeMetadata: true })};
|
|
154
97
|
`;
|
|
155
|
-
if (ctx.llmsTxt?.enabled) {
|
|
156
|
-
code += `import {
|
|
157
|
-
collectFarmLlmsTxtPages,
|
|
158
|
-
createFarmDefaultLlmsTxt,
|
|
159
|
-
createFarmLlmsFullRenderer,
|
|
160
|
-
createFarmLlmsMarkdownReader,
|
|
161
|
-
createFarmMetadataRouteResponse,
|
|
162
|
-
farmPathGuardCoversPage,
|
|
163
|
-
renderFarmLlmsFullTxt,
|
|
164
|
-
} from '@farm.js/core/internal/production-runtime';
|
|
165
|
-
import { FARM_MARKDOWN_ANONYMOUS_CLIENT_ADDRESS } from '@farm.js/core/internal/app-markdown-runtime';
|
|
166
|
-
|
|
167
|
-
const farmLlmsTxtConfig = ${JSON.stringify(ctx.llmsTxt)};
|
|
168
|
-
const farmLlmsFullRenderer = createFarmLlmsFullRenderer({ revalidate: farmLlmsTxtConfig.revalidate });
|
|
169
|
-
`;
|
|
170
|
-
}
|
|
171
98
|
if (ctx.actionsEnabled) {
|
|
172
99
|
code += `import {
|
|
173
100
|
createServerActionRequestErrorResponse,
|
|
@@ -179,56 +106,6 @@ const farmLlmsFullRenderer = createFarmLlmsFullRenderer({ revalidate: farmLlmsTx
|
|
|
179
106
|
} from '@farm.js/core/server-action-security';
|
|
180
107
|
|
|
181
108
|
const serverActionSecurity = ${JSON.stringify(ctx.serverActions)};
|
|
182
|
-
`;
|
|
183
|
-
}
|
|
184
|
-
// In development, a page, layout, loading or error file that fails to load
|
|
185
|
-
// fails only the routes that use it. Eager globs would fail the whole entry,
|
|
186
|
-
// so every route returned the same error until the file was fixed. The
|
|
187
|
-
// modules still load once, in order, before the first request. Middleware
|
|
188
|
-
// and API routes stay eager: skipping a broken auth middleware would leave
|
|
189
|
-
// its routes unprotected. Production keeps eager globs, where a broken
|
|
190
|
-
// import already fails the build.
|
|
191
|
-
const isolateRouteModules = ctx.development === true;
|
|
192
|
-
const uiRouteGlob = (pattern) => isolateRouteModules
|
|
193
|
-
? `await loadFarmDevRouteModules(import.meta.glob(${JSON.stringify(pattern)}))`
|
|
194
|
-
: `import.meta.glob(${JSON.stringify(pattern)}, { eager: true })`;
|
|
195
|
-
if (isolateRouteModules) {
|
|
196
|
-
code += `
|
|
197
|
-
const farmRouteLoadErrors = new Map();
|
|
198
|
-
|
|
199
|
-
async function loadFarmDevRouteModules(loaders) {
|
|
200
|
-
const modules = {};
|
|
201
|
-
for (const [filePath, load] of Object.entries(loaders)) {
|
|
202
|
-
try {
|
|
203
|
-
modules[filePath] = await load();
|
|
204
|
-
} catch (error) {
|
|
205
|
-
console.error('[Farm.js] Could not load ' + filePath + ':', error);
|
|
206
|
-
const failed = {
|
|
207
|
-
default: function FarmRouteLoadFailure() {
|
|
208
|
-
throw error;
|
|
209
|
-
},
|
|
210
|
-
};
|
|
211
|
-
farmRouteLoadErrors.set(failed, error);
|
|
212
|
-
modules[filePath] = failed;
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
return modules;
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
/** The load error of a module the matched route renders with, if any. */
|
|
219
|
-
function findFarmRouteLoadError(matched) {
|
|
220
|
-
if (farmRouteLoadErrors.size === 0) return undefined;
|
|
221
|
-
const routeModules = [
|
|
222
|
-
pages[matched.pattern],
|
|
223
|
-
...getRouteModules(matched.pattern, layouts, 'layout'),
|
|
224
|
-
...getRouteModules(matched.pattern, loadings, 'loading'),
|
|
225
|
-
...getRouteModules(matched.pattern, errors, 'error'),
|
|
226
|
-
];
|
|
227
|
-
for (const module of routeModules) {
|
|
228
|
-
if (farmRouteLoadErrors.has(module)) return farmRouteLoadErrors.get(module);
|
|
229
|
-
}
|
|
230
|
-
return undefined;
|
|
231
|
-
}
|
|
232
109
|
`;
|
|
233
110
|
}
|
|
234
111
|
// Auto-discover pages, layouts, and middleware using Vite's glob import
|
|
@@ -255,18 +132,14 @@ function applyActionResponseHeaders(headers, request) {
|
|
|
255
132
|
headers.set('cache-control', 'no-store');
|
|
256
133
|
headers.set('x-content-type-options', 'nosniff');
|
|
257
134
|
}
|
|
258
|
-
// A page renders per request (cookies, headers, client address), so a shared
|
|
259
|
-
// cache must not keep its HTML or Flight payload unless middleware chose a
|
|
260
|
-
// policy. Core's server defaults pages the same way.
|
|
261
|
-
if (!headers.has('cache-control')) headers.set('cache-control', 'private, no-store');
|
|
262
135
|
}
|
|
263
136
|
|
|
264
137
|
// Auto-discover all route modules. Every glob remains a literal so Vite can analyze it.
|
|
265
138
|
${routeSourceRoots
|
|
266
|
-
.map((root, index) => `const pages${index} = ${
|
|
267
|
-
const layouts${index} = ${
|
|
268
|
-
const loadings${index} = ${
|
|
269
|
-
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 });
|
|
270
143
|
const middlewares${index} = import.meta.glob(${JSON.stringify(`${root.glob}/**/middleware.{tsx,jsx,ts,js}`)}, { eager: true });
|
|
271
144
|
const apiRouteModules${index} = import.meta.glob(${JSON.stringify(`${root.glob}/api/**/route.{tsx,jsx,ts,js}`)}, { eager: true });
|
|
272
145
|
const routeDefinitionModules${index} = import.meta.glob(${JSON.stringify(root.sourceGlob === root.glob
|
|
@@ -319,14 +192,6 @@ const pages = mergeRouteModules([${routeRoots
|
|
|
319
192
|
const layouts = mergeRouteModules([${routeRoots
|
|
320
193
|
.map((root, index) => `{ base: ${JSON.stringify(root.base)}, modules: layouts${index} }`)
|
|
321
194
|
.join(", ")}]);
|
|
322
|
-
// Root layouts that render <html> themselves own the document, as in Next.js.
|
|
323
|
-
const farmDocumentLayoutKeys = new Set(${JSON.stringify(ctx.documentLayouts ?? [])});
|
|
324
|
-
const farmDocumentLayoutModules = new Set(
|
|
325
|
-
Object.entries(layouts)
|
|
326
|
-
.filter(([key]) => farmDocumentLayoutKeys.has(key))
|
|
327
|
-
.map(([, module]) => module),
|
|
328
|
-
);
|
|
329
|
-
|
|
330
195
|
const loadings = mergeRouteModules([${routeRoots
|
|
331
196
|
.map((root, index) => `{ base: ${JSON.stringify(root.base)}, modules: loadings${index} }`)
|
|
332
197
|
.join(", ")}]);
|
|
@@ -418,42 +283,7 @@ function registerApiRouteSources(fileModules, definitionModules, sourceCount) {
|
|
|
418
283
|
}
|
|
419
284
|
|
|
420
285
|
registerApiRouteSources(apiRouteModules, routeDefinitionModules, ${routeSourceRoots.length});
|
|
421
|
-
|
|
422
|
-
? `
|
|
423
|
-
// mcp: the same plugin core's production server mounts, built from the mcp
|
|
424
|
-
// config read from each config file, layers first.
|
|
425
|
-
const farmNativeMCPPlugin = (() => {
|
|
426
|
-
const farmRuntimeConfigs = [${(ctx.mcpConfigPaths ?? [])
|
|
427
|
-
.map((_path, index) => `(FarmMCPConfigModule${index}.default || FarmMCPConfigModule${index})`)
|
|
428
|
-
.join(", ")}];
|
|
429
|
-
${mcpSource.registerSource}
|
|
430
|
-
return farmNativeMCPPlugin;
|
|
431
|
-
})();
|
|
432
|
-
if (farmNativeMCPPlugin) {
|
|
433
|
-
const mountedRoutes = [...apiRouteMap.values()].map((route) => ({
|
|
434
|
-
path: route.path,
|
|
435
|
-
methods: [...route.methods],
|
|
436
|
-
endpoints: { ...route.handlers },
|
|
437
|
-
}));
|
|
438
|
-
// Rejects a plugin route that would replace an app endpoint. An MCP tool calls its
|
|
439
|
-
// endpoint through handler(), so the middleware guarding that path runs for it.
|
|
440
|
-
for (const route of mergePluginAPIRoutes(mountedRoutes, [farmNativeMCPPlugin], undefined, {
|
|
441
|
-
dispatch: (request) => handler(request),
|
|
442
|
-
})) {
|
|
443
|
-
for (const method of route.pluginMethods ?? []) {
|
|
444
|
-
let target = apiRouteMap.get(route.path);
|
|
445
|
-
if (!target) {
|
|
446
|
-
target = { path: route.path, methods: [], handlers: {}, files: {}, sources: {} };
|
|
447
|
-
apiRouteMap.set(route.path, target);
|
|
448
|
-
}
|
|
449
|
-
target.methods.push(method);
|
|
450
|
-
target.handlers[method] = route.endpoints[method];
|
|
451
|
-
target.files[method] = 'plugin:' + farmNativeMCPPlugin.name;
|
|
452
|
-
}
|
|
453
|
-
}
|
|
454
|
-
}
|
|
455
|
-
`
|
|
456
|
-
: ""}
|
|
286
|
+
|
|
457
287
|
async function handleAPIRequest(request) {
|
|
458
288
|
const url = new URL(request.url);
|
|
459
289
|
const match = matchAPIRouteAtBasePath(apiRouteMap, url.pathname, farmApiBasePath);
|
|
@@ -501,20 +331,9 @@ const farmMiddlewareRunner = createProductionMiddlewareRunner({
|
|
|
501
331
|
.filter((entry) => entry.path !== null)
|
|
502
332
|
// Root first, as core runs them: a nested guard can rely on what its
|
|
503
333
|
// parent middleware set, and glob order is alphabetical, not by depth.
|
|
504
|
-
|
|
505
|
-
// '/middleware.ts' precedes '/(app)/middleware.ts'.
|
|
506
|
-
.sort(
|
|
507
|
-
(left, right) =>
|
|
508
|
-
middlewareRouteDepth(left.path) - middlewareRouteDepth(right.path) ||
|
|
509
|
-
left.path.localeCompare(right.path) ||
|
|
510
|
-
middlewareRouteDepth(left.filePath) - middlewareRouteDepth(right.filePath) ||
|
|
511
|
-
left.filePath.localeCompare(right.filePath),
|
|
512
|
-
),
|
|
334
|
+
.sort((left, right) => middlewareRouteDepth(left.path) - middlewareRouteDepth(right.path)),
|
|
513
335
|
i18n: ${JSON.stringify(ctx.i18n) ?? "undefined"},
|
|
514
336
|
server: ${JSON.stringify(ctx.server) ?? "undefined"},
|
|
515
|
-
apiBasePath: farmApiBasePath,
|
|
516
|
-
// matchRoute() reads url.pathname as received, so middleware guards that path too.
|
|
517
|
-
rawPathRouting: true,
|
|
518
337
|
});
|
|
519
338
|
|
|
520
339
|
debug('Discovered pages:', Object.keys(pages));
|
|
@@ -527,37 +346,22 @@ debug('Discovered API routes:', Array.from(apiRouteMap.keys()));
|
|
|
527
346
|
/**
|
|
528
347
|
* Convert an app-relative middleware file path to the route it guards, with the
|
|
529
348
|
* same rules as core's middleware discovery: a route group such as
|
|
530
|
-
* '(protected)'
|
|
531
|
-
* an intercepting folder guards the URL it intercepts, a '_private' folder
|
|
532
|
-
* 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
|
|
533
350
|
* holds no routes, so its middleware never runs (null).
|
|
534
351
|
* e.g., '/middleware.ts' -> '/'
|
|
535
352
|
* e.g., '/(protected)/dashboard/middleware.ts' -> '/dashboard'
|
|
536
|
-
* e.g., '/dashboard/@team/middleware.ts' -> '/dashboard'
|
|
537
|
-
* e.g., '/feed/@modal/(.)photo/middleware.ts' -> '/feed/photo'
|
|
538
353
|
*/
|
|
539
354
|
function middlewarePathToRoute(filePath) {
|
|
540
355
|
const segments = filePath
|
|
541
356
|
.replace(/\\/middleware\\.[tj]sx?$/, '')
|
|
542
357
|
.split('/')
|
|
543
358
|
.filter(Boolean);
|
|
544
|
-
if (segments.some((segment) => segment.startsWith('.'))) {
|
|
359
|
+
if (segments.some((segment) => segment.startsWith('_') || segment.startsWith('.'))) {
|
|
545
360
|
return null;
|
|
546
361
|
}
|
|
547
|
-
const routeSegments =
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
if (marker) {
|
|
551
|
-
if (marker[1] === '(...)') routeSegments.length = 0;
|
|
552
|
-
else if (marker[1] !== '(.)') routeSegments.splice(-(marker[1].length / 4));
|
|
553
|
-
if (marker[2]) routeSegments.push(marker[2]);
|
|
554
|
-
continue;
|
|
555
|
-
}
|
|
556
|
-
if ((segment.startsWith('(') && segment.endsWith(')')) || /^@[A-Za-z][A-Za-z0-9_-]*$/.test(segment)) {
|
|
557
|
-
continue;
|
|
558
|
-
}
|
|
559
|
-
routeSegments.push(segment);
|
|
560
|
-
}
|
|
362
|
+
const routeSegments = segments.filter(
|
|
363
|
+
(segment) => !(segment.startsWith('(') && segment.endsWith(')')),
|
|
364
|
+
);
|
|
561
365
|
return routeSegments.length === 0 ? '/' : '/' + routeSegments.join('/');
|
|
562
366
|
}
|
|
563
367
|
|
|
@@ -616,12 +420,7 @@ const RouteErrorBoundary = React.Component
|
|
|
616
420
|
|
|
617
421
|
// Parse and rank once per entry initialization, not on every request. Use the
|
|
618
422
|
// same validation, decoding and specificity rules as Farm's ordinary router.
|
|
619
|
-
|
|
620
|
-
// answer at its literal folder path ('/feed/@modal/(.)photo/1'), past the middleware
|
|
621
|
-
// that guards the URL it intercepts.
|
|
622
|
-
const pageRoutes = Object.entries(pages)
|
|
623
|
-
.filter(([filePath]) => !filePath.split('/').some((segment) => /^@[A-Za-z][A-Za-z0-9_-]*$/.test(segment)))
|
|
624
|
-
.map(([filePath, module]) => ({
|
|
423
|
+
const pageRoutes = Object.entries(pages).map(([filePath, module]) => ({
|
|
625
424
|
filePath,
|
|
626
425
|
module,
|
|
627
426
|
segments: parseRoutePath(filePath).segments,
|
|
@@ -644,7 +443,7 @@ function matchRoute(pathname) {
|
|
|
644
443
|
Page: module.default,
|
|
645
444
|
pattern: filePath,
|
|
646
445
|
params: match.params,
|
|
647
|
-
module,
|
|
446
|
+
pageMetadata: module.metadata,
|
|
648
447
|
};
|
|
649
448
|
}
|
|
650
449
|
}
|
|
@@ -653,77 +452,13 @@ function matchRoute(pathname) {
|
|
|
653
452
|
return null;
|
|
654
453
|
}
|
|
655
454
|
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
const
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
* The URL paths the build prerenders, by core's SSG rules: a page asks to be static
|
|
662
|
-
* (dynamic = "force-static", generateStaticParams, "use ssg"), does not read request
|
|
663
|
-
* state, and does not revalidate. A prerendered page is a static file the server never sees, so a
|
|
664
|
-
* path any middleware may handle stays server-rendered.
|
|
665
|
-
*/
|
|
666
|
-
async function collectFarmStaticPages() {
|
|
667
|
-
${ctx.i18n?.enabled
|
|
668
|
-
? `console.info('[Farm.js] Prerendering is off: i18n resolves the locale per request.');
|
|
669
|
-
return [];`
|
|
670
|
-
: ""}
|
|
671
|
-
const middlewareRoutes = Object.keys(middlewares)
|
|
672
|
-
.map((filePath) => ({ path: middlewarePathToRoute(filePath) }))
|
|
673
|
-
.filter((route) => route.path !== null);
|
|
674
|
-
const paths = new Set();
|
|
675
|
-
for (const { filePath, module, segments } of pageRoutes) {
|
|
676
|
-
const rendering = mergeRouteRenderingDirectiveConfig(farmPageRenderingDirectives[filePath], module);
|
|
677
|
-
if (!rendering.ssg || rendering.revalidate !== undefined) continue;
|
|
678
|
-
const pattern = '/' + segments
|
|
679
|
-
.map((part) => part.isCatchAll
|
|
680
|
-
? (part.isOptional ? '[[...' + part.segment + ']]' : '[...' + part.segment + ']')
|
|
681
|
-
: part.isDynamic ? '[' + part.segment + ']' : part.segment)
|
|
682
|
-
.join('/');
|
|
683
|
-
let pagePaths;
|
|
684
|
-
try {
|
|
685
|
-
if (!segments.some((part) => part.isDynamic)) {
|
|
686
|
-
pagePaths = [pattern];
|
|
687
|
-
} else {
|
|
688
|
-
const getStaticPaths = module.getStaticPaths || module.generateStaticParams;
|
|
689
|
-
if (typeof getStaticPaths !== 'function') {
|
|
690
|
-
throw new Error('a static route with dynamic segments needs generateStaticParams()');
|
|
691
|
-
}
|
|
692
|
-
pagePaths = (await getStaticPaths()).map((params) => materializeSSGRoutePath(pattern, params));
|
|
693
|
-
}
|
|
694
|
-
} catch (error) {
|
|
695
|
-
console.error('[Farm.js] Rendering ' + filePath + ' on each request: could not list its static paths.', error);
|
|
696
|
-
continue;
|
|
697
|
-
}
|
|
698
|
-
for (const pagePath of pagePaths) {
|
|
699
|
-
if (
|
|
700
|
-
appMiddlewareMayHandlePath(middlewareRoutes, pagePath) ||
|
|
701
|
-
configMiddlewareMayHandlePath(farmConfigMiddleware, pagePath)
|
|
702
|
-
) {
|
|
703
|
-
continue;
|
|
704
|
-
}
|
|
705
|
-
paths.add(pagePath);
|
|
706
|
-
}
|
|
707
|
-
}
|
|
708
|
-
return [...paths];
|
|
709
|
-
}
|
|
710
|
-
|
|
711
|
-
// The route's metadata as core's server resolves it: layouts root to leaf, then the page, each
|
|
712
|
-
// module's \`metadata\`, \`generateMetadata()\` and viewport exports merged in order.
|
|
713
|
-
async function resolveFarmRouteMetadata(layoutModules, pageModule, pageProps) {
|
|
714
|
-
let metadata = {};
|
|
715
|
-
for (const layoutModule of layoutModules) {
|
|
716
|
-
metadata = mergeMetadata(metadata, layoutModule.metadata);
|
|
717
|
-
if (typeof layoutModule.generateMetadata === 'function') {
|
|
718
|
-
metadata = mergeMetadata(metadata, await layoutModule.generateMetadata({ params: pageProps.params }));
|
|
719
|
-
}
|
|
720
|
-
metadata = await mergeModuleViewport(metadata, layoutModule, { params: pageProps.params });
|
|
721
|
-
}
|
|
722
|
-
metadata = mergeMetadata(metadata, pageModule?.metadata);
|
|
723
|
-
if (typeof pageModule?.generateMetadata === 'function') {
|
|
724
|
-
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;
|
|
725
460
|
}
|
|
726
|
-
return
|
|
461
|
+
return metadata;
|
|
727
462
|
}
|
|
728
463
|
|
|
729
464
|
/**
|
|
@@ -774,19 +509,8 @@ function getMatchingBoundary(pageFilePath, modules, kind) {
|
|
|
774
509
|
/**
|
|
775
510
|
* Main request handler - entry point for both dev and production (Nitro).
|
|
776
511
|
* Exported as { fetch: handler } for the RSC/Nitro contract (see vite-plugin-rsc-deploy-example).
|
|
777
|
-
*
|
|
778
|
-
* Middleware that let a request through may have been a guard: an IP allowlist, an API key
|
|
779
|
-
* header, a VPN header. A CDN keys its copy by URL and never runs the guard on a hit, so
|
|
780
|
-
* whatever such a request answers stays out of shared caches, as in core's server. Only
|
|
781
|
-
* middleware declaring cache: "public" leaves the policy alone.
|
|
782
512
|
*/
|
|
783
513
|
async function handleFarmRequest(request, context) {
|
|
784
|
-
const farmCacheGuard = { guarded: false };
|
|
785
|
-
const response = await resolveFarmRequest(farmCacheGuard, request, context);
|
|
786
|
-
return farmCacheGuard.guarded ? _withFarmGuardedResponseCache(response) : response;
|
|
787
|
-
}
|
|
788
|
-
|
|
789
|
-
async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
790
514
|
let url = new URL(request.url);
|
|
791
515
|
let matchedPage = null;
|
|
792
516
|
let errorData = new Map();
|
|
@@ -826,7 +550,6 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
826
550
|
// Execute middleware first
|
|
827
551
|
const middlewareResult = await executeMiddleware(request, context);
|
|
828
552
|
${generateRscMiddlewareResultHandling()}
|
|
829
|
-
if (middlewareResult.guarded) farmCacheGuard.guarded = true;
|
|
830
553
|
|
|
831
554
|
request = middlewareResult.request;
|
|
832
555
|
url = new URL(request.url);
|
|
@@ -849,21 +572,11 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
849
572
|
_runWithMiddlewareContext(middlewareContext, async () => {
|
|
850
573
|
const glob = '';
|
|
851
574
|
|
|
852
|
-
if (farmImageHandler && url.pathname === farmImagePath) {
|
|
853
|
-
const imageResponse = await farmImageHandler(request);
|
|
854
|
-
if (imageResponse) return imageResponse;
|
|
855
|
-
}
|
|
856
|
-
|
|
857
575
|
const apiResponse = await handleAPIRequest(request.clone());
|
|
858
576
|
if (apiResponse) {
|
|
859
577
|
return applyProductionMiddlewareHeaders(apiResponse, middlewareHeaders);
|
|
860
578
|
}
|
|
861
|
-
|
|
862
|
-
? `// agent.llmsTxt: answered after middleware, so its redirects and headers apply.
|
|
863
|
-
const llmsResponse = await handleFarmLlmsTxtRequest(request, context);
|
|
864
|
-
if (llmsResponse) return applyProductionMiddlewareHeaders(llmsResponse, middlewareHeaders);
|
|
865
|
-
`
|
|
866
|
-
: ""}if (isFarmAPIPathname(url.pathname, farmApiBasePath) || isFarmAPIPathname(url.pathname)) {
|
|
579
|
+
if (isFarmAPIPathname(url.pathname, farmApiBasePath) || isFarmAPIPathname(url.pathname)) {
|
|
867
580
|
return applyProductionMiddlewareHeaders(new Response(
|
|
868
581
|
JSON.stringify({ error: 'API route not found', pathname: url.pathname }),
|
|
869
582
|
{ status: 404, headers: { 'Content-Type': 'application/json' } },
|
|
@@ -1018,26 +731,15 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1018
731
|
|
|
1019
732
|
if (!matched) {
|
|
1020
733
|
debug('404 - No route found for:', url.pathname);
|
|
1021
|
-
// Agents that read in Markdown get a Markdown 404, as in core's server.
|
|
1022
|
-
if (farmMarkdownConfig.enabled && farmRequestWantsMarkdown(url.pathname, request.headers.get('accept'))) {
|
|
1023
|
-
return new Response(createFarmMarkdownErrorBody(404, url.pathname), {
|
|
1024
|
-
status: 404,
|
|
1025
|
-
headers: {
|
|
1026
|
-
'Content-Type': FARM_MARKDOWN_CONTENT_TYPE,
|
|
1027
|
-
'X-Farm-Markdown-Error': '404',
|
|
1028
|
-
'Cache-Control': 'no-store',
|
|
1029
|
-
},
|
|
1030
|
-
});
|
|
1031
|
-
}
|
|
1032
734
|
return new Response('Not Found', { status: 404 });
|
|
1033
735
|
}
|
|
1034
736
|
|
|
1035
|
-
const { Page, pattern, params,
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
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
|
+
);
|
|
1041
743
|
const configuredRoutesDir = ${ctx.routesDir === undefined ? "undefined" : JSON.stringify(ctx.routesDir)};
|
|
1042
744
|
const routesDir = configuredRoutesDir === undefined ? 'app' : configuredRoutesDir.trim();
|
|
1043
745
|
const routesPath = routesDir ? '/' + routesDir : '';
|
|
@@ -1050,14 +752,6 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1050
752
|
|
|
1051
753
|
// Page props passed to components (includes middleware shared data)
|
|
1052
754
|
const pageProps = { params, searchParams, middlewareData };
|
|
1053
|
-
const metadata = await resolveFarmRouteMetadata(LayoutModules, pageModule, pageProps);
|
|
1054
|
-
const renderedHead = renderMetadataHead(metadata, { pathname: url.pathname });
|
|
1055
|
-
// Injected into <head> by the SSR entry; React renders only the charset.
|
|
1056
|
-
const metadataHead =
|
|
1057
|
-
(renderedHead.hasExplicitTitle ? '<title>' + renderedHead.title + '</title>' : '') +
|
|
1058
|
-
renderedHead.viewport +
|
|
1059
|
-
renderedHead.tags;
|
|
1060
|
-
const metadataTitle = resolveMetadataTitle(metadata.title);
|
|
1061
755
|
|
|
1062
756
|
debug('Rendering page:', pattern, 'with props:', pageProps);
|
|
1063
757
|
|
|
@@ -1103,36 +797,26 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1103
797
|
}
|
|
1104
798
|
}
|
|
1105
799
|
|
|
1106
|
-
//
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
LayoutModules.length > 0 && farmDocumentLayoutModules.has(LayoutModules[0]);
|
|
1110
|
-
// Otherwise a single wrapper, so #root has exactly one child (avoids a duplicate block in the DOM).
|
|
1111
|
-
const rootInner = ownsDocument
|
|
1112
|
-
? h(
|
|
1113
|
-
React.Fragment,
|
|
1114
|
-
null,
|
|
1115
|
-
h('meta', { charSet: 'utf-8' }),
|
|
1116
|
-
layoutContent,
|
|
1117
|
-
)
|
|
1118
|
-
: h('div', { 'data-farm-root': 'true' }, layoutContent);
|
|
1119
|
-
// 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).
|
|
1120
803
|
const payload = {
|
|
1121
|
-
|
|
1122
|
-
root: ownsDocument ? rootInner : h('html', null,
|
|
804
|
+
root: h('html', null,
|
|
1123
805
|
h('head', null,
|
|
1124
806
|
h('meta', { charSet: 'utf-8' }),
|
|
1125
|
-
|
|
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
|
|
1126
811
|
),
|
|
1127
812
|
h('body', null,
|
|
1128
813
|
h('div', { id: 'root' }, rootInner)
|
|
1129
814
|
)
|
|
1130
815
|
),
|
|
1131
816
|
rootContent: rootInner,
|
|
1132
|
-
metadataHead,
|
|
1133
817
|
metadata: {
|
|
1134
|
-
title:
|
|
1135
|
-
description: typeof metadata
|
|
818
|
+
title: typeof metadata?.title === 'string' ? metadata.title : undefined,
|
|
819
|
+
description: typeof metadata?.description === 'string' ? metadata.description : undefined,
|
|
1136
820
|
},
|
|
1137
821
|
`;
|
|
1138
822
|
// Include action results in payload if actions are enabled
|
|
@@ -1190,8 +874,8 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1190
874
|
h('meta', { charSet: 'utf-8' }),
|
|
1191
875
|
h('meta', { name: 'viewport', content: 'width=device-width, initial-scale=1' }),
|
|
1192
876
|
h('link', { rel: 'icon', href: 'data:,' }),
|
|
1193
|
-
|
|
1194
|
-
|
|
877
|
+
metadata?.title ? h('title', null, metadata.title) : null,
|
|
878
|
+
metadata?.description ? h('meta', { name: 'description', content: metadata.description }) : null,
|
|
1195
879
|
h('link', { rel: 'stylesheet', href: globalsCssPath, as: 'style', precedence: 'default' }),
|
|
1196
880
|
h('script', { type: 'module', src: '/@vite/client' })
|
|
1197
881
|
),
|
|
@@ -1210,11 +894,7 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1210
894
|
)
|
|
1211
895
|
);
|
|
1212
896
|
} catch (err) {
|
|
1213
|
-
|
|
1214
|
-
? `// A file that failed to load: show the dev error page, not error.tsx.
|
|
1215
|
-
if ([...farmRouteLoadErrors.values()].includes(err)) throw err;
|
|
1216
|
-
`
|
|
1217
|
-
: ""}const redirect = getFarmRedirectError(err);
|
|
897
|
+
const redirect = getFarmRedirectError(err);
|
|
1218
898
|
if (redirect) return new Response(null, { status: redirect.status, headers: { location: redirect.url, 'cache-control': 'no-store' } });
|
|
1219
899
|
if (isFarmNotFoundError(err)) return new Response('Not Found', { status: 404, headers: { 'cache-control': 'no-store' } });
|
|
1220
900
|
console.error('[RSC] Handler error:', err);
|
|
@@ -1300,186 +980,13 @@ async function resolveFarmRequest(farmCacheGuard, request, context) {
|
|
|
1300
980
|
}
|
|
1301
981
|
}
|
|
1302
982
|
|
|
1303
|
-
${ctx.llmsTxt?.enabled
|
|
1304
|
-
? `/**
|
|
1305
|
-
* agent.llmsTxt, built the same way as core's production server: /llms.txt
|
|
1306
|
-
* lists the app's static pages and links to their Markdown mirrors, and
|
|
1307
|
-
* /llms-full.txt inlines each mirror.
|
|
1308
|
-
*/
|
|
1309
|
-
function createFarmLlmsTxtContext(request, context, full) {
|
|
1310
|
-
const origin = new URL(request.url).origin;
|
|
1311
|
-
// A page a path-specific guard covers (a non-root middleware.ts, a config
|
|
1312
|
-
// middleware matcher naming the path) is left out, as core's server does.
|
|
1313
|
-
const guard = {
|
|
1314
|
-
config: { middleware: farmConfigMiddleware },
|
|
1315
|
-
middlewareRoutes: Object.keys(middlewares)
|
|
1316
|
-
.map((filePath) => ({ path: middlewarePathToRoute(filePath) }))
|
|
1317
|
-
.filter((route) => route.path !== null),
|
|
1318
|
-
};
|
|
1319
|
-
const pages = collectFarmLlmsTxtPages(
|
|
1320
|
-
pageRoutes
|
|
1321
|
-
.map(({ module, segments }) => ({
|
|
1322
|
-
// Dynamic routes have no single URL, so the collector skips them.
|
|
1323
|
-
pattern: '/' + segments
|
|
1324
|
-
.map((part) => (part.isDynamic ? '[' + part.segment + ']' : part.segment))
|
|
1325
|
-
.join('/'),
|
|
1326
|
-
metadata: module && module.metadata,
|
|
1327
|
-
}))
|
|
1328
|
-
.filter((page) => page.pattern.includes('[') || !farmPathGuardCoversPage(guard, page.pattern)),
|
|
1329
|
-
{
|
|
1330
|
-
origin,
|
|
1331
|
-
markdown: farmMarkdownConfig,
|
|
1332
|
-
include: farmLlmsTxtConfig.include,
|
|
1333
|
-
exclude: farmLlmsTxtConfig.exclude,
|
|
1334
|
-
},
|
|
1335
|
-
);
|
|
1336
|
-
const rootLayout = getRouteModules('/page.tsx', layouts, 'layout')[0];
|
|
1337
|
-
return {
|
|
1338
|
-
defaults: createFarmDefaultLlmsTxt({
|
|
1339
|
-
origin,
|
|
1340
|
-
pages,
|
|
1341
|
-
config: farmLlmsTxtConfig,
|
|
1342
|
-
rootMetadata: rootLayout && rootLayout.metadata,
|
|
1343
|
-
}),
|
|
1344
|
-
// Pages are read in-process through the full handler as an anonymous
|
|
1345
|
-
// visitor: a fresh request, so the caller's cookies never shape the file,
|
|
1346
|
-
// and a neutral client address, so an IP allowlist never admits the read.
|
|
1347
|
-
// The body is shared across callers. HEAD reads nothing.
|
|
1348
|
-
markdown: full && request.method.toUpperCase() !== 'HEAD'
|
|
1349
|
-
? createFarmLlmsMarkdownReader((page) =>
|
|
1350
|
-
handler(page, {
|
|
1351
|
-
waitUntil: context && context.waitUntil,
|
|
1352
|
-
clientAddress: FARM_MARKDOWN_ANONYMOUS_CLIENT_ADDRESS,
|
|
1353
|
-
}),
|
|
1354
|
-
)
|
|
1355
|
-
: async () => null,
|
|
1356
|
-
};
|
|
1357
|
-
}
|
|
1358
|
-
|
|
1359
|
-
async function handleFarmLlmsTxtRequest(request, context) {
|
|
1360
|
-
const { origin, pathname } = new URL(request.url);
|
|
1361
|
-
const kind = pathname === '/llms.txt'
|
|
1362
|
-
? 'llms'
|
|
1363
|
-
: farmLlmsTxtConfig.full && pathname === '/llms-full.txt' ? 'llms-full' : null;
|
|
1364
|
-
if (!kind) return null;
|
|
1365
|
-
const method = request.method.toUpperCase();
|
|
1366
|
-
if (method !== 'GET' && method !== 'HEAD') {
|
|
1367
|
-
return new Response(null, { status: 405, headers: { Allow: 'GET, HEAD' } });
|
|
1368
|
-
}
|
|
1369
|
-
const llmsContext = createFarmLlmsTxtContext(request, context, kind === 'llms-full');
|
|
1370
|
-
// A page that times out is left out, and that response is neither reused nor cached.
|
|
1371
|
-
let complete = true;
|
|
1372
|
-
const renderFull = (shared) =>
|
|
1373
|
-
renderFarmLlmsFullTxt(llmsContext.defaults, {
|
|
1374
|
-
origin,
|
|
1375
|
-
readMarkdown: llmsContext.markdown,
|
|
1376
|
-
onIncomplete: () => {
|
|
1377
|
-
complete = false;
|
|
1378
|
-
if (shared) shared.incomplete();
|
|
1379
|
-
},
|
|
1380
|
-
});
|
|
1381
|
-
// HEAD reads no pages, so it neither waits for nor fills the shared render.
|
|
1382
|
-
const body = kind === 'llms'
|
|
1383
|
-
? llmsContext.defaults
|
|
1384
|
-
: method === 'HEAD'
|
|
1385
|
-
? await renderFull()
|
|
1386
|
-
: await farmLlmsFullRenderer(origin, renderFull, (settled) => {
|
|
1387
|
-
complete = settled;
|
|
1388
|
-
});
|
|
1389
|
-
const response = createFarmMetadataRouteResponse(
|
|
1390
|
-
kind,
|
|
1391
|
-
body,
|
|
1392
|
-
{ revalidate: complete ? farmLlmsTxtConfig.revalidate : 0 },
|
|
1393
|
-
{ method, request },
|
|
1394
|
-
);
|
|
1395
|
-
if (!complete) response.headers.set('cache-control', 'no-store');
|
|
1396
|
-
return response;
|
|
1397
|
-
}
|
|
1398
|
-
|
|
1399
|
-
`
|
|
1400
|
-
: ""}/**
|
|
1401
|
-
* Serves a page's Markdown mirror (\`/page.md\` or \`Accept: text/markdown\`) by
|
|
1402
|
-
* rendering the page through the normal request path, so middleware and sign-in
|
|
1403
|
-
* gates apply; every other request renders as usual, and HTML pages advertise
|
|
1404
|
-
* their mirror with a Link header.
|
|
1405
|
-
*/
|
|
1406
|
-
async function handleFarmPageOrMarkdown(request, context) {
|
|
1407
|
-
if (!farmMarkdownConfig.enabled) return handleFarmRequest(request, context);
|
|
1408
|
-
const markdown = await createMarkdownMirrorResponse({
|
|
1409
|
-
request,
|
|
1410
|
-
config: farmMarkdownConfig,
|
|
1411
|
-
routeExists: (pathname) => Boolean(matchRoute(pathname)),
|
|
1412
|
-
renderPage: (pageRequest) => handleFarmRequest(pageRequest, context),
|
|
1413
|
-
apiServerBasePath: farmApiBasePath,
|
|
1414
|
-
});
|
|
1415
|
-
if (markdown) return markdown;
|
|
1416
|
-
const response = await handleFarmRequest(request, context);
|
|
1417
|
-
return applyMarkdownNegotiationHeaders(response, {
|
|
1418
|
-
config: farmMarkdownConfig,
|
|
1419
|
-
pathname: new URL(request.url).pathname,
|
|
1420
|
-
});
|
|
1421
|
-
}
|
|
1422
|
-
|
|
1423
|
-
// Client navigation addresses a page's RSC payload as '<page>.rsc' ('<dir>/index.rsc' for a
|
|
1424
|
-
// trailing slash), so a prerendered page can be a static HTML file next to a static payload file.
|
|
1425
|
-
// 'Accept: text/x-component' on the page URL keeps working.
|
|
1426
|
-
function farmPayloadPath(pathname) {
|
|
1427
|
-
return pathname.endsWith('/') ? pathname + 'index.rsc' : pathname + '.rsc';
|
|
1428
|
-
}
|
|
1429
|
-
|
|
1430
|
-
function toFarmPayloadRequest(request) {
|
|
1431
|
-
if (request.method !== 'GET' && request.method !== 'HEAD') return request;
|
|
1432
|
-
const url = new URL(request.url);
|
|
1433
|
-
if (!url.pathname.endsWith('.rsc')) return request;
|
|
1434
|
-
if (isFarmAPIPathname(url.pathname, farmApiBasePath) || isFarmAPIPathname(url.pathname)) return request;
|
|
1435
|
-
const page = url.pathname.slice(0, -'.rsc'.length);
|
|
1436
|
-
url.pathname = page.endsWith('/index') ? page.slice(0, -'index'.length) : page;
|
|
1437
|
-
const headers = new Headers(request.headers);
|
|
1438
|
-
headers.set('accept', 'text/x-component');
|
|
1439
|
-
return new Request(url, { method: request.method, headers, signal: request.signal });
|
|
1440
|
-
}
|
|
1441
|
-
|
|
1442
|
-
// The build's prerender pass (Nitro) runs this server with FARM_RSC_PRERENDER set. It seeds one
|
|
1443
|
-
// route that lists the static pages, and each prerendered page queues its payload, both through
|
|
1444
|
-
// Nitro's x-nitro-prerender response header. Production servers never answer either.
|
|
1445
|
-
const FARM_PRERENDER_ROUTES_PATH = '/__farm/rsc-prerender-routes';
|
|
1446
|
-
function isFarmPrerenderRequest(request) {
|
|
1447
|
-
return globalThis.process?.env?.FARM_RSC_PRERENDER === '1' && request.headers.has('x-nitro-prerender');
|
|
1448
|
-
}
|
|
1449
|
-
|
|
1450
983
|
async function handler(request, context) {
|
|
1451
|
-
const prerendering = isFarmPrerenderRequest(request);
|
|
1452
|
-
if (prerendering && new URL(request.url).pathname === FARM_PRERENDER_ROUTES_PATH) {
|
|
1453
|
-
const pages = await collectFarmStaticPages();
|
|
1454
|
-
return new Response('<!doctype html>', {
|
|
1455
|
-
headers: {
|
|
1456
|
-
'content-type': 'text/html; charset=utf-8',
|
|
1457
|
-
'x-nitro-prerender': pages.map(encodeURIComponent).join(','),
|
|
1458
|
-
},
|
|
1459
|
-
});
|
|
1460
|
-
}
|
|
1461
|
-
const pageRequest = toFarmPayloadRequest(request);
|
|
1462
|
-
const response = await handleFarmRequestWithRuntime(pageRequest, context);
|
|
1463
|
-
if (
|
|
1464
|
-
prerendering &&
|
|
1465
|
-
pageRequest === request &&
|
|
1466
|
-
response.status === 200 &&
|
|
1467
|
-
(response.headers.get('content-type') || '').includes('text/html')
|
|
1468
|
-
) {
|
|
1469
|
-
const headers = new Headers(response.headers);
|
|
1470
|
-
headers.set('x-nitro-prerender', encodeURIComponent(farmPayloadPath(new URL(request.url).pathname)));
|
|
1471
|
-
return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
|
|
1472
|
-
}
|
|
1473
|
-
return response;
|
|
1474
|
-
}
|
|
1475
|
-
|
|
1476
|
-
async function handleFarmRequestWithRuntime(request, context) {
|
|
1477
984
|
return _runWithAPIRequestRuntime({
|
|
1478
985
|
basePath: farmApiBasePath,
|
|
1479
986
|
dispatch: async (localRequest) =>
|
|
1480
987
|
(await handleAPIRequest(localRequest)) ?? Response.json({ error: 'Not Found' }, { status: 404 }),
|
|
1481
988
|
}, () => _runWithCurrentRequest(request, () =>
|
|
1482
|
-
_runWithAfterRequest(request, () =>
|
|
989
|
+
_runWithAfterRequest(request, () => handleFarmRequest(request, context), context)
|
|
1483
990
|
));
|
|
1484
991
|
}
|
|
1485
992
|
|