@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.
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/middleware/index.d.ts +8 -1
- package/dist/middleware/index.d.ts.map +1 -1
- package/dist/middleware/index.js +16 -10
- package/dist/middleware/matching.d.ts +4 -2
- package/dist/middleware/matching.d.ts.map +1 -1
- package/dist/middleware/matching.js +7 -47
- package/dist/rsc/client-sourcemaps.d.ts +13 -0
- package/dist/rsc/client-sourcemaps.d.ts.map +1 -0
- package/dist/rsc/client-sourcemaps.js +52 -0
- package/dist/rsc/document-layouts.d.ts +16 -0
- package/dist/rsc/document-layouts.d.ts.map +1 -0
- package/dist/rsc/document-layouts.js +82 -0
- package/dist/rsc/entries/client.d.ts.map +1 -1
- package/dist/rsc/entries/client.js +92 -16
- package/dist/rsc/entries/rsc.d.ts.map +1 -1
- package/dist/rsc/entries/rsc.js +567 -47
- package/dist/rsc/entries/ssr.d.ts.map +1 -1
- package/dist/rsc/entries/ssr.js +27 -10
- package/dist/rsc/index.d.ts +38 -3
- package/dist/rsc/index.d.ts.map +1 -1
- package/dist/rsc/index.js +300 -292
- package/dist/rsc/middleware-config-module.d.ts +3 -0
- package/dist/rsc/middleware-config-module.d.ts.map +1 -1
- package/dist/rsc/middleware-config-module.js +41 -28
- package/dist/rsc/mobile-client.d.ts +67 -0
- package/dist/rsc/mobile-client.d.ts.map +1 -0
- package/dist/rsc/mobile-client.js +148 -0
- package/dist/rsc/nitro-build.d.ts.map +1 -1
- package/dist/rsc/nitro-build.js +268 -81
- package/dist/rsc/server-fn-transform.d.ts +1 -5
- package/dist/rsc/server-fn-transform.d.ts.map +1 -1
- package/dist/rsc/server-fn-transform.js +3 -338
- package/dist/rsc/types.d.ts +39 -0
- package/dist/rsc/types.d.ts.map +1 -1
- package/dist/rsc/vite-plugin-nitro.d.ts +2 -0
- package/dist/rsc/vite-plugin-nitro.d.ts.map +1 -1
- package/dist/rsc/vite-plugin-nitro.js +12 -2
- package/package.json +3 -3
package/dist/rsc/index.js
CHANGED
|
@@ -25,18 +25,22 @@ import { loadFarmDevModule, FarmDevEnvironmentError } from "@farm.js/core/plugin
|
|
|
25
25
|
import { parseAst, version as viteVersion, } from "vite";
|
|
26
26
|
import { init as initModuleLexer, parse as parseModuleImports } from "es-module-lexer";
|
|
27
27
|
import { farmEnvironmentFunctionsPlugin } from "@farm.js/core/environment/vite";
|
|
28
|
-
import { generateClientCachePersistenceCode, resolveFarmClientCacheAdapterEntry, } from "@farm.js/core/vite";
|
|
28
|
+
import { collectDevStylesheetUrls, farmFontImportsPlugin, farmImageImportsPlugin, generateClientCachePersistenceCode, getPublicFarmImageConfig, resolveFarmClientCacheAdapterEntry, resolveFarmClientOptimizeDeps, resolveFarmImageConfig, resolveFarmImageProviderForRuntime, resolveFarmImageServerRuntime, readRouteRenderingDirectiveFromFile, } from "@farm.js/core/vite";
|
|
29
29
|
import { generateRscEntry } from "./entries/rsc.js";
|
|
30
|
+
import { resolveMarkdownConfig } from "@farm.js/core/markdown";
|
|
30
31
|
import { generateSsrEntry } from "./entries/ssr.js";
|
|
31
32
|
import { generateErrorFallbackEntry } from "./entries/error-fallback.js";
|
|
32
33
|
import { generateClientEntry, serverFnTransportErrorClientRuntime } from "./entries/client.js";
|
|
33
34
|
import { transformFarmRouteActionClients } from "./route-action-transform.js";
|
|
34
|
-
import { transformFarmServerFns } from "./server-fn-transform.js";
|
|
35
|
+
import { createFarmServerFnBoundaryModule, isFarmServerFnBoundaryId, transformFarmServerFns, } from "./server-fn-transform.js";
|
|
35
36
|
import { transformAutomaticOptimizedBoundaries } from "./automatic-optimized-boundary.js";
|
|
36
37
|
import { resolveRscBuildOutputPath } from "./build-paths.js";
|
|
38
|
+
import { FARM_RSC_MOBILE_CLIENT_ENTRY_NAME, createFarmRscMobileClientManifestPlugin, generateMobileClientEntry, removeFarmRscMobileClientManifest, } from "./mobile-client.js";
|
|
39
|
+
import { rscPrivateClientSourcemaps } from "./client-sourcemaps.js";
|
|
40
|
+
import { findDocumentLayouts, findRouteFiles } from "./document-layouts.js";
|
|
37
41
|
import { assertRscPackageCompatibility } from "./compatibility.js";
|
|
38
42
|
import { sendRscDevelopmentResponse } from "./dev-response.js";
|
|
39
|
-
import { loadRscMiddlewareConfigModule } from "./middleware-config-module.js";
|
|
43
|
+
import { loadRscConfigPropertyModule, loadRscMiddlewareConfigModule, } from "./middleware-config-module.js";
|
|
40
44
|
import fs from "fs/promises";
|
|
41
45
|
import path from "path";
|
|
42
46
|
import { devServableFileExists } from "../dev-static.js";
|
|
@@ -46,17 +50,21 @@ import { createRequire } from "node:module";
|
|
|
46
50
|
// Use API and middleware plugins from @farm.js/core (require so CJS build resolves when ESM .mjs is missing)
|
|
47
51
|
const require_ = createRequire(import.meta.url);
|
|
48
52
|
const { farmApiPlugin } = require_("@farm.js/core");
|
|
53
|
+
const { FARM_VERSION } = require_("@farm.js/core/version");
|
|
49
54
|
const { farmMiddlewarePlugin } = require_("@farm.js/core/middleware");
|
|
50
55
|
const { resolveServerActionsConfig, validateServerActionRequest, createServerActionRequestErrorResponse, } = require_("@farm.js/core/server-action-security");
|
|
51
56
|
const { normalizeFarmDeploymentId } = require_("@farm.js/core/deployment");
|
|
52
|
-
const { getFarmLayerAliases, getFarmSourceRoots, resolveFarmLayers } = require_("@farm.js/core/server");
|
|
53
|
-
const {
|
|
57
|
+
const { getFarmLayerAliases, getFarmSourceRoots, resolveFarmLayers, resolveFarmMCPConfig, resolveFarmMCPPlugin, } = require_("@farm.js/core/server");
|
|
58
|
+
const { readNodeRequestBody, resolveFarmServerConfig, resolveFarmI18nConfig, createFarmRequestBodyErrorResponse, createDefaultErrorMarkup, resolveFarmLlmsTxtConfig, } = require_("@farm.js/core/internal/production-runtime");
|
|
54
59
|
const { isFarmAPIPathname } = require_("@farm.js/core/api/runtime");
|
|
55
60
|
const { resolveFarmAPIConfig, resolveFarmAPIServerBasePath } = require_("@farm.js/core/api");
|
|
56
61
|
const { getResolvedEnv } = require_("@farm.js/core/env");
|
|
57
62
|
export { buildRscNitro, waitForRscManifest, waitForRscOutputs } from "./nitro-build.js";
|
|
58
63
|
import { registerRscNitroRuntimePackage } from "./nitro-build.js";
|
|
59
64
|
export { default as nitro } from "./vite-plugin-nitro.js";
|
|
65
|
+
const PAGE_FILE = /^page\.(tsx|jsx|ts|js)$/;
|
|
66
|
+
/** Packages the generated RSC entries import that belong to this plugin, not to the app. */
|
|
67
|
+
const PLUGIN_OWNED_ENTRY_IMPORTS = ["rsc-html-stream/server", "rsc-html-stream/client"];
|
|
60
68
|
/**
|
|
61
69
|
* Define a Farm.js RSC configuration
|
|
62
70
|
* This is the recommended way to configure your RSC app
|
|
@@ -80,6 +88,11 @@ export function defineConfig(config = {}) {
|
|
|
80
88
|
serverActions: config.serverActions,
|
|
81
89
|
deploymentId: config.deploymentId,
|
|
82
90
|
generateBuildId: config.generateBuildId,
|
|
91
|
+
md: config.md,
|
|
92
|
+
agent: config.agent,
|
|
93
|
+
mcp: config.mcp,
|
|
94
|
+
middleware: config.middleware,
|
|
95
|
+
images: config.images,
|
|
83
96
|
// Vite server configuration
|
|
84
97
|
server: {
|
|
85
98
|
...config.server,
|
|
@@ -88,22 +101,28 @@ export function defineConfig(config = {}) {
|
|
|
88
101
|
},
|
|
89
102
|
// Custom logger to hide Vite's default startup banner
|
|
90
103
|
customLogger: createFarmLogger(port, debug),
|
|
91
|
-
// Configure esbuild for JSX transformation
|
|
92
|
-
esbuild: {
|
|
93
|
-
jsx: "automatic",
|
|
94
|
-
jsxImportSource: "react",
|
|
95
|
-
},
|
|
96
104
|
plugins: [
|
|
97
105
|
farmMiddlewarePlugin({
|
|
98
106
|
srcDir: config.srcDir ?? "src",
|
|
99
107
|
basePath: config.basePath ?? "/",
|
|
108
|
+
// API routes in development run through this plugin's middleware, not the RSC entry's.
|
|
109
|
+
middleware: config.middleware,
|
|
100
110
|
debug,
|
|
101
111
|
}),
|
|
102
112
|
farmApiPlugin({
|
|
103
113
|
srcDir: config.srcDir ?? "src",
|
|
114
|
+
// The production entry serves API routes from the routes directory; so does development.
|
|
115
|
+
apiDir: path.join(config.srcDir ?? "src", config.routesDir === undefined ? "app" : config.routesDir.trim(), "api"),
|
|
104
116
|
debug,
|
|
105
117
|
bodySizeLimit: config.server?.bodySizeLimit,
|
|
118
|
+
// The dev API server mounts the MCP endpoint, as core's does.
|
|
119
|
+
...(config.mcp ? { plugins: ({ root }) => resolveRscMCPPlugins(config.mcp, root) } : {}),
|
|
106
120
|
}),
|
|
121
|
+
// localFont() from @farm.js/core/font, with its CSS carried by the bundler: this pipeline
|
|
122
|
+
// has no step that merges font CSS into a global stylesheet.
|
|
123
|
+
farmFontImportsPlugin({ basePath: config.basePath ?? "/", importCss: true }),
|
|
124
|
+
// Static image imports as { src, width, height }, which <Image> sizes from.
|
|
125
|
+
farmImageImportsPlugin(),
|
|
107
126
|
farmRsc({
|
|
108
127
|
debug,
|
|
109
128
|
encryptActions: config.encryptActions,
|
|
@@ -111,6 +130,7 @@ export function defineConfig(config = {}) {
|
|
|
111
130
|
deploymentId: config.deploymentId,
|
|
112
131
|
routesDir: config.routesDir,
|
|
113
132
|
entries: config.entries,
|
|
133
|
+
mobileClient: config.mobileClient,
|
|
114
134
|
}),
|
|
115
135
|
...(Array.isArray(config.plugins) ? config.plugins : []),
|
|
116
136
|
],
|
|
@@ -180,10 +200,16 @@ const VIRTUAL_PREFIX = "\0";
|
|
|
180
200
|
const VIRTUAL_RSC_ENTRY = "virtual:@farm.js/rsc/entry-rsc";
|
|
181
201
|
const VIRTUAL_SSR_ENTRY = "virtual:@farm.js/rsc/entry-ssr";
|
|
182
202
|
const VIRTUAL_CLIENT_ENTRY = "virtual:@farm.js/rsc/entry-client";
|
|
203
|
+
const VIRTUAL_MOBILE_CLIENT_ENTRY = "virtual:@farm.js/rsc/entry-mobile";
|
|
204
|
+
/** The browser entry, as the client build's `index` input names it. */
|
|
205
|
+
const RSC_CLIENT_ENTRY = "./.farm/rsc-entries/entry.browser.tsx";
|
|
206
|
+
/** The mobile client entry a build of an app with a `mobile` block adds. */
|
|
207
|
+
const RSC_MOBILE_CLIENT_ENTRY = "./.farm/rsc-entries/entry.mobile.tsx";
|
|
183
208
|
const VIRTUAL_HYDRATE_ENTRY = "virtual:@farm.js/rsc/hydrate";
|
|
184
209
|
const OPTIMIZED_BOUNDARY_ADAPTER = "@farm.js/plugin/rsc/optimized-boundary";
|
|
185
210
|
const STRATA_PACKAGE = "@farming-labs/strata";
|
|
186
211
|
const RSC_MIDDLEWARE_CONFIG_QUERY = "?farm-rsc-middleware";
|
|
212
|
+
const RSC_MCP_CONFIG_QUERY = "?farm-rsc-mcp";
|
|
187
213
|
const FARM_CORE_PACKAGE_ROOT = path.resolve(path.dirname(require_.resolve("@farm.js/core")), "..");
|
|
188
214
|
const FARM_CONFIG_FILENAMES = [
|
|
189
215
|
"farm.config.ts",
|
|
@@ -228,6 +254,19 @@ async function findFarmConfigPath(root) {
|
|
|
228
254
|
}
|
|
229
255
|
return null;
|
|
230
256
|
}
|
|
257
|
+
/** Resolves `mcp` for an RSC app, rejecting what the RSC server cannot serve yet. */
|
|
258
|
+
function resolveRscMCPConfig(input) {
|
|
259
|
+
const config = resolveFarmMCPConfig(input);
|
|
260
|
+
if (config.enabled && config.oauth) {
|
|
261
|
+
throw new Error("[Farm.js] mcp.oauth is not supported in RSC apps yet: the RSC server does not serve " +
|
|
262
|
+
"the protected-resource metadata. Remove oauth, or validate tokens in mcp.authorize.");
|
|
263
|
+
}
|
|
264
|
+
return config;
|
|
265
|
+
}
|
|
266
|
+
async function resolveRscMCPPlugins(input, root) {
|
|
267
|
+
const plugin = await resolveFarmMCPPlugin(resolveRscMCPConfig(input), { root });
|
|
268
|
+
return plugin ? [plugin] : [];
|
|
269
|
+
}
|
|
231
270
|
async function resolveMiddlewareConfigPaths(root, layers) {
|
|
232
271
|
const paths = (layers ?? []).flatMap((layer) => layer.configFile ? [path.resolve(layer.configFile)] : []);
|
|
233
272
|
const projectConfigPath = await findFarmConfigPath(root);
|
|
@@ -235,11 +274,50 @@ async function resolveMiddlewareConfigPaths(root, layers) {
|
|
|
235
274
|
paths.push(projectConfigPath);
|
|
236
275
|
return [...new Set(paths)];
|
|
237
276
|
}
|
|
277
|
+
// Vite's default config names: `defineConfig` from this package is written in one of them.
|
|
278
|
+
const VITE_CONFIG_FILENAMES = [
|
|
279
|
+
"vite.config.js",
|
|
280
|
+
"vite.config.mjs",
|
|
281
|
+
"vite.config.ts",
|
|
282
|
+
"vite.config.cjs",
|
|
283
|
+
"vite.config.mts",
|
|
284
|
+
"vite.config.cts",
|
|
285
|
+
];
|
|
286
|
+
async function findViteConfigPath(root) {
|
|
287
|
+
for (const fileName of VITE_CONFIG_FILENAMES) {
|
|
288
|
+
const candidate = path.join(root, fileName);
|
|
289
|
+
try {
|
|
290
|
+
if ((await fs.stat(candidate)).isFile())
|
|
291
|
+
return candidate;
|
|
292
|
+
}
|
|
293
|
+
catch {
|
|
294
|
+
// Continue checking supported config names.
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
return null;
|
|
298
|
+
}
|
|
238
299
|
function isOptimizedBoundaryModule(id) {
|
|
239
300
|
return (id === OPTIMIZED_BOUNDARY_ADAPTER ||
|
|
240
301
|
id === STRATA_PACKAGE ||
|
|
241
302
|
id.startsWith(`${STRATA_PACKAGE}/`));
|
|
242
303
|
}
|
|
304
|
+
/** The development error page for a failed RSC render: core's error page, with the real error. */
|
|
305
|
+
function createRscDevErrorDocument(error, method, pathname) {
|
|
306
|
+
const failure = error instanceof Error ? error : new Error(String(error));
|
|
307
|
+
const markup = createDefaultErrorMarkup({
|
|
308
|
+
statusCode: 500,
|
|
309
|
+
requestPath: pathname,
|
|
310
|
+
method,
|
|
311
|
+
message: failure.message,
|
|
312
|
+
errorName: failure.name,
|
|
313
|
+
stack: failure.stack,
|
|
314
|
+
development: true,
|
|
315
|
+
mode: "development",
|
|
316
|
+
farmVersion: FARM_VERSION,
|
|
317
|
+
nodeVersion: process.version,
|
|
318
|
+
});
|
|
319
|
+
return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>500 · Farm.js</title></head><body>${markup}</body></html>`;
|
|
320
|
+
}
|
|
243
321
|
function resolveOptimizedBoundaryRuntimeRoot() {
|
|
244
322
|
try {
|
|
245
323
|
return path.dirname(require_.resolve(`${STRATA_PACKAGE}/package.json`));
|
|
@@ -450,7 +528,10 @@ export default function farmRsc(options = {}) {
|
|
|
450
528
|
// Context passed to entry generators
|
|
451
529
|
let entryContext;
|
|
452
530
|
let rscBuildRoot;
|
|
531
|
+
/** The app root, when this build adds the mobile client entry. */
|
|
532
|
+
let mobileClientRoot;
|
|
453
533
|
const middlewareConfigModules = new Map();
|
|
534
|
+
let mcpConfigCandidates = null;
|
|
454
535
|
// Store for debugging
|
|
455
536
|
const debug = options.debug ?? false;
|
|
456
537
|
const automaticDeploymentId = `build-${Date.now()}`;
|
|
@@ -540,14 +621,44 @@ export default function farmRsc(options = {}) {
|
|
|
540
621
|
};
|
|
541
622
|
return [
|
|
542
623
|
farmEnvironmentFunctionsPlugin(),
|
|
624
|
+
rscPrivateClientSourcemaps(),
|
|
625
|
+
createFarmRscMobileClientManifestPlugin(() => mobileClientRoot),
|
|
543
626
|
{
|
|
544
627
|
name: "@farm.js/plugin/rsc:middleware-config",
|
|
545
628
|
enforce: "pre",
|
|
546
629
|
resolveId(id) {
|
|
547
|
-
if (!id.endsWith(RSC_MIDDLEWARE_CONFIG_QUERY))
|
|
630
|
+
if (!id.endsWith(RSC_MIDDLEWARE_CONFIG_QUERY) && !id.endsWith(RSC_MCP_CONFIG_QUERY)) {
|
|
548
631
|
return null;
|
|
632
|
+
}
|
|
549
633
|
return id.replace(/\\/g, "/");
|
|
550
634
|
},
|
|
635
|
+
// The MCP config is read from the Vite config file too, whose path is
|
|
636
|
+
// only known here. Entries are generated on load, after this runs.
|
|
637
|
+
async configResolved(resolved) {
|
|
638
|
+
if (!mcpConfigCandidates || !entryContext)
|
|
639
|
+
return;
|
|
640
|
+
const configPaths = [...mcpConfigCandidates];
|
|
641
|
+
if (resolved.configFile)
|
|
642
|
+
configPaths.push(path.resolve(resolved.configFile));
|
|
643
|
+
const mcpConfigPaths = [];
|
|
644
|
+
for (const configPath of new Set(configPaths)) {
|
|
645
|
+
const extracted = await loadRscConfigPropertyModule(configPath, "mcp");
|
|
646
|
+
if (extracted.kind === "unsupported") {
|
|
647
|
+
throw new Error(`[Farm.js] Cannot read mcp for the RSC server from ${configPath}: ${extracted.reason}. ` +
|
|
648
|
+
"Declare mcp directly in defineConfig({ mcp: ... }).");
|
|
649
|
+
}
|
|
650
|
+
if (extracted.kind === "absent")
|
|
651
|
+
continue;
|
|
652
|
+
const moduleId = `${configPath.replace(/\\/g, "/")}${RSC_MCP_CONFIG_QUERY}`;
|
|
653
|
+
middlewareConfigModules.set(moduleId, extracted.code);
|
|
654
|
+
mcpConfigPaths.push(moduleId);
|
|
655
|
+
}
|
|
656
|
+
if (mcpConfigPaths.length === 0) {
|
|
657
|
+
throw new Error("[Farm.js] The RSC server could not find the mcp config. " +
|
|
658
|
+
"Declare mcp directly in defineConfig({ mcp: ... }) in your Vite or Farm config file.");
|
|
659
|
+
}
|
|
660
|
+
entryContext.mcpConfigPaths = mcpConfigPaths;
|
|
661
|
+
},
|
|
551
662
|
load(id) {
|
|
552
663
|
return middlewareConfigModules.get(id.replace(/\\/g, "/")) ?? null;
|
|
553
664
|
},
|
|
@@ -585,7 +696,15 @@ export default function farmRsc(options = {}) {
|
|
|
585
696
|
async config(config, env) {
|
|
586
697
|
const c = config;
|
|
587
698
|
// Check if user enabled RSC in their config
|
|
588
|
-
|
|
699
|
+
const serverComponents = c.experimental?.serverComponents;
|
|
700
|
+
if (typeof serverComponents === "object" &&
|
|
701
|
+
serverComponents !== null &&
|
|
702
|
+
serverComponents.mode !== "rsc") {
|
|
703
|
+
throw new Error(`[Farm.js] @farm.js/plugin/rsc runs the "rsc" engine; experimental.serverComponents.mode "${String(serverComponents.mode)}" is not supported here.`);
|
|
704
|
+
}
|
|
705
|
+
rscEnabled =
|
|
706
|
+
serverComponents === true ||
|
|
707
|
+
(typeof serverComponents === "object" && serverComponents !== null);
|
|
589
708
|
actionsEnabled = c.experimental?.serverActions === true;
|
|
590
709
|
bodySizeLimit = resolveFarmServerConfig(c.server).bodySizeLimit;
|
|
591
710
|
optimizedBoundaryEnabled = c.experimental?.optimizedBoundary === true;
|
|
@@ -612,11 +731,19 @@ export default function farmRsc(options = {}) {
|
|
|
612
731
|
Object.assign(c, layerResolution.config);
|
|
613
732
|
}
|
|
614
733
|
middlewareConfigModules.clear();
|
|
734
|
+
// The config files mcp is read from at runtime; the Vite config file is
|
|
735
|
+
// added once it is known, in configResolved.
|
|
736
|
+
mcpConfigCandidates = resolveRscMCPConfig(c.mcp).enabled
|
|
737
|
+
? await resolveMiddlewareConfigPaths(root, c.layers)
|
|
738
|
+
: null;
|
|
615
739
|
const middlewareConfigPaths = [];
|
|
616
740
|
if (hasFarmMiddlewareConfig(c.middleware)) {
|
|
617
741
|
const configPaths = await resolveMiddlewareConfigPaths(root, c.layers);
|
|
742
|
+
const viteConfigPath = await findViteConfigPath(root);
|
|
743
|
+
if (viteConfigPath)
|
|
744
|
+
configPaths.push(viteConfigPath);
|
|
618
745
|
if (configPaths.length === 0) {
|
|
619
|
-
throw new Error("[Farm.js] RSC config middleware requires an importable farm.config file. " +
|
|
746
|
+
throw new Error("[Farm.js] RSC config middleware requires an importable farm.config or vite.config file. " +
|
|
620
747
|
"Move the middleware to farm.config.ts or src/app/middleware.ts.");
|
|
621
748
|
}
|
|
622
749
|
for (const configPath of configPaths) {
|
|
@@ -643,6 +770,7 @@ export default function farmRsc(options = {}) {
|
|
|
643
770
|
env: getResolvedEnv(),
|
|
644
771
|
});
|
|
645
772
|
const srcDir = c.srcDir ?? "src";
|
|
773
|
+
const clientOptimizeDeps = resolveFarmClientOptimizeDeps(path.resolve(root, srcDir), root);
|
|
646
774
|
const outDir = c.outDir ?? "dist";
|
|
647
775
|
const deploymentId = normalizeFarmDeploymentId(options.deploymentId ||
|
|
648
776
|
c.deploymentId ||
|
|
@@ -677,8 +805,61 @@ export default function farmRsc(options = {}) {
|
|
|
677
805
|
: `/${projectSourceDir}${routeSuffix}`;
|
|
678
806
|
return { name: source.name, base, glob: base };
|
|
679
807
|
});
|
|
808
|
+
// Each page's rendering directive and whether its source reads request state, which the
|
|
809
|
+
// runtime cannot see from module exports: the same baked input core's server merges.
|
|
810
|
+
// Later roots override earlier ones, as the entry's merged page map does.
|
|
811
|
+
const pageRenderingDirectives = {};
|
|
812
|
+
for (const source of getFarmSourceRoots(c)) {
|
|
813
|
+
const routesRoot = path.resolve(root, source.srcDir, configuredRoutesDir);
|
|
814
|
+
for (const { key, file } of await findRouteFiles(routesRoot, (name) => PAGE_FILE.test(name))) {
|
|
815
|
+
const directive = readRouteRenderingDirectiveFromFile(file);
|
|
816
|
+
if (directive)
|
|
817
|
+
pageRenderingDirectives[key] = directive;
|
|
818
|
+
else
|
|
819
|
+
delete pageRenderingDirectives[key];
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
// Root layouts that render <html> own the document (Next.js's root layout contract).
|
|
823
|
+
const documentLayouts = [
|
|
824
|
+
...new Set((await Promise.all(getFarmSourceRoots(c).map((source) => findDocumentLayouts(path.resolve(root, source.srcDir, configuredRoutesDir))))).flat()),
|
|
825
|
+
];
|
|
826
|
+
// The same images contract as core: without Sharp, "auto" keeps original URLs
|
|
827
|
+
// (provider "none") instead of pointing <Image> at an optimizer that cannot run.
|
|
828
|
+
const nitroPreset = process.env.NITRO_PRESET || "vercel";
|
|
829
|
+
const imageConfig = resolveFarmImageConfig(resolveFarmImageProviderForRuntime(c.images, {
|
|
830
|
+
root,
|
|
831
|
+
preset: nitroPreset,
|
|
832
|
+
dev: env.command === "serve",
|
|
833
|
+
}));
|
|
834
|
+
const publicImageConfig = getPublicFarmImageConfig(imageConfig);
|
|
835
|
+
// An app with a `mobile` block (RFC 0004): a build adds the mobile entry, and
|
|
836
|
+
// `farm dev --mobile` makes the browser entry itself the mobile client.
|
|
837
|
+
const mobileClient = options.mobileClient === "entry" && env.command === "build"
|
|
838
|
+
? "entry"
|
|
839
|
+
: options.mobileClient === "inline" && env.command === "serve"
|
|
840
|
+
? "inline"
|
|
841
|
+
: undefined;
|
|
842
|
+
mobileClientRoot = mobileClient === "entry" ? root : undefined;
|
|
843
|
+
// A mobile client from an earlier build must not outlive the `mobile` block.
|
|
844
|
+
if (env.command === "build" && mobileClient !== "entry") {
|
|
845
|
+
removeFarmRscMobileClientManifest(root);
|
|
846
|
+
}
|
|
847
|
+
// Development always optimizes with Sharp, as core's dev server does.
|
|
848
|
+
const imageRuntime = env.command === "serve"
|
|
849
|
+
? imageConfig.provider === "none"
|
|
850
|
+
? "none"
|
|
851
|
+
: "node"
|
|
852
|
+
: resolveFarmImageServerRuntime(imageConfig, nitroPreset);
|
|
680
853
|
// Build context for entry generators
|
|
681
854
|
entryContext = {
|
|
855
|
+
documentLayouts,
|
|
856
|
+
pageRenderingDirectives,
|
|
857
|
+
images: {
|
|
858
|
+
config: imageConfig,
|
|
859
|
+
public: publicImageConfig,
|
|
860
|
+
path: imageConfig.path,
|
|
861
|
+
runtime: imageRuntime,
|
|
862
|
+
},
|
|
682
863
|
srcDir,
|
|
683
864
|
outDir,
|
|
684
865
|
basePath: c.basePath ?? "/",
|
|
@@ -693,6 +874,9 @@ export default function farmRsc(options = {}) {
|
|
|
693
874
|
allowedOrigins: options.serverActions?.allowedOrigins ?? c.serverActions?.allowedOrigins,
|
|
694
875
|
}),
|
|
695
876
|
deploymentId,
|
|
877
|
+
markdown: resolveMarkdownConfig(c.md),
|
|
878
|
+
// Core's default for an app without docs: llms.txt on, llms-full.txt off.
|
|
879
|
+
llmsTxt: resolveFarmLlmsTxtConfig(c.agent?.llmsTxt ?? { full: false }),
|
|
696
880
|
// Resolved the same way core resolves it for the config, so RSC and
|
|
697
881
|
// non-RSC apps match middleware against the same pathname.
|
|
698
882
|
i18n: resolveFarmI18nConfig(c.i18n, {
|
|
@@ -705,6 +889,7 @@ export default function farmRsc(options = {}) {
|
|
|
705
889
|
debug,
|
|
706
890
|
development: env.command === "serve",
|
|
707
891
|
clientCachePersistence: generateClientCachePersistenceCode(resolveFarmClientCacheAdapterEntry(root, c.cache)),
|
|
892
|
+
mobileClient,
|
|
708
893
|
};
|
|
709
894
|
logInfo(`srcDir: ${entryContext.srcDir}, outDir: ${entryContext.outDir}`);
|
|
710
895
|
// Write real entry files so @vitejs/plugin-rsc can use file-based entries.
|
|
@@ -715,6 +900,9 @@ export default function farmRsc(options = {}) {
|
|
|
715
900
|
await fs.writeFile(entryRscPath, generateRscEntry(entryContext));
|
|
716
901
|
await fs.writeFile(entrySsrPath, generateSsrEntry(entryContext));
|
|
717
902
|
await fs.writeFile(entryClientPath, generateClientEntry(entryContext));
|
|
903
|
+
if (mobileClient === "entry") {
|
|
904
|
+
await fs.writeFile(path.join(entriesDir, "entry.mobile.tsx"), generateMobileClientEntry(RSC_CLIENT_ENTRY));
|
|
905
|
+
}
|
|
718
906
|
await fs.writeFile(path.join(entriesDir, "error-fallback.tsx"), generateErrorFallbackEntry());
|
|
719
907
|
logInfo(`Wrote RSC entries to ${entriesDir}`);
|
|
720
908
|
// User must add rsc({ entries: { rsc, ssr, client } }) to config.plugins so the RSC plugin
|
|
@@ -722,7 +910,7 @@ export default function farmRsc(options = {}) {
|
|
|
722
910
|
// Entry paths (relative to root) so Vite runs rsc/ssr/client builds (not index.html).
|
|
723
911
|
const entryRsc = "./.farm/rsc-entries/entry.rsc.tsx";
|
|
724
912
|
const entrySsr = "./.farm/rsc-entries/entry.ssr.tsx";
|
|
725
|
-
const entryClient =
|
|
913
|
+
const entryClient = RSC_CLIENT_ENTRY;
|
|
726
914
|
// Resolve @farm.js/core so Vite (and rsc/ssr envs) can load it when app code imports it (fixes "Failed to resolve entry" in dev).
|
|
727
915
|
let farmCorePath = null;
|
|
728
916
|
try {
|
|
@@ -744,6 +932,7 @@ export default function farmRsc(options = {}) {
|
|
|
744
932
|
builder: { sharedConfigBuild: true },
|
|
745
933
|
define: {
|
|
746
934
|
__FARM_API_BASE_URL__: JSON.stringify(api.baseURL),
|
|
935
|
+
__FARM_IMAGE_CONFIG__: JSON.stringify(entryContext.images?.public),
|
|
747
936
|
},
|
|
748
937
|
ssr: {
|
|
749
938
|
external: [
|
|
@@ -767,6 +956,21 @@ export default function farmRsc(options = {}) {
|
|
|
767
956
|
resolve: {
|
|
768
957
|
dedupe: ["react", "react-dom", "react-server-dom-webpack"],
|
|
769
958
|
alias: [
|
|
959
|
+
// The generated entries import the plugin's own dependencies; resolve them from here
|
|
960
|
+
// so an app (strict pnpm layout) does not have to install them itself.
|
|
961
|
+
...PLUGIN_OWNED_ENTRY_IMPORTS.flatMap((specifier) => {
|
|
962
|
+
try {
|
|
963
|
+
return [
|
|
964
|
+
{
|
|
965
|
+
find: new RegExp(`^${specifier.replace(/[/.]/g, "\\$&")}$`),
|
|
966
|
+
replacement: require_.resolve(specifier),
|
|
967
|
+
},
|
|
968
|
+
];
|
|
969
|
+
}
|
|
970
|
+
catch {
|
|
971
|
+
return [];
|
|
972
|
+
}
|
|
973
|
+
}),
|
|
770
974
|
...Object.entries(layerAliases).map(([find, replacement]) => ({
|
|
771
975
|
find,
|
|
772
976
|
replacement,
|
|
@@ -809,10 +1013,11 @@ export default function farmRsc(options = {}) {
|
|
|
809
1013
|
: []),
|
|
810
1014
|
],
|
|
811
1015
|
},
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
1016
|
+
// Vite 8 compiles with oxc, which already uses the automatic runtime;
|
|
1017
|
+
// setting esbuild there only prints a "both options were set" warning.
|
|
1018
|
+
...(this?.meta?.rolldownVersion
|
|
1019
|
+
? {}
|
|
1020
|
+
: { esbuild: { jsx: "automatic", jsxImportSource: "react" } }),
|
|
816
1021
|
...(c.layers?.length
|
|
817
1022
|
? {
|
|
818
1023
|
server: {
|
|
@@ -829,7 +1034,14 @@ export default function farmRsc(options = {}) {
|
|
|
829
1034
|
copyPublicDir: false,
|
|
830
1035
|
rollupOptions: { input: { index: entryRsc } },
|
|
831
1036
|
},
|
|
832
|
-
resolve: {
|
|
1037
|
+
resolve: {
|
|
1038
|
+
conditions: ["react-server", "node", "import"],
|
|
1039
|
+
// Strata is a native CommonJS loader: Node must load it, not Vite's
|
|
1040
|
+
// module runner. ssr.external does not reach this environment.
|
|
1041
|
+
...(optimizedBoundaryEnabled
|
|
1042
|
+
? { external: [STRATA_PACKAGE, `${STRATA_PACKAGE}/react-server`] }
|
|
1043
|
+
: {}),
|
|
1044
|
+
},
|
|
833
1045
|
},
|
|
834
1046
|
ssr: {
|
|
835
1047
|
build: {
|
|
@@ -842,9 +1054,35 @@ export default function farmRsc(options = {}) {
|
|
|
842
1054
|
client: {
|
|
843
1055
|
build: {
|
|
844
1056
|
outDir: `${outDir}/client`,
|
|
845
|
-
rollupOptions: {
|
|
1057
|
+
rollupOptions: {
|
|
1058
|
+
input: {
|
|
1059
|
+
index: entryClient,
|
|
1060
|
+
...(mobileClient === "entry"
|
|
1061
|
+
? { [FARM_RSC_MOBILE_CLIENT_ENTRY_NAME]: RSC_MOBILE_CLIENT_ENTRY }
|
|
1062
|
+
: {}),
|
|
1063
|
+
},
|
|
1064
|
+
},
|
|
846
1065
|
},
|
|
847
1066
|
resolve: { conditions: ["browser", "import"] },
|
|
1067
|
+
// Optimize what the browser entry needs up front. A dependency first
|
|
1068
|
+
// found on page load makes Vite re-optimize and reload, and until the
|
|
1069
|
+
// reload client components can see two React copies ("Invalid hook call").
|
|
1070
|
+
optimizeDeps: {
|
|
1071
|
+
include: [
|
|
1072
|
+
"react",
|
|
1073
|
+
"react/jsx-runtime",
|
|
1074
|
+
"react/jsx-dev-runtime",
|
|
1075
|
+
"react-dom",
|
|
1076
|
+
"react-dom/client",
|
|
1077
|
+
"rsc-html-stream/client",
|
|
1078
|
+
// Client components and the packages they use load only once a page renders
|
|
1079
|
+
// (client references), so they would be found late too.
|
|
1080
|
+
...clientOptimizeDeps.include,
|
|
1081
|
+
],
|
|
1082
|
+
// Packages whose react-server build re-exports a "use client" module: the plugin
|
|
1083
|
+
// loads that module from the package, so pre-bundling them would add a copy.
|
|
1084
|
+
exclude: clientOptimizeDeps.exclude,
|
|
1085
|
+
},
|
|
848
1086
|
},
|
|
849
1087
|
},
|
|
850
1088
|
};
|
|
@@ -913,10 +1151,22 @@ export default function farmRsc(options = {}) {
|
|
|
913
1151
|
{
|
|
914
1152
|
name: "@farm.js/plugin/rsc:server-fn-actions",
|
|
915
1153
|
enforce: "pre",
|
|
1154
|
+
// The "use server" boundary for a module whose server functions were
|
|
1155
|
+
// found without an explicit directive. Its exports come from the source
|
|
1156
|
+
// file on disk, never from the request, so nothing else can be named.
|
|
1157
|
+
async load(id) {
|
|
1158
|
+
if (!rscEnabled || !actionsEnabled || !isFarmServerFnBoundaryId(id))
|
|
1159
|
+
return null;
|
|
1160
|
+
const file = id.split("?", 1)[0];
|
|
1161
|
+
this.addWatchFile(file);
|
|
1162
|
+
const source = await fs.readFile(file, "utf8");
|
|
1163
|
+
return createFarmServerFnBoundaryModule(source, file) ?? "export {};\n";
|
|
1164
|
+
},
|
|
916
1165
|
transform(code, id) {
|
|
917
|
-
if (!rscEnabled || !actionsEnabled)
|
|
1166
|
+
if (!rscEnabled || !actionsEnabled || isFarmServerFnBoundaryId(id))
|
|
918
1167
|
return null;
|
|
919
|
-
const
|
|
1168
|
+
const environment = this.environment?.name;
|
|
1169
|
+
const result = transformFarmServerFns(code, id, { environment: environment ?? "rsc" });
|
|
920
1170
|
if (!result)
|
|
921
1171
|
return null;
|
|
922
1172
|
return {
|
|
@@ -983,6 +1233,9 @@ export default function farmRsc(options = {}) {
|
|
|
983
1233
|
if (source.includes("rsc-entries") && source.includes("entry.browser.tsx")) {
|
|
984
1234
|
return VIRTUAL_PREFIX + VIRTUAL_CLIENT_ENTRY;
|
|
985
1235
|
}
|
|
1236
|
+
if (source.includes("rsc-entries") && source.includes("entry.mobile.tsx")) {
|
|
1237
|
+
return VIRTUAL_PREFIX + VIRTUAL_MOBILE_CLIENT_ENTRY;
|
|
1238
|
+
}
|
|
986
1239
|
if (source.includes("rsc-entries") && source.includes("entry.rsc.tsx")) {
|
|
987
1240
|
return VIRTUAL_PREFIX + VIRTUAL_RSC_ENTRY;
|
|
988
1241
|
}
|
|
@@ -1013,6 +1266,9 @@ export default function farmRsc(options = {}) {
|
|
|
1013
1266
|
logInfo("Generating client entry");
|
|
1014
1267
|
return generateClientEntry(entryContext);
|
|
1015
1268
|
}
|
|
1269
|
+
if (id === VIRTUAL_PREFIX + VIRTUAL_MOBILE_CLIENT_ENTRY) {
|
|
1270
|
+
return generateMobileClientEntry(RSC_CLIENT_ENTRY);
|
|
1271
|
+
}
|
|
1016
1272
|
// Handle dynamic hydration entries
|
|
1017
1273
|
if (id.startsWith(VIRTUAL_PREFIX + "/@rsc-hydrate/")) {
|
|
1018
1274
|
const pagePath = id.replace(VIRTUAL_PREFIX + "/@rsc-hydrate", "");
|
|
@@ -1107,9 +1363,22 @@ if (document.readyState === 'loading') {
|
|
|
1107
1363
|
return;
|
|
1108
1364
|
}
|
|
1109
1365
|
logInfo("Dev server middleware ready");
|
|
1366
|
+
// The stylesheets the SSR environment's modules import, for entries/ssr.ts to link in the
|
|
1367
|
+
// head: a client component's CSS module otherwise arrives with its JavaScript, so its
|
|
1368
|
+
// server HTML is unstyled until scripts run. Removed when this server closes.
|
|
1369
|
+
const devStyles = () => collectDevStylesheetUrls(server.environments.ssr?.moduleGraph.idToModuleMap.values() ?? [], undefined, {
|
|
1370
|
+
cssModules: true,
|
|
1371
|
+
})
|
|
1372
|
+
.map((href) => `<link rel="stylesheet" href="${href.replace(/"/g, """)}" data-farm-dev-style>`)
|
|
1373
|
+
.join("");
|
|
1374
|
+
globalThis.__FARM_RSC_DEV_CLIENT_STYLES__ = devStyles;
|
|
1375
|
+
server.httpServer?.once("close", () => {
|
|
1376
|
+
const scope = globalThis;
|
|
1377
|
+
if (scope.__FARM_RSC_DEV_CLIENT_STYLES__ === devStyles)
|
|
1378
|
+
delete scope.__FARM_RSC_DEV_CLIENT_STYLES__;
|
|
1379
|
+
});
|
|
1110
1380
|
const serverStartTime = Date.now();
|
|
1111
1381
|
let bannerPrinted = false;
|
|
1112
|
-
const pageCache = new Map();
|
|
1113
1382
|
server.httpServer?.once("listening", () => {
|
|
1114
1383
|
if (bannerPrinted)
|
|
1115
1384
|
return;
|
|
@@ -1119,7 +1388,7 @@ if (document.readyState === 'loading') {
|
|
|
1119
1388
|
const port = typeof address === "object" && address ? address.port : 3000;
|
|
1120
1389
|
const colors = getColors();
|
|
1121
1390
|
console.log("");
|
|
1122
|
-
console.log(` ${colors.bold(colors.green("Farm.js"))} ${colors.dim(
|
|
1391
|
+
console.log(` ${colors.bold(colors.green("Farm.js"))} ${colors.dim(`v${FARM_VERSION}`)} ${colors.dim(`ready in ${elapsed}ms`)}`);
|
|
1123
1392
|
console.log("");
|
|
1124
1393
|
console.log(` ${colors.dim("➜")} ${colors.bold("Local:")} ${colors.cyan(`http://localhost:${port}/`)}`);
|
|
1125
1394
|
console.log(` ${colors.dim("➜")} ${colors.bold("Network:")} ${colors.dim("use --host to expose")}`);
|
|
@@ -1229,276 +1498,15 @@ if (document.readyState === 'loading') {
|
|
|
1229
1498
|
res.destroy(rscError instanceof Error ? rscError : new Error(String(rscError)));
|
|
1230
1499
|
return;
|
|
1231
1500
|
}
|
|
1232
|
-
//
|
|
1233
|
-
|
|
1234
|
-
const duration = Date.now() - startTime;
|
|
1235
|
-
logResponse(method, pathname, 500, duration);
|
|
1236
|
-
console.error("[Farm.js] RSC dev handler error:", rscError);
|
|
1237
|
-
res.statusCode = 500;
|
|
1238
|
-
res.setHeader("Content-Type", "text/html");
|
|
1239
|
-
res.end(`<!DOCTYPE html><html><head><title>Error</title></head><body><pre>${rscError.message}</pre></body></html>`);
|
|
1240
|
-
return;
|
|
1241
|
-
}
|
|
1242
|
-
}
|
|
1243
|
-
try {
|
|
1244
|
-
if (method !== "GET")
|
|
1245
|
-
return next();
|
|
1246
|
-
// Get middleware data from standalone middleware plugin
|
|
1247
|
-
const middlewareData = req.__FARM_MIDDLEWARE_DATA__ || {};
|
|
1248
|
-
// Build the glob pattern for discovering routes (Farm convention: src/app when routesDir unset)
|
|
1249
|
-
const srcDir = entryContext.srcDir;
|
|
1250
|
-
const appSegment = entryContext.routesDir === undefined ? "app" : entryContext.routesDir.trim();
|
|
1251
|
-
const glob = appSegment ? `/${srcDir}/${appSegment}` : `/${srcDir}`;
|
|
1252
|
-
// Find matching page file
|
|
1253
|
-
const normalized = pathname.replace(/\/$/, "") || "/";
|
|
1254
|
-
// Common page file patterns
|
|
1255
|
-
const possiblePaths = [
|
|
1256
|
-
`${glob}${normalized === "/" ? "" : normalized}/page.tsx`,
|
|
1257
|
-
`${glob}${normalized === "/" ? "" : normalized}/page.jsx`,
|
|
1258
|
-
`${glob}/page.tsx`,
|
|
1259
|
-
`${glob}/page.jsx`,
|
|
1260
|
-
];
|
|
1261
|
-
// Also check for dynamic routes by walking up the path
|
|
1262
|
-
const parts = normalized.split("/").filter(Boolean);
|
|
1263
|
-
for (let i = parts.length; i >= 0; i--) {
|
|
1264
|
-
const base = parts.slice(0, i).join("/");
|
|
1265
|
-
possiblePaths.push(base ? `${glob}/${base}/page.tsx` : `${glob}/page.tsx`);
|
|
1266
|
-
possiblePaths.push(base ? `${glob}/${base}/page.jsx` : `${glob}/page.jsx`);
|
|
1267
|
-
}
|
|
1268
|
-
let pageModule = null;
|
|
1269
|
-
let matchedPath = "";
|
|
1270
|
-
let layoutModule = null;
|
|
1271
|
-
// Try to find and load the page
|
|
1272
|
-
for (const pagePath of possiblePaths) {
|
|
1273
|
-
try {
|
|
1274
|
-
// Convert glob path to actual file path
|
|
1275
|
-
const actualPath = pagePath.startsWith("/") ? `.${pagePath}` : pagePath;
|
|
1276
|
-
if (pageCache.has(pagePath)) {
|
|
1277
|
-
pageModule = pageCache.get(pagePath);
|
|
1278
|
-
matchedPath = pagePath;
|
|
1279
|
-
break;
|
|
1280
|
-
}
|
|
1281
|
-
pageModule = await loadFarmDevModule(server, actualPath);
|
|
1282
|
-
if (pageModule?.default) {
|
|
1283
|
-
pageCache.set(pagePath, pageModule);
|
|
1284
|
-
matchedPath = pagePath;
|
|
1285
|
-
// Page loaded successfully
|
|
1286
|
-
break;
|
|
1287
|
-
}
|
|
1288
|
-
}
|
|
1289
|
-
catch (e) {
|
|
1290
|
-
// Page not found at this path, continue
|
|
1291
|
-
}
|
|
1292
|
-
}
|
|
1293
|
-
if (!pageModule?.default) {
|
|
1294
|
-
return next();
|
|
1295
|
-
}
|
|
1296
|
-
try {
|
|
1297
|
-
const layoutPath = `./${srcDir}${appSegment ? `/${appSegment}` : ""}/layout.tsx`;
|
|
1298
|
-
layoutModule = await loadFarmDevModule(server, layoutPath);
|
|
1299
|
-
}
|
|
1300
|
-
catch { }
|
|
1301
|
-
const React = await import("react");
|
|
1302
|
-
const ReactDOMServer = await import("react-dom/server");
|
|
1303
|
-
const Page = pageModule.default;
|
|
1304
|
-
const metadata = {
|
|
1305
|
-
title: typeof pageModule.metadata?.title === "string"
|
|
1306
|
-
? pageModule.metadata.title
|
|
1307
|
-
: layoutModule?.metadata?.title,
|
|
1308
|
-
description: typeof pageModule.metadata?.description === "string"
|
|
1309
|
-
? pageModule.metadata.description
|
|
1310
|
-
: layoutModule?.metadata?.description,
|
|
1311
|
-
};
|
|
1312
|
-
const Layout = layoutModule?.default;
|
|
1313
|
-
// Parse URL params (basic dynamic route support)
|
|
1314
|
-
const params = {};
|
|
1315
|
-
const searchParams = searchParamsToObject(resolveDevRequestURL(req).searchParams);
|
|
1316
|
-
// Render the page with middleware data
|
|
1317
|
-
const pageProps = {
|
|
1318
|
-
params,
|
|
1319
|
-
searchParams,
|
|
1320
|
-
// Middleware shared data is available to pages
|
|
1321
|
-
middlewareData,
|
|
1322
|
-
};
|
|
1323
|
-
// Helper to check if a function is async or returns a Promise
|
|
1324
|
-
// We need to actually call the function to detect this reliably
|
|
1325
|
-
// since transpiled async functions may not be detectable by constructor
|
|
1326
|
-
const isAsyncFunction = (fn) => {
|
|
1327
|
-
if (!fn)
|
|
1328
|
-
return false;
|
|
1329
|
-
// Check if it's an AsyncFunction
|
|
1330
|
-
if (fn.constructor?.name === "AsyncFunction")
|
|
1331
|
-
return true;
|
|
1332
|
-
// Check if function.toString() contains async
|
|
1333
|
-
try {
|
|
1334
|
-
const str = fn.toString();
|
|
1335
|
-
// Check for "async function" or "async (" patterns
|
|
1336
|
-
if (/^async\s/.test(str) || /^async\s*\(/.test(str))
|
|
1337
|
-
return true;
|
|
1338
|
-
}
|
|
1339
|
-
catch { }
|
|
1340
|
-
return false;
|
|
1341
|
-
};
|
|
1342
|
-
// Try to render the page - if it returns a Promise, it's async
|
|
1343
|
-
let pageContent;
|
|
1344
|
-
let isAsyncPage = isAsyncFunction(Page);
|
|
1345
|
-
try {
|
|
1346
|
-
const result = Page(pageProps);
|
|
1347
|
-
// Check if result is a Promise (thenable)
|
|
1348
|
-
if (result && typeof result.then === "function") {
|
|
1349
|
-
isAsyncPage = true;
|
|
1350
|
-
pageContent = await result;
|
|
1351
|
-
}
|
|
1352
|
-
else {
|
|
1353
|
-
// If it's not a Promise, it's a React element or we need to use createElement
|
|
1354
|
-
if (React.default.isValidElement(result)) {
|
|
1355
|
-
pageContent = result;
|
|
1356
|
-
}
|
|
1357
|
-
else {
|
|
1358
|
-
pageContent = React.default.createElement(Page, pageProps);
|
|
1359
|
-
}
|
|
1360
|
-
}
|
|
1361
|
-
}
|
|
1362
|
-
catch (e) {
|
|
1363
|
-
// If calling directly failed, use createElement
|
|
1364
|
-
pageContent = React.default.createElement(Page, pageProps);
|
|
1365
|
-
}
|
|
1366
|
-
// Check if Layout is async
|
|
1367
|
-
let isAsyncLayout = isAsyncFunction(Layout);
|
|
1368
|
-
// Wrap in layout if available
|
|
1369
|
-
let content = pageContent;
|
|
1370
|
-
if (Layout) {
|
|
1371
|
-
try {
|
|
1372
|
-
const layoutResult = Layout({ children: pageContent });
|
|
1373
|
-
if (layoutResult && typeof layoutResult.then === "function") {
|
|
1374
|
-
isAsyncLayout = true;
|
|
1375
|
-
content = await layoutResult;
|
|
1376
|
-
}
|
|
1377
|
-
else if (React.default.isValidElement(layoutResult)) {
|
|
1378
|
-
content = layoutResult;
|
|
1379
|
-
}
|
|
1380
|
-
else {
|
|
1381
|
-
content = React.default.createElement(Layout, null, pageContent);
|
|
1382
|
-
}
|
|
1383
|
-
}
|
|
1384
|
-
catch (e) {
|
|
1385
|
-
content = React.default.createElement(Layout, null, pageContent);
|
|
1386
|
-
}
|
|
1387
|
-
}
|
|
1388
|
-
// Create full HTML page
|
|
1389
|
-
const h = React.default.createElement;
|
|
1390
|
-
const isSyncPage = !isAsyncPage && !isAsyncLayout;
|
|
1391
|
-
// For sync pages we load preamble + vite client + hydrate in one script below; do not load vite-client in head so order is guaranteed.
|
|
1392
|
-
const routesDir = entryContext.routesDir === undefined ? "app" : entryContext.routesDir.trim();
|
|
1393
|
-
const routesPath = routesDir ? `/${routesDir}` : "";
|
|
1394
|
-
const headElements = [
|
|
1395
|
-
h("meta", { key: "charset", charSet: "utf-8" }),
|
|
1396
|
-
h("meta", {
|
|
1397
|
-
key: "viewport",
|
|
1398
|
-
name: "viewport",
|
|
1399
|
-
content: "width=device-width, initial-scale=1",
|
|
1400
|
-
}),
|
|
1401
|
-
metadata.title
|
|
1402
|
-
? h("title", { key: "title" }, metadata.title)
|
|
1403
|
-
: h("title", { key: "title" }, "Farm.js"),
|
|
1404
|
-
metadata.description
|
|
1405
|
-
? h("meta", {
|
|
1406
|
-
key: "description",
|
|
1407
|
-
name: "description",
|
|
1408
|
-
content: metadata.description,
|
|
1409
|
-
})
|
|
1410
|
-
: null,
|
|
1411
|
-
h("link", {
|
|
1412
|
-
key: "globals-css",
|
|
1413
|
-
rel: "stylesheet",
|
|
1414
|
-
href: `/${srcDir}${routesPath}/globals.css`,
|
|
1415
|
-
}),
|
|
1416
|
-
...(isSyncPage
|
|
1417
|
-
? []
|
|
1418
|
-
: [
|
|
1419
|
-
h("script", {
|
|
1420
|
-
key: "vite-client",
|
|
1421
|
-
type: "module",
|
|
1422
|
-
src: "/@vite/client",
|
|
1423
|
-
}),
|
|
1424
|
-
]),
|
|
1425
|
-
].filter(Boolean);
|
|
1426
|
-
// Create body elements
|
|
1427
|
-
// For async (server) pages, we don't hydrate the page itself - only client components within
|
|
1428
|
-
// For sync pages, we can hydrate the whole thing
|
|
1429
|
-
const bodyElements = [h("div", { key: "root", id: "root" }, content)];
|
|
1430
|
-
// Only add hydration script for sync pages (non-async)
|
|
1431
|
-
// When server actions are enabled, set __viteRscCallServer first so form submission works.
|
|
1432
|
-
if (actionsEnabled) {
|
|
1433
|
-
bodyElements.push(h("script", {
|
|
1434
|
-
key: "rsc-call-server",
|
|
1435
|
-
dangerouslySetInnerHTML: {
|
|
1436
|
-
__html: `(function(){if(typeof globalThis.__viteRscCallServer!=='function'){globalThis.__viteRscCallServer=function(){return Promise.reject(new Error('Farm.js: server actions not ready'));}}})();`,
|
|
1437
|
-
},
|
|
1438
|
-
}));
|
|
1439
|
-
}
|
|
1440
|
-
// Set React refresh preamble synchronously first so "use client" components don't throw when they load.
|
|
1441
|
-
if (!isAsyncPage && !isAsyncLayout) {
|
|
1442
|
-
bodyElements.push(h("script", {
|
|
1443
|
-
key: "preamble-sync",
|
|
1444
|
-
dangerouslySetInnerHTML: {
|
|
1445
|
-
__html: `window.__vite_plugin_react_preamble_installed__=true;window.$RefreshReg$=function(){};window.$RefreshSig$=function(){return function(t){return t;}};`,
|
|
1446
|
-
},
|
|
1447
|
-
}), h("script", {
|
|
1448
|
-
key: "page-props",
|
|
1449
|
-
dangerouslySetInnerHTML: {
|
|
1450
|
-
__html: `window.__PAGE_PROPS__ = ${JSON.stringify(pageProps)};`,
|
|
1451
|
-
},
|
|
1452
|
-
}), h("script", {
|
|
1453
|
-
key: "hydrate",
|
|
1454
|
-
type: "module",
|
|
1455
|
-
dangerouslySetInnerHTML: {
|
|
1456
|
-
__html: `import("/@react-refresh").then(m=>{m.default.injectIntoGlobalHook(window);return import("/@vite/client");}).then(()=>import(${JSON.stringify(`/@rsc-hydrate${normalized}`)}));`,
|
|
1457
|
-
},
|
|
1458
|
-
}));
|
|
1459
|
-
}
|
|
1460
|
-
else {
|
|
1461
|
-
// For async pages, we need to hydrate client component islands
|
|
1462
|
-
// Load a minimal script that finds and hydrates "use client" components
|
|
1463
|
-
bodyElements.push(h("script", {
|
|
1464
|
-
key: "client-islands",
|
|
1465
|
-
type: "module",
|
|
1466
|
-
dangerouslySetInnerHTML: {
|
|
1467
|
-
__html: `
|
|
1468
|
-
// Hydrate client component islands
|
|
1469
|
-
import '/@vite/client';
|
|
1470
|
-
|
|
1471
|
-
// Find all client components and hydrate them
|
|
1472
|
-
// The actual hydration is handled by @vitejs/plugin-rsc transforms
|
|
1473
|
-
`,
|
|
1474
|
-
},
|
|
1475
|
-
}));
|
|
1476
|
-
}
|
|
1477
|
-
const fullPage = h("html", { lang: "en" }, h("head", null, ...headElements), h("body", null, ...bodyElements));
|
|
1478
|
-
const html = "<!DOCTYPE html>" + ReactDOMServer.renderToString(fullPage);
|
|
1479
|
-
res.statusCode = 200;
|
|
1480
|
-
res.setHeader("Content-Type", "text/html");
|
|
1481
|
-
res.end(html);
|
|
1482
|
-
const duration = Date.now() - startTime;
|
|
1483
|
-
logResponse("GET", pathname, 200, duration);
|
|
1484
|
-
}
|
|
1485
|
-
catch (error) {
|
|
1501
|
+
// Show the failure. Rendering another page instead (the old legacy
|
|
1502
|
+
// SSR fallback) served the wrong page and hid the error.
|
|
1486
1503
|
const duration = Date.now() - startTime;
|
|
1487
|
-
logResponse(
|
|
1488
|
-
console.error(
|
|
1489
|
-
// Return error page
|
|
1504
|
+
logResponse(method, pathname, 500, duration);
|
|
1505
|
+
console.error(`[Farm.js] RSC render failed for ${method} ${pathname}:`, rscError);
|
|
1490
1506
|
res.statusCode = 500;
|
|
1491
|
-
res.setHeader("Content-Type", "text/html");
|
|
1492
|
-
res.
|
|
1493
|
-
|
|
1494
|
-
<html>
|
|
1495
|
-
<head><title>Error</title></head>
|
|
1496
|
-
<body style="font-family: system-ui; padding: 2rem; background: #1a1a2e; color: #eee;">
|
|
1497
|
-
<h1 style="color: #ff6b6b;">Error</h1>
|
|
1498
|
-
<pre style="background: #16213e; padding: 1rem; border-radius: 8px; overflow: auto;">${error.stack || error.message}</pre>
|
|
1499
|
-
</body>
|
|
1500
|
-
</html>
|
|
1501
|
-
`);
|
|
1507
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
1508
|
+
res.setHeader("Cache-Control", "no-store");
|
|
1509
|
+
res.end(createRscDevErrorDocument(rscError, method, pathname));
|
|
1502
1510
|
}
|
|
1503
1511
|
});
|
|
1504
1512
|
};
|