@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.
Files changed (38) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/middleware/index.d.ts +1 -8
  5. package/dist/middleware/index.d.ts.map +1 -1
  6. package/dist/middleware/index.js +10 -16
  7. package/dist/middleware/matching.d.ts +2 -4
  8. package/dist/middleware/matching.d.ts.map +1 -1
  9. package/dist/middleware/matching.js +47 -7
  10. package/dist/rsc/entries/client.d.ts.map +1 -1
  11. package/dist/rsc/entries/client.js +9 -22
  12. package/dist/rsc/entries/rsc.d.ts.map +1 -1
  13. package/dist/rsc/entries/rsc.js +40 -533
  14. package/dist/rsc/entries/ssr.d.ts.map +1 -1
  15. package/dist/rsc/entries/ssr.js +6 -7
  16. package/dist/rsc/index.d.ts +2 -35
  17. package/dist/rsc/index.d.ts.map +1 -1
  18. package/dist/rsc/index.js +290 -238
  19. package/dist/rsc/middleware-config-module.d.ts +0 -3
  20. package/dist/rsc/middleware-config-module.d.ts.map +1 -1
  21. package/dist/rsc/middleware-config-module.js +28 -41
  22. package/dist/rsc/nitro-build.d.ts.map +1 -1
  23. package/dist/rsc/nitro-build.js +81 -259
  24. package/dist/rsc/server-fn-transform.d.ts +5 -1
  25. package/dist/rsc/server-fn-transform.d.ts.map +1 -1
  26. package/dist/rsc/server-fn-transform.js +338 -3
  27. package/dist/rsc/types.d.ts +0 -28
  28. package/dist/rsc/types.d.ts.map +1 -1
  29. package/dist/rsc/vite-plugin-nitro.d.ts +0 -2
  30. package/dist/rsc/vite-plugin-nitro.d.ts.map +1 -1
  31. package/dist/rsc/vite-plugin-nitro.js +2 -12
  32. package/package.json +3 -3
  33. package/dist/rsc/client-sourcemaps.d.ts +0 -13
  34. package/dist/rsc/client-sourcemaps.d.ts.map +0 -1
  35. package/dist/rsc/client-sourcemaps.js +0 -52
  36. package/dist/rsc/document-layouts.d.ts +0 -16
  37. package/dist/rsc/document-layouts.d.ts.map +0 -1
  38. package/dist/rsc/document-layouts.js +0 -82
package/dist/rsc/index.js CHANGED
@@ -25,21 +25,18 @@ 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 { farmFontImportsPlugin, farmImageImportsPlugin, generateClientCachePersistenceCode, getPublicFarmImageConfig, resolveFarmClientCacheAdapterEntry, resolveFarmImageConfig, resolveFarmImageProviderForRuntime, resolveFarmImageServerRuntime, readRouteRenderingDirectiveFromFile, } from "@farm.js/core/vite";
28
+ import { generateClientCachePersistenceCode, resolveFarmClientCacheAdapterEntry, } from "@farm.js/core/vite";
29
29
  import { generateRscEntry } from "./entries/rsc.js";
30
- import { resolveMarkdownConfig } from "@farm.js/core/markdown";
31
30
  import { generateSsrEntry } from "./entries/ssr.js";
32
31
  import { generateErrorFallbackEntry } from "./entries/error-fallback.js";
33
32
  import { generateClientEntry, serverFnTransportErrorClientRuntime } from "./entries/client.js";
34
33
  import { transformFarmRouteActionClients } from "./route-action-transform.js";
35
- import { createFarmServerFnBoundaryModule, isFarmServerFnBoundaryId, transformFarmServerFns, } from "./server-fn-transform.js";
34
+ import { transformFarmServerFns } from "./server-fn-transform.js";
36
35
  import { transformAutomaticOptimizedBoundaries } from "./automatic-optimized-boundary.js";
37
36
  import { resolveRscBuildOutputPath } from "./build-paths.js";
38
- import { rscPrivateClientSourcemaps } from "./client-sourcemaps.js";
39
- import { findDocumentLayouts, findRouteFiles } from "./document-layouts.js";
40
37
  import { assertRscPackageCompatibility } from "./compatibility.js";
41
38
  import { sendRscDevelopmentResponse } from "./dev-response.js";
42
- import { loadRscConfigPropertyModule, loadRscMiddlewareConfigModule, } from "./middleware-config-module.js";
39
+ import { loadRscMiddlewareConfigModule } from "./middleware-config-module.js";
43
40
  import fs from "fs/promises";
44
41
  import path from "path";
45
42
  import { devServableFileExists } from "../dev-static.js";
@@ -49,21 +46,17 @@ import { createRequire } from "node:module";
49
46
  // Use API and middleware plugins from @farm.js/core (require so CJS build resolves when ESM .mjs is missing)
50
47
  const require_ = createRequire(import.meta.url);
51
48
  const { farmApiPlugin } = require_("@farm.js/core");
52
- const { FARM_VERSION } = require_("@farm.js/core/version");
53
49
  const { farmMiddlewarePlugin } = require_("@farm.js/core/middleware");
54
50
  const { resolveServerActionsConfig, validateServerActionRequest, createServerActionRequestErrorResponse, } = require_("@farm.js/core/server-action-security");
55
51
  const { normalizeFarmDeploymentId } = require_("@farm.js/core/deployment");
56
- const { getFarmLayerAliases, getFarmSourceRoots, resolveFarmLayers, resolveFarmMCPConfig, resolveFarmMCPPlugin, } = require_("@farm.js/core/server");
57
- const { readNodeRequestBody, resolveFarmServerConfig, resolveFarmI18nConfig, createFarmRequestBodyErrorResponse, createDefaultErrorMarkup, resolveFarmLlmsTxtConfig, } = require_("@farm.js/core/internal/production-runtime");
52
+ const { getFarmLayerAliases, getFarmSourceRoots, resolveFarmLayers } = require_("@farm.js/core/server");
53
+ const { searchParamsToObject, readNodeRequestBody, resolveFarmServerConfig, resolveFarmI18nConfig, createFarmRequestBodyErrorResponse, } = require_("@farm.js/core/internal/production-runtime");
58
54
  const { isFarmAPIPathname } = require_("@farm.js/core/api/runtime");
59
55
  const { resolveFarmAPIConfig, resolveFarmAPIServerBasePath } = require_("@farm.js/core/api");
60
56
  const { getResolvedEnv } = require_("@farm.js/core/env");
61
57
  export { buildRscNitro, waitForRscManifest, waitForRscOutputs } from "./nitro-build.js";
62
58
  import { registerRscNitroRuntimePackage } from "./nitro-build.js";
63
59
  export { default as nitro } from "./vite-plugin-nitro.js";
64
- const PAGE_FILE = /^page\.(tsx|jsx|ts|js)$/;
65
- /** Packages the generated RSC entries import that belong to this plugin, not to the app. */
66
- const PLUGIN_OWNED_ENTRY_IMPORTS = ["rsc-html-stream/server", "rsc-html-stream/client"];
67
60
  /**
68
61
  * Define a Farm.js RSC configuration
69
62
  * This is the recommended way to configure your RSC app
@@ -87,11 +80,6 @@ export function defineConfig(config = {}) {
87
80
  serverActions: config.serverActions,
88
81
  deploymentId: config.deploymentId,
89
82
  generateBuildId: config.generateBuildId,
90
- md: config.md,
91
- agent: config.agent,
92
- mcp: config.mcp,
93
- middleware: config.middleware,
94
- images: config.images,
95
83
  // Vite server configuration
96
84
  server: {
97
85
  ...config.server,
@@ -100,28 +88,22 @@ export function defineConfig(config = {}) {
100
88
  },
101
89
  // Custom logger to hide Vite's default startup banner
102
90
  customLogger: createFarmLogger(port, debug),
91
+ // Configure esbuild for JSX transformation
92
+ esbuild: {
93
+ jsx: "automatic",
94
+ jsxImportSource: "react",
95
+ },
103
96
  plugins: [
104
97
  farmMiddlewarePlugin({
105
98
  srcDir: config.srcDir ?? "src",
106
99
  basePath: config.basePath ?? "/",
107
- // API routes in development run through this plugin's middleware, not the RSC entry's.
108
- middleware: config.middleware,
109
100
  debug,
110
101
  }),
111
102
  farmApiPlugin({
112
103
  srcDir: config.srcDir ?? "src",
113
- // The production entry serves API routes from the routes directory; so does development.
114
- apiDir: path.join(config.srcDir ?? "src", config.routesDir === undefined ? "app" : config.routesDir.trim(), "api"),
115
104
  debug,
116
105
  bodySizeLimit: config.server?.bodySizeLimit,
117
- // The dev API server mounts the MCP endpoint, as core's does.
118
- ...(config.mcp ? { plugins: ({ root }) => resolveRscMCPPlugins(config.mcp, root) } : {}),
119
106
  }),
120
- // localFont() from @farm.js/core/font, with its CSS carried by the bundler: this pipeline
121
- // has no step that merges font CSS into a global stylesheet.
122
- farmFontImportsPlugin({ basePath: config.basePath ?? "/", importCss: true }),
123
- // Static image imports as { src, width, height }, which <Image> sizes from.
124
- farmImageImportsPlugin(),
125
107
  farmRsc({
126
108
  debug,
127
109
  encryptActions: config.encryptActions,
@@ -202,7 +184,6 @@ const VIRTUAL_HYDRATE_ENTRY = "virtual:@farm.js/rsc/hydrate";
202
184
  const OPTIMIZED_BOUNDARY_ADAPTER = "@farm.js/plugin/rsc/optimized-boundary";
203
185
  const STRATA_PACKAGE = "@farming-labs/strata";
204
186
  const RSC_MIDDLEWARE_CONFIG_QUERY = "?farm-rsc-middleware";
205
- const RSC_MCP_CONFIG_QUERY = "?farm-rsc-mcp";
206
187
  const FARM_CORE_PACKAGE_ROOT = path.resolve(path.dirname(require_.resolve("@farm.js/core")), "..");
207
188
  const FARM_CONFIG_FILENAMES = [
208
189
  "farm.config.ts",
@@ -247,19 +228,6 @@ async function findFarmConfigPath(root) {
247
228
  }
248
229
  return null;
249
230
  }
250
- /** Resolves `mcp` for an RSC app, rejecting what the RSC server cannot serve yet. */
251
- function resolveRscMCPConfig(input) {
252
- const config = resolveFarmMCPConfig(input);
253
- if (config.enabled && config.oauth) {
254
- throw new Error("[Farm.js] mcp.oauth is not supported in RSC apps yet: the RSC server does not serve " +
255
- "the protected-resource metadata. Remove oauth, or validate tokens in mcp.authorize.");
256
- }
257
- return config;
258
- }
259
- async function resolveRscMCPPlugins(input, root) {
260
- const plugin = await resolveFarmMCPPlugin(resolveRscMCPConfig(input), { root });
261
- return plugin ? [plugin] : [];
262
- }
263
231
  async function resolveMiddlewareConfigPaths(root, layers) {
264
232
  const paths = (layers ?? []).flatMap((layer) => layer.configFile ? [path.resolve(layer.configFile)] : []);
265
233
  const projectConfigPath = await findFarmConfigPath(root);
@@ -267,50 +235,11 @@ async function resolveMiddlewareConfigPaths(root, layers) {
267
235
  paths.push(projectConfigPath);
268
236
  return [...new Set(paths)];
269
237
  }
270
- // Vite's default config names: `defineConfig` from this package is written in one of them.
271
- const VITE_CONFIG_FILENAMES = [
272
- "vite.config.js",
273
- "vite.config.mjs",
274
- "vite.config.ts",
275
- "vite.config.cjs",
276
- "vite.config.mts",
277
- "vite.config.cts",
278
- ];
279
- async function findViteConfigPath(root) {
280
- for (const fileName of VITE_CONFIG_FILENAMES) {
281
- const candidate = path.join(root, fileName);
282
- try {
283
- if ((await fs.stat(candidate)).isFile())
284
- return candidate;
285
- }
286
- catch {
287
- // Continue checking supported config names.
288
- }
289
- }
290
- return null;
291
- }
292
238
  function isOptimizedBoundaryModule(id) {
293
239
  return (id === OPTIMIZED_BOUNDARY_ADAPTER ||
294
240
  id === STRATA_PACKAGE ||
295
241
  id.startsWith(`${STRATA_PACKAGE}/`));
296
242
  }
297
- /** The development error page for a failed RSC render: core's error page, with the real error. */
298
- function createRscDevErrorDocument(error, method, pathname) {
299
- const failure = error instanceof Error ? error : new Error(String(error));
300
- const markup = createDefaultErrorMarkup({
301
- statusCode: 500,
302
- requestPath: pathname,
303
- method,
304
- message: failure.message,
305
- errorName: failure.name,
306
- stack: failure.stack,
307
- development: true,
308
- mode: "development",
309
- farmVersion: FARM_VERSION,
310
- nodeVersion: process.version,
311
- });
312
- 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>`;
313
- }
314
243
  function resolveOptimizedBoundaryRuntimeRoot() {
315
244
  try {
316
245
  return path.dirname(require_.resolve(`${STRATA_PACKAGE}/package.json`));
@@ -522,7 +451,6 @@ export default function farmRsc(options = {}) {
522
451
  let entryContext;
523
452
  let rscBuildRoot;
524
453
  const middlewareConfigModules = new Map();
525
- let mcpConfigCandidates = null;
526
454
  // Store for debugging
527
455
  const debug = options.debug ?? false;
528
456
  const automaticDeploymentId = `build-${Date.now()}`;
@@ -612,43 +540,14 @@ export default function farmRsc(options = {}) {
612
540
  };
613
541
  return [
614
542
  farmEnvironmentFunctionsPlugin(),
615
- rscPrivateClientSourcemaps(),
616
543
  {
617
544
  name: "@farm.js/plugin/rsc:middleware-config",
618
545
  enforce: "pre",
619
546
  resolveId(id) {
620
- if (!id.endsWith(RSC_MIDDLEWARE_CONFIG_QUERY) && !id.endsWith(RSC_MCP_CONFIG_QUERY)) {
547
+ if (!id.endsWith(RSC_MIDDLEWARE_CONFIG_QUERY))
621
548
  return null;
622
- }
623
549
  return id.replace(/\\/g, "/");
624
550
  },
625
- // The MCP config is read from the Vite config file too, whose path is
626
- // only known here. Entries are generated on load, after this runs.
627
- async configResolved(resolved) {
628
- if (!mcpConfigCandidates || !entryContext)
629
- return;
630
- const configPaths = [...mcpConfigCandidates];
631
- if (resolved.configFile)
632
- configPaths.push(path.resolve(resolved.configFile));
633
- const mcpConfigPaths = [];
634
- for (const configPath of new Set(configPaths)) {
635
- const extracted = await loadRscConfigPropertyModule(configPath, "mcp");
636
- if (extracted.kind === "unsupported") {
637
- throw new Error(`[Farm.js] Cannot read mcp for the RSC server from ${configPath}: ${extracted.reason}. ` +
638
- "Declare mcp directly in defineConfig({ mcp: ... }).");
639
- }
640
- if (extracted.kind === "absent")
641
- continue;
642
- const moduleId = `${configPath.replace(/\\/g, "/")}${RSC_MCP_CONFIG_QUERY}`;
643
- middlewareConfigModules.set(moduleId, extracted.code);
644
- mcpConfigPaths.push(moduleId);
645
- }
646
- if (mcpConfigPaths.length === 0) {
647
- throw new Error("[Farm.js] The RSC server could not find the mcp config. " +
648
- "Declare mcp directly in defineConfig({ mcp: ... }) in your Vite or Farm config file.");
649
- }
650
- entryContext.mcpConfigPaths = mcpConfigPaths;
651
- },
652
551
  load(id) {
653
552
  return middlewareConfigModules.get(id.replace(/\\/g, "/")) ?? null;
654
553
  },
@@ -686,15 +585,7 @@ export default function farmRsc(options = {}) {
686
585
  async config(config, env) {
687
586
  const c = config;
688
587
  // Check if user enabled RSC in their config
689
- const serverComponents = c.experimental?.serverComponents;
690
- if (typeof serverComponents === "object" &&
691
- serverComponents !== null &&
692
- serverComponents.mode !== "rsc") {
693
- throw new Error(`[Farm.js] @farm.js/plugin/rsc runs the "rsc" engine; experimental.serverComponents.mode "${String(serverComponents.mode)}" is not supported here.`);
694
- }
695
- rscEnabled =
696
- serverComponents === true ||
697
- (typeof serverComponents === "object" && serverComponents !== null);
588
+ rscEnabled = c.experimental?.serverComponents === true;
698
589
  actionsEnabled = c.experimental?.serverActions === true;
699
590
  bodySizeLimit = resolveFarmServerConfig(c.server).bodySizeLimit;
700
591
  optimizedBoundaryEnabled = c.experimental?.optimizedBoundary === true;
@@ -721,19 +612,11 @@ export default function farmRsc(options = {}) {
721
612
  Object.assign(c, layerResolution.config);
722
613
  }
723
614
  middlewareConfigModules.clear();
724
- // The config files mcp is read from at runtime; the Vite config file is
725
- // added once it is known, in configResolved.
726
- mcpConfigCandidates = resolveRscMCPConfig(c.mcp).enabled
727
- ? await resolveMiddlewareConfigPaths(root, c.layers)
728
- : null;
729
615
  const middlewareConfigPaths = [];
730
616
  if (hasFarmMiddlewareConfig(c.middleware)) {
731
617
  const configPaths = await resolveMiddlewareConfigPaths(root, c.layers);
732
- const viteConfigPath = await findViteConfigPath(root);
733
- if (viteConfigPath)
734
- configPaths.push(viteConfigPath);
735
618
  if (configPaths.length === 0) {
736
- throw new Error("[Farm.js] RSC config middleware requires an importable farm.config or vite.config file. " +
619
+ throw new Error("[Farm.js] RSC config middleware requires an importable farm.config file. " +
737
620
  "Move the middleware to farm.config.ts or src/app/middleware.ts.");
738
621
  }
739
622
  for (const configPath of configPaths) {
@@ -794,49 +677,8 @@ export default function farmRsc(options = {}) {
794
677
  : `/${projectSourceDir}${routeSuffix}`;
795
678
  return { name: source.name, base, glob: base };
796
679
  });
797
- // Each page's rendering directive and whether its source reads request state, which the
798
- // runtime cannot see from module exports: the same baked input core's server merges.
799
- // Later roots override earlier ones, as the entry's merged page map does.
800
- const pageRenderingDirectives = {};
801
- for (const source of getFarmSourceRoots(c)) {
802
- const routesRoot = path.resolve(root, source.srcDir, configuredRoutesDir);
803
- for (const { key, file } of await findRouteFiles(routesRoot, (name) => PAGE_FILE.test(name))) {
804
- const directive = readRouteRenderingDirectiveFromFile(file);
805
- if (directive)
806
- pageRenderingDirectives[key] = directive;
807
- else
808
- delete pageRenderingDirectives[key];
809
- }
810
- }
811
- // Root layouts that render <html> own the document (Next.js's root layout contract).
812
- const documentLayouts = [
813
- ...new Set((await Promise.all(getFarmSourceRoots(c).map((source) => findDocumentLayouts(path.resolve(root, source.srcDir, configuredRoutesDir))))).flat()),
814
- ];
815
- // The same images contract as core: without Sharp, "auto" keeps original URLs
816
- // (provider "none") instead of pointing <Image> at an optimizer that cannot run.
817
- const nitroPreset = process.env.NITRO_PRESET || "vercel";
818
- const imageConfig = resolveFarmImageConfig(resolveFarmImageProviderForRuntime(c.images, {
819
- root,
820
- preset: nitroPreset,
821
- dev: env.command === "serve",
822
- }));
823
- const publicImageConfig = getPublicFarmImageConfig(imageConfig);
824
- // Development always optimizes with Sharp, as core's dev server does.
825
- const imageRuntime = env.command === "serve"
826
- ? imageConfig.provider === "none"
827
- ? "none"
828
- : "node"
829
- : resolveFarmImageServerRuntime(imageConfig, nitroPreset);
830
680
  // Build context for entry generators
831
681
  entryContext = {
832
- documentLayouts,
833
- pageRenderingDirectives,
834
- images: {
835
- config: imageConfig,
836
- public: publicImageConfig,
837
- path: imageConfig.path,
838
- runtime: imageRuntime,
839
- },
840
682
  srcDir,
841
683
  outDir,
842
684
  basePath: c.basePath ?? "/",
@@ -851,9 +693,6 @@ export default function farmRsc(options = {}) {
851
693
  allowedOrigins: options.serverActions?.allowedOrigins ?? c.serverActions?.allowedOrigins,
852
694
  }),
853
695
  deploymentId,
854
- markdown: resolveMarkdownConfig(c.md),
855
- // Core's default for an app without docs: llms.txt on, llms-full.txt off.
856
- llmsTxt: resolveFarmLlmsTxtConfig(c.agent?.llmsTxt ?? { full: false }),
857
696
  // Resolved the same way core resolves it for the config, so RSC and
858
697
  // non-RSC apps match middleware against the same pathname.
859
698
  i18n: resolveFarmI18nConfig(c.i18n, {
@@ -905,7 +744,6 @@ export default function farmRsc(options = {}) {
905
744
  builder: { sharedConfigBuild: true },
906
745
  define: {
907
746
  __FARM_API_BASE_URL__: JSON.stringify(api.baseURL),
908
- __FARM_IMAGE_CONFIG__: JSON.stringify(entryContext.images?.public),
909
747
  },
910
748
  ssr: {
911
749
  external: [
@@ -929,21 +767,6 @@ export default function farmRsc(options = {}) {
929
767
  resolve: {
930
768
  dedupe: ["react", "react-dom", "react-server-dom-webpack"],
931
769
  alias: [
932
- // The generated entries import the plugin's own dependencies; resolve them from here
933
- // so an app (strict pnpm layout) does not have to install them itself.
934
- ...PLUGIN_OWNED_ENTRY_IMPORTS.flatMap((specifier) => {
935
- try {
936
- return [
937
- {
938
- find: new RegExp(`^${specifier.replace(/[/.]/g, "\\$&")}$`),
939
- replacement: require_.resolve(specifier),
940
- },
941
- ];
942
- }
943
- catch {
944
- return [];
945
- }
946
- }),
947
770
  ...Object.entries(layerAliases).map(([find, replacement]) => ({
948
771
  find,
949
772
  replacement,
@@ -986,11 +809,10 @@ export default function farmRsc(options = {}) {
986
809
  : []),
987
810
  ],
988
811
  },
989
- // Vite 8 compiles with oxc, which already uses the automatic runtime;
990
- // setting esbuild there only prints a "both options were set" warning.
991
- ...(this?.meta?.rolldownVersion
992
- ? {}
993
- : { esbuild: { jsx: "automatic", jsxImportSource: "react" } }),
812
+ esbuild: {
813
+ jsx: "automatic",
814
+ jsxImportSource: "react",
815
+ },
994
816
  ...(c.layers?.length
995
817
  ? {
996
818
  server: {
@@ -1007,14 +829,7 @@ export default function farmRsc(options = {}) {
1007
829
  copyPublicDir: false,
1008
830
  rollupOptions: { input: { index: entryRsc } },
1009
831
  },
1010
- resolve: {
1011
- conditions: ["react-server", "node", "import"],
1012
- // Strata is a native CommonJS loader: Node must load it, not Vite's
1013
- // module runner. ssr.external does not reach this environment.
1014
- ...(optimizedBoundaryEnabled
1015
- ? { external: [STRATA_PACKAGE, `${STRATA_PACKAGE}/react-server`] }
1016
- : {}),
1017
- },
832
+ resolve: { conditions: ["react-server", "node", "import"] },
1018
833
  },
1019
834
  ssr: {
1020
835
  build: {
@@ -1030,19 +845,6 @@ export default function farmRsc(options = {}) {
1030
845
  rollupOptions: { input: { index: entryClient } },
1031
846
  },
1032
847
  resolve: { conditions: ["browser", "import"] },
1033
- // Optimize what the browser entry needs up front. A dependency first
1034
- // found on page load makes Vite re-optimize and reload, and until the
1035
- // reload client components can see two React copies ("Invalid hook call").
1036
- optimizeDeps: {
1037
- include: [
1038
- "react",
1039
- "react/jsx-runtime",
1040
- "react/jsx-dev-runtime",
1041
- "react-dom",
1042
- "react-dom/client",
1043
- "rsc-html-stream/client",
1044
- ],
1045
- },
1046
848
  },
1047
849
  },
1048
850
  };
@@ -1111,22 +913,10 @@ export default function farmRsc(options = {}) {
1111
913
  {
1112
914
  name: "@farm.js/plugin/rsc:server-fn-actions",
1113
915
  enforce: "pre",
1114
- // The "use server" boundary for a module whose server functions were
1115
- // found without an explicit directive. Its exports come from the source
1116
- // file on disk, never from the request, so nothing else can be named.
1117
- async load(id) {
1118
- if (!rscEnabled || !actionsEnabled || !isFarmServerFnBoundaryId(id))
1119
- return null;
1120
- const file = id.split("?", 1)[0];
1121
- this.addWatchFile(file);
1122
- const source = await fs.readFile(file, "utf8");
1123
- return createFarmServerFnBoundaryModule(source, file) ?? "export {};\n";
1124
- },
1125
916
  transform(code, id) {
1126
- if (!rscEnabled || !actionsEnabled || isFarmServerFnBoundaryId(id))
917
+ if (!rscEnabled || !actionsEnabled)
1127
918
  return null;
1128
- const environment = this.environment?.name;
1129
- const result = transformFarmServerFns(code, id, { environment: environment ?? "rsc" });
919
+ const result = transformFarmServerFns(code, id);
1130
920
  if (!result)
1131
921
  return null;
1132
922
  return {
@@ -1319,6 +1109,7 @@ if (document.readyState === 'loading') {
1319
1109
  logInfo("Dev server middleware ready");
1320
1110
  const serverStartTime = Date.now();
1321
1111
  let bannerPrinted = false;
1112
+ const pageCache = new Map();
1322
1113
  server.httpServer?.once("listening", () => {
1323
1114
  if (bannerPrinted)
1324
1115
  return;
@@ -1328,7 +1119,7 @@ if (document.readyState === 'loading') {
1328
1119
  const port = typeof address === "object" && address ? address.port : 3000;
1329
1120
  const colors = getColors();
1330
1121
  console.log("");
1331
- console.log(` ${colors.bold(colors.green("Farm.js"))} ${colors.dim(`v${FARM_VERSION}`)} ${colors.dim(`ready in ${elapsed}ms`)}`);
1122
+ console.log(` ${colors.bold(colors.green("Farm.js"))} ${colors.dim("v1.0.0")} ${colors.dim(`ready in ${elapsed}ms`)}`);
1332
1123
  console.log("");
1333
1124
  console.log(` ${colors.dim("➜")} ${colors.bold("Local:")} ${colors.cyan(`http://localhost:${port}/`)}`);
1334
1125
  console.log(` ${colors.dim("➜")} ${colors.bold("Network:")} ${colors.dim("use --host to expose")}`);
@@ -1438,15 +1229,276 @@ if (document.readyState === 'loading') {
1438
1229
  res.destroy(rscError instanceof Error ? rscError : new Error(String(rscError)));
1439
1230
  return;
1440
1231
  }
1441
- // Show the failure. Rendering another page instead (the old legacy
1442
- // SSR fallback) served the wrong page and hid the error.
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) {
1443
1486
  const duration = Date.now() - startTime;
1444
- logResponse(method, pathname, 500, duration);
1445
- console.error(`[Farm.js] RSC render failed for ${method} ${pathname}:`, rscError);
1487
+ logResponse("GET", pathname, 500, duration);
1488
+ console.error(error);
1489
+ // Return error page
1446
1490
  res.statusCode = 500;
1447
- res.setHeader("Content-Type", "text/html; charset=utf-8");
1448
- res.setHeader("Cache-Control", "no-store");
1449
- res.end(createRscDevErrorDocument(rscError, method, pathname));
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
+ `);
1450
1502
  }
1451
1503
  });
1452
1504
  };