@farm.js/plugin 0.1.61 → 0.1.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.js +1 -1
  3. package/dist/middleware/index.d.ts +8 -1
  4. package/dist/middleware/index.d.ts.map +1 -1
  5. package/dist/middleware/index.js +16 -10
  6. package/dist/middleware/matching.d.ts +4 -2
  7. package/dist/middleware/matching.d.ts.map +1 -1
  8. package/dist/middleware/matching.js +7 -47
  9. package/dist/rsc/client-sourcemaps.d.ts +13 -0
  10. package/dist/rsc/client-sourcemaps.d.ts.map +1 -0
  11. package/dist/rsc/client-sourcemaps.js +52 -0
  12. package/dist/rsc/document-layouts.d.ts +16 -0
  13. package/dist/rsc/document-layouts.d.ts.map +1 -0
  14. package/dist/rsc/document-layouts.js +82 -0
  15. package/dist/rsc/entries/client.d.ts.map +1 -1
  16. package/dist/rsc/entries/client.js +92 -16
  17. package/dist/rsc/entries/rsc.d.ts.map +1 -1
  18. package/dist/rsc/entries/rsc.js +563 -45
  19. package/dist/rsc/entries/ssr.d.ts.map +1 -1
  20. package/dist/rsc/entries/ssr.js +7 -6
  21. package/dist/rsc/index.d.ts +38 -3
  22. package/dist/rsc/index.d.ts.map +1 -1
  23. package/dist/rsc/index.js +282 -292
  24. package/dist/rsc/middleware-config-module.d.ts +3 -0
  25. package/dist/rsc/middleware-config-module.d.ts.map +1 -1
  26. package/dist/rsc/middleware-config-module.js +41 -28
  27. package/dist/rsc/mobile-client.d.ts +67 -0
  28. package/dist/rsc/mobile-client.d.ts.map +1 -0
  29. package/dist/rsc/mobile-client.js +148 -0
  30. package/dist/rsc/nitro-build.d.ts.map +1 -1
  31. package/dist/rsc/nitro-build.js +268 -81
  32. package/dist/rsc/server-fn-transform.d.ts +1 -5
  33. package/dist/rsc/server-fn-transform.d.ts.map +1 -1
  34. package/dist/rsc/server-fn-transform.js +3 -338
  35. package/dist/rsc/types.d.ts +39 -0
  36. package/dist/rsc/types.d.ts.map +1 -1
  37. package/dist/rsc/vite-plugin-nitro.d.ts +2 -0
  38. package/dist/rsc/vite-plugin-nitro.d.ts.map +1 -1
  39. package/dist/rsc/vite-plugin-nitro.js +12 -2
  40. package/package.json +3 -3
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 { collectFarmClientPackageImports, farmFontImportsPlugin, farmImageImportsPlugin, generateClientCachePersistenceCode, getPublicFarmImageConfig, resolveFarmClientCacheAdapterEntry, 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 { searchParamsToObject, readNodeRequestBody, resolveFarmServerConfig, resolveFarmI18nConfig, createFarmRequestBodyErrorResponse, } = require_("@farm.js/core/internal/production-runtime");
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
- rscEnabled = c.experimental?.serverComponents === true;
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) {
@@ -677,8 +804,61 @@ export default function farmRsc(options = {}) {
677
804
  : `/${projectSourceDir}${routeSuffix}`;
678
805
  return { name: source.name, base, glob: base };
679
806
  });
807
+ // Each page's rendering directive and whether its source reads request state, which the
808
+ // runtime cannot see from module exports: the same baked input core's server merges.
809
+ // Later roots override earlier ones, as the entry's merged page map does.
810
+ const pageRenderingDirectives = {};
811
+ for (const source of getFarmSourceRoots(c)) {
812
+ const routesRoot = path.resolve(root, source.srcDir, configuredRoutesDir);
813
+ for (const { key, file } of await findRouteFiles(routesRoot, (name) => PAGE_FILE.test(name))) {
814
+ const directive = readRouteRenderingDirectiveFromFile(file);
815
+ if (directive)
816
+ pageRenderingDirectives[key] = directive;
817
+ else
818
+ delete pageRenderingDirectives[key];
819
+ }
820
+ }
821
+ // Root layouts that render <html> own the document (Next.js's root layout contract).
822
+ const documentLayouts = [
823
+ ...new Set((await Promise.all(getFarmSourceRoots(c).map((source) => findDocumentLayouts(path.resolve(root, source.srcDir, configuredRoutesDir))))).flat()),
824
+ ];
825
+ // The same images contract as core: without Sharp, "auto" keeps original URLs
826
+ // (provider "none") instead of pointing <Image> at an optimizer that cannot run.
827
+ const nitroPreset = process.env.NITRO_PRESET || "vercel";
828
+ const imageConfig = resolveFarmImageConfig(resolveFarmImageProviderForRuntime(c.images, {
829
+ root,
830
+ preset: nitroPreset,
831
+ dev: env.command === "serve",
832
+ }));
833
+ const publicImageConfig = getPublicFarmImageConfig(imageConfig);
834
+ // An app with a `mobile` block (RFC 0004): a build adds the mobile entry, and
835
+ // `farm dev --mobile` makes the browser entry itself the mobile client.
836
+ const mobileClient = options.mobileClient === "entry" && env.command === "build"
837
+ ? "entry"
838
+ : options.mobileClient === "inline" && env.command === "serve"
839
+ ? "inline"
840
+ : undefined;
841
+ mobileClientRoot = mobileClient === "entry" ? root : undefined;
842
+ // A mobile client from an earlier build must not outlive the `mobile` block.
843
+ if (env.command === "build" && mobileClient !== "entry") {
844
+ removeFarmRscMobileClientManifest(root);
845
+ }
846
+ // Development always optimizes with Sharp, as core's dev server does.
847
+ const imageRuntime = env.command === "serve"
848
+ ? imageConfig.provider === "none"
849
+ ? "none"
850
+ : "node"
851
+ : resolveFarmImageServerRuntime(imageConfig, nitroPreset);
680
852
  // Build context for entry generators
681
853
  entryContext = {
854
+ documentLayouts,
855
+ pageRenderingDirectives,
856
+ images: {
857
+ config: imageConfig,
858
+ public: publicImageConfig,
859
+ path: imageConfig.path,
860
+ runtime: imageRuntime,
861
+ },
682
862
  srcDir,
683
863
  outDir,
684
864
  basePath: c.basePath ?? "/",
@@ -693,6 +873,9 @@ export default function farmRsc(options = {}) {
693
873
  allowedOrigins: options.serverActions?.allowedOrigins ?? c.serverActions?.allowedOrigins,
694
874
  }),
695
875
  deploymentId,
876
+ markdown: resolveMarkdownConfig(c.md),
877
+ // Core's default for an app without docs: llms.txt on, llms-full.txt off.
878
+ llmsTxt: resolveFarmLlmsTxtConfig(c.agent?.llmsTxt ?? { full: false }),
696
879
  // Resolved the same way core resolves it for the config, so RSC and
697
880
  // non-RSC apps match middleware against the same pathname.
698
881
  i18n: resolveFarmI18nConfig(c.i18n, {
@@ -705,6 +888,7 @@ export default function farmRsc(options = {}) {
705
888
  debug,
706
889
  development: env.command === "serve",
707
890
  clientCachePersistence: generateClientCachePersistenceCode(resolveFarmClientCacheAdapterEntry(root, c.cache)),
891
+ mobileClient,
708
892
  };
709
893
  logInfo(`srcDir: ${entryContext.srcDir}, outDir: ${entryContext.outDir}`);
710
894
  // Write real entry files so @vitejs/plugin-rsc can use file-based entries.
@@ -715,6 +899,9 @@ export default function farmRsc(options = {}) {
715
899
  await fs.writeFile(entryRscPath, generateRscEntry(entryContext));
716
900
  await fs.writeFile(entrySsrPath, generateSsrEntry(entryContext));
717
901
  await fs.writeFile(entryClientPath, generateClientEntry(entryContext));
902
+ if (mobileClient === "entry") {
903
+ await fs.writeFile(path.join(entriesDir, "entry.mobile.tsx"), generateMobileClientEntry(RSC_CLIENT_ENTRY));
904
+ }
718
905
  await fs.writeFile(path.join(entriesDir, "error-fallback.tsx"), generateErrorFallbackEntry());
719
906
  logInfo(`Wrote RSC entries to ${entriesDir}`);
720
907
  // User must add rsc({ entries: { rsc, ssr, client } }) to config.plugins so the RSC plugin
@@ -722,7 +909,7 @@ export default function farmRsc(options = {}) {
722
909
  // Entry paths (relative to root) so Vite runs rsc/ssr/client builds (not index.html).
723
910
  const entryRsc = "./.farm/rsc-entries/entry.rsc.tsx";
724
911
  const entrySsr = "./.farm/rsc-entries/entry.ssr.tsx";
725
- const entryClient = "./.farm/rsc-entries/entry.browser.tsx";
912
+ const entryClient = RSC_CLIENT_ENTRY;
726
913
  // 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
914
  let farmCorePath = null;
728
915
  try {
@@ -744,6 +931,7 @@ export default function farmRsc(options = {}) {
744
931
  builder: { sharedConfigBuild: true },
745
932
  define: {
746
933
  __FARM_API_BASE_URL__: JSON.stringify(api.baseURL),
934
+ __FARM_IMAGE_CONFIG__: JSON.stringify(entryContext.images?.public),
747
935
  },
748
936
  ssr: {
749
937
  external: [
@@ -767,6 +955,21 @@ export default function farmRsc(options = {}) {
767
955
  resolve: {
768
956
  dedupe: ["react", "react-dom", "react-server-dom-webpack"],
769
957
  alias: [
958
+ // The generated entries import the plugin's own dependencies; resolve them from here
959
+ // so an app (strict pnpm layout) does not have to install them itself.
960
+ ...PLUGIN_OWNED_ENTRY_IMPORTS.flatMap((specifier) => {
961
+ try {
962
+ return [
963
+ {
964
+ find: new RegExp(`^${specifier.replace(/[/.]/g, "\\$&")}$`),
965
+ replacement: require_.resolve(specifier),
966
+ },
967
+ ];
968
+ }
969
+ catch {
970
+ return [];
971
+ }
972
+ }),
770
973
  ...Object.entries(layerAliases).map(([find, replacement]) => ({
771
974
  find,
772
975
  replacement,
@@ -809,10 +1012,11 @@ export default function farmRsc(options = {}) {
809
1012
  : []),
810
1013
  ],
811
1014
  },
812
- esbuild: {
813
- jsx: "automatic",
814
- jsxImportSource: "react",
815
- },
1015
+ // Vite 8 compiles with oxc, which already uses the automatic runtime;
1016
+ // setting esbuild there only prints a "both options were set" warning.
1017
+ ...(this?.meta?.rolldownVersion
1018
+ ? {}
1019
+ : { esbuild: { jsx: "automatic", jsxImportSource: "react" } }),
816
1020
  ...(c.layers?.length
817
1021
  ? {
818
1022
  server: {
@@ -829,7 +1033,14 @@ export default function farmRsc(options = {}) {
829
1033
  copyPublicDir: false,
830
1034
  rollupOptions: { input: { index: entryRsc } },
831
1035
  },
832
- resolve: { conditions: ["react-server", "node", "import"] },
1036
+ resolve: {
1037
+ conditions: ["react-server", "node", "import"],
1038
+ // Strata is a native CommonJS loader: Node must load it, not Vite's
1039
+ // module runner. ssr.external does not reach this environment.
1040
+ ...(optimizedBoundaryEnabled
1041
+ ? { external: [STRATA_PACKAGE, `${STRATA_PACKAGE}/react-server`] }
1042
+ : {}),
1043
+ },
833
1044
  },
834
1045
  ssr: {
835
1046
  build: {
@@ -842,9 +1053,32 @@ export default function farmRsc(options = {}) {
842
1053
  client: {
843
1054
  build: {
844
1055
  outDir: `${outDir}/client`,
845
- rollupOptions: { input: { index: entryClient } },
1056
+ rollupOptions: {
1057
+ input: {
1058
+ index: entryClient,
1059
+ ...(mobileClient === "entry"
1060
+ ? { [FARM_RSC_MOBILE_CLIENT_ENTRY_NAME]: RSC_MOBILE_CLIENT_ENTRY }
1061
+ : {}),
1062
+ },
1063
+ },
846
1064
  },
847
1065
  resolve: { conditions: ["browser", "import"] },
1066
+ // Optimize what the browser entry needs up front. A dependency first
1067
+ // found on page load makes Vite re-optimize and reload, and until the
1068
+ // reload client components can see two React copies ("Invalid hook call").
1069
+ optimizeDeps: {
1070
+ include: [
1071
+ "react",
1072
+ "react/jsx-runtime",
1073
+ "react/jsx-dev-runtime",
1074
+ "react-dom",
1075
+ "react-dom/client",
1076
+ "rsc-html-stream/client",
1077
+ // Client components and the packages they use load only once a page renders
1078
+ // (client references), so they would be found late too.
1079
+ ...collectFarmClientPackageImports(path.resolve(root, srcDir), root),
1080
+ ],
1081
+ },
848
1082
  },
849
1083
  },
850
1084
  };
@@ -913,10 +1147,22 @@ export default function farmRsc(options = {}) {
913
1147
  {
914
1148
  name: "@farm.js/plugin/rsc:server-fn-actions",
915
1149
  enforce: "pre",
1150
+ // The "use server" boundary for a module whose server functions were
1151
+ // found without an explicit directive. Its exports come from the source
1152
+ // file on disk, never from the request, so nothing else can be named.
1153
+ async load(id) {
1154
+ if (!rscEnabled || !actionsEnabled || !isFarmServerFnBoundaryId(id))
1155
+ return null;
1156
+ const file = id.split("?", 1)[0];
1157
+ this.addWatchFile(file);
1158
+ const source = await fs.readFile(file, "utf8");
1159
+ return createFarmServerFnBoundaryModule(source, file) ?? "export {};\n";
1160
+ },
916
1161
  transform(code, id) {
917
- if (!rscEnabled || !actionsEnabled)
1162
+ if (!rscEnabled || !actionsEnabled || isFarmServerFnBoundaryId(id))
918
1163
  return null;
919
- const result = transformFarmServerFns(code, id);
1164
+ const environment = this.environment?.name;
1165
+ const result = transformFarmServerFns(code, id, { environment: environment ?? "rsc" });
920
1166
  if (!result)
921
1167
  return null;
922
1168
  return {
@@ -983,6 +1229,9 @@ export default function farmRsc(options = {}) {
983
1229
  if (source.includes("rsc-entries") && source.includes("entry.browser.tsx")) {
984
1230
  return VIRTUAL_PREFIX + VIRTUAL_CLIENT_ENTRY;
985
1231
  }
1232
+ if (source.includes("rsc-entries") && source.includes("entry.mobile.tsx")) {
1233
+ return VIRTUAL_PREFIX + VIRTUAL_MOBILE_CLIENT_ENTRY;
1234
+ }
986
1235
  if (source.includes("rsc-entries") && source.includes("entry.rsc.tsx")) {
987
1236
  return VIRTUAL_PREFIX + VIRTUAL_RSC_ENTRY;
988
1237
  }
@@ -1013,6 +1262,9 @@ export default function farmRsc(options = {}) {
1013
1262
  logInfo("Generating client entry");
1014
1263
  return generateClientEntry(entryContext);
1015
1264
  }
1265
+ if (id === VIRTUAL_PREFIX + VIRTUAL_MOBILE_CLIENT_ENTRY) {
1266
+ return generateMobileClientEntry(RSC_CLIENT_ENTRY);
1267
+ }
1016
1268
  // Handle dynamic hydration entries
1017
1269
  if (id.startsWith(VIRTUAL_PREFIX + "/@rsc-hydrate/")) {
1018
1270
  const pagePath = id.replace(VIRTUAL_PREFIX + "/@rsc-hydrate", "");
@@ -1109,7 +1361,6 @@ if (document.readyState === 'loading') {
1109
1361
  logInfo("Dev server middleware ready");
1110
1362
  const serverStartTime = Date.now();
1111
1363
  let bannerPrinted = false;
1112
- const pageCache = new Map();
1113
1364
  server.httpServer?.once("listening", () => {
1114
1365
  if (bannerPrinted)
1115
1366
  return;
@@ -1119,7 +1370,7 @@ if (document.readyState === 'loading') {
1119
1370
  const port = typeof address === "object" && address ? address.port : 3000;
1120
1371
  const colors = getColors();
1121
1372
  console.log("");
1122
- console.log(` ${colors.bold(colors.green("Farm.js"))} ${colors.dim("v1.0.0")} ${colors.dim(`ready in ${elapsed}ms`)}`);
1373
+ console.log(` ${colors.bold(colors.green("Farm.js"))} ${colors.dim(`v${FARM_VERSION}`)} ${colors.dim(`ready in ${elapsed}ms`)}`);
1123
1374
  console.log("");
1124
1375
  console.log(` ${colors.dim("➜")} ${colors.bold("Local:")} ${colors.cyan(`http://localhost:${port}/`)}`);
1125
1376
  console.log(` ${colors.dim("➜")} ${colors.bold("Network:")} ${colors.dim("use --host to expose")}`);
@@ -1229,276 +1480,15 @@ if (document.readyState === 'loading') {
1229
1480
  res.destroy(rscError instanceof Error ? rscError : new Error(String(rscError)));
1230
1481
  return;
1231
1482
  }
1232
- // RSC pipeline failed; fall back to legacy SSR for GET only
1233
- if (method !== "GET" || rscError instanceof FarmDevEnvironmentError) {
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) {
1483
+ // Show the failure. Rendering another page instead (the old legacy
1484
+ // SSR fallback) served the wrong page and hid the error.
1486
1485
  const duration = Date.now() - startTime;
1487
- logResponse("GET", pathname, 500, duration);
1488
- console.error(error);
1489
- // Return error page
1486
+ logResponse(method, pathname, 500, duration);
1487
+ console.error(`[Farm.js] RSC render failed for ${method} ${pathname}:`, rscError);
1490
1488
  res.statusCode = 500;
1491
- res.setHeader("Content-Type", "text/html");
1492
- res.end(`
1493
- <!DOCTYPE html>
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
- `);
1489
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
1490
+ res.setHeader("Cache-Control", "no-store");
1491
+ res.end(createRscDevErrorDocument(rscError, method, pathname));
1502
1492
  }
1503
1493
  });
1504
1494
  };