@farm.js/plugin 0.1.0-beta.98 → 0.1.0
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/README.md +2 -2
- package/dist/api/index.d.ts +2 -0
- package/dist/api/index.d.ts.map +1 -1
- package/dist/api/index.js +43 -31
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/middleware/index.d.ts +2 -3
- package/dist/middleware/index.d.ts.map +1 -1
- package/dist/middleware/index.js +44 -10
- package/dist/middleware/matching.d.ts +8 -3
- package/dist/middleware/matching.d.ts.map +1 -1
- package/dist/middleware/matching.js +15 -7
- package/dist/observability/index.d.ts.map +1 -1
- package/dist/observability/index.js +7 -2
- package/dist/rsc/entries/client.d.ts.map +1 -1
- package/dist/rsc/entries/client.js +37 -2
- package/dist/rsc/entries/rsc.d.ts.map +1 -1
- package/dist/rsc/entries/rsc.js +77 -22
- package/dist/rsc/index.d.ts +2 -0
- package/dist/rsc/index.d.ts.map +1 -1
- package/dist/rsc/index.js +163 -30
- package/dist/rsc/middleware-config-module.d.ts +19 -0
- package/dist/rsc/middleware-config-module.d.ts.map +1 -0
- package/dist/rsc/middleware-config-module.js +355 -0
- package/dist/rsc/nitro-build.d.ts +2 -0
- package/dist/rsc/nitro-build.d.ts.map +1 -1
- package/dist/rsc/nitro-build.js +64 -39
- package/dist/rsc/server-fn-transform.d.ts.map +1 -1
- package/dist/rsc/server-fn-transform.js +177 -0
- package/dist/rsc/test-fixture-dependencies.d.ts +2 -0
- package/dist/rsc/test-fixture-dependencies.d.ts.map +1 -0
- package/dist/rsc/test-fixture-dependencies.js +23 -0
- package/dist/rsc/types.d.ts +20 -0
- package/dist/rsc/types.d.ts.map +1 -1
- package/dist/rsc/vite-plugin-nitro.d.ts +20 -7
- package/dist/rsc/vite-plugin-nitro.d.ts.map +1 -1
- package/dist/rsc/vite-plugin-nitro.js +51 -66
- package/package.json +5 -4
package/dist/rsc/entries/rsc.js
CHANGED
|
@@ -23,9 +23,14 @@ export function generateRscEntry(ctx) {
|
|
|
23
23
|
return { ...root, sourceGlob };
|
|
24
24
|
});
|
|
25
25
|
const debugLog = `// Debug disabled`;
|
|
26
|
+
const middlewareConfigImports = (ctx.middlewareConfigPaths ?? [])
|
|
27
|
+
.map((configPath, index) => `import * as FarmMiddlewareConfigModule${index} from ${JSON.stringify(configPath.replace(/\\/g, "/"))};`)
|
|
28
|
+
.join("\n");
|
|
29
|
+
const middlewareConfigValues = (ctx.middlewareConfigPaths ?? []).map((_configPath, index) => `(FarmMiddlewareConfigModule${index}.default || FarmMiddlewareConfigModule${index})`);
|
|
26
30
|
let code = `
|
|
27
31
|
import React from 'react';
|
|
28
32
|
import ServerErrorFallback from '/.farm/rsc-entries/error-fallback.tsx';
|
|
33
|
+
${middlewareConfigImports}
|
|
29
34
|
import { registerAPIRouteShape } from '@farm.js/core/api/runtime';
|
|
30
35
|
import {
|
|
31
36
|
renderToReadableStream,
|
|
@@ -289,12 +294,26 @@ async function handleAPIRequest(request) {
|
|
|
289
294
|
});
|
|
290
295
|
}
|
|
291
296
|
}
|
|
297
|
+
const farmRuntimeConfigs = [${middlewareConfigValues.join(", ")}].filter(Boolean);
|
|
298
|
+
const farmConfigMiddleware = farmRuntimeConfigs.flatMap((config) => {
|
|
299
|
+
const middleware = config.middleware;
|
|
300
|
+
if (!middleware) return [];
|
|
301
|
+
return Array.isArray(middleware) ? middleware : [middleware];
|
|
302
|
+
});
|
|
292
303
|
const farmMiddlewareRunner = createProductionMiddlewareRunner({
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
filePath,
|
|
296
|
-
|
|
297
|
-
|
|
304
|
+
config: farmConfigMiddleware,
|
|
305
|
+
modules: Object.entries(middlewares)
|
|
306
|
+
.map(([filePath, module]) => ({
|
|
307
|
+
path: middlewarePathToRoute(filePath),
|
|
308
|
+
filePath,
|
|
309
|
+
module,
|
|
310
|
+
}))
|
|
311
|
+
.filter((entry) => entry.path !== null)
|
|
312
|
+
// Root first, as core runs them: a nested guard can rely on what its
|
|
313
|
+
// parent middleware set, and glob order is alphabetical, not by depth.
|
|
314
|
+
.sort((left, right) => middlewareRouteDepth(left.path) - middlewareRouteDepth(right.path)),
|
|
315
|
+
i18n: ${JSON.stringify(ctx.i18n) ?? "undefined"},
|
|
316
|
+
server: ${JSON.stringify(ctx.server) ?? "undefined"},
|
|
298
317
|
});
|
|
299
318
|
|
|
300
319
|
debug('Discovered pages:', Object.keys(pages));
|
|
@@ -305,22 +324,38 @@ debug('Discovered middlewares:', Object.keys(middlewares));
|
|
|
305
324
|
debug('Discovered API routes:', Array.from(apiRouteMap.keys()));
|
|
306
325
|
|
|
307
326
|
/**
|
|
308
|
-
* Convert middleware file path to route
|
|
309
|
-
*
|
|
310
|
-
*
|
|
327
|
+
* Convert an app-relative middleware file path to the route it guards, with the
|
|
328
|
+
* same rules as core's middleware discovery: a route group such as
|
|
329
|
+
* '(protected)' adds no URL segment, and a '_private' or dot-prefixed folder
|
|
330
|
+
* holds no routes, so its middleware never runs (null).
|
|
331
|
+
* e.g., '/middleware.ts' -> '/'
|
|
332
|
+
* e.g., '/(protected)/dashboard/middleware.ts' -> '/dashboard'
|
|
311
333
|
*/
|
|
312
334
|
function middlewarePathToRoute(filePath) {
|
|
313
|
-
|
|
314
|
-
.replace(
|
|
315
|
-
.
|
|
316
|
-
|
|
335
|
+
const segments = filePath
|
|
336
|
+
.replace(/\\/middleware\\.[tj]sx?$/, '')
|
|
337
|
+
.split('/')
|
|
338
|
+
.filter(Boolean);
|
|
339
|
+
if (segments.some((segment) => segment.startsWith('_') || segment.startsWith('.'))) {
|
|
340
|
+
return null;
|
|
341
|
+
}
|
|
342
|
+
const routeSegments = segments.filter(
|
|
343
|
+
(segment) => !(segment.startsWith('(') && segment.endsWith(')')),
|
|
344
|
+
);
|
|
345
|
+
return routeSegments.length === 0 ? '/' : '/' + routeSegments.join('/');
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function middlewareRouteDepth(route) {
|
|
349
|
+
return route === '/' ? 0 : route.split('/').length - 1;
|
|
317
350
|
}
|
|
318
351
|
|
|
319
352
|
/**
|
|
320
353
|
* Execute middleware chain for a request
|
|
321
354
|
*/
|
|
322
|
-
async function executeMiddleware(request) {
|
|
323
|
-
|
|
355
|
+
async function executeMiddleware(request, context) {
|
|
356
|
+
// The Request was rebuilt by the Nitro handler and has no socket; the
|
|
357
|
+
// handler passes the connection's address alongside it.
|
|
358
|
+
return farmMiddlewareRunner(request, { clientAddress: context?.clientAddress });
|
|
324
359
|
}
|
|
325
360
|
|
|
326
361
|
/**
|
|
@@ -455,7 +490,7 @@ function getMatchingBoundary(pageFilePath, modules, kind) {
|
|
|
455
490
|
* Main request handler - entry point for both dev and production (Nitro).
|
|
456
491
|
* Exported as { fetch: handler } for the RSC/Nitro contract (see vite-plugin-rsc-deploy-example).
|
|
457
492
|
*/
|
|
458
|
-
async function handleFarmRequest(request) {
|
|
493
|
+
async function handleFarmRequest(request, context) {
|
|
459
494
|
let url = new URL(request.url);
|
|
460
495
|
let matchedPage = null;
|
|
461
496
|
let errorData = new Map();
|
|
@@ -493,7 +528,7 @@ async function handleFarmRequest(request) {
|
|
|
493
528
|
: ""}
|
|
494
529
|
|
|
495
530
|
// Execute middleware first
|
|
496
|
-
const middlewareResult = await executeMiddleware(request);
|
|
531
|
+
const middlewareResult = await executeMiddleware(request, context);
|
|
497
532
|
|
|
498
533
|
// If middleware handled the request (e.g., redirect, auth), return the response
|
|
499
534
|
if (middlewareResult.response) {
|
|
@@ -599,12 +634,22 @@ async function handleFarmRequest(request) {
|
|
|
599
634
|
if (request.signal.aborted) {
|
|
600
635
|
return new Response(null, { status: 499, headers: { 'Cache-Control': 'no-store' } });
|
|
601
636
|
}
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
637
|
+
// redirect() unwinds by throwing, so it arrives here looking like a
|
|
638
|
+
// failure. It is control flow, not an error: carry it to the client as
|
|
639
|
+
// data so the router can navigate. Everything else still goes through
|
|
640
|
+
// sanitizeServerActionError untouched.
|
|
641
|
+
const actionRedirect = getFarmRedirectError(e);
|
|
642
|
+
if (actionRedirect) {
|
|
643
|
+
returnValue = { ok: false, redirect: { url: actionRedirect.url, status: actionRedirect.status } };
|
|
644
|
+
debug('Server action redirected:', actionId, actionRedirect.url);
|
|
645
|
+
} else {
|
|
646
|
+
const actionError = sanitizeServerActionError(e);
|
|
647
|
+
if (actionError.name === 'ServerActionError') {
|
|
648
|
+
console.error('[Farm.js] Server action failed:', e);
|
|
649
|
+
}
|
|
650
|
+
returnValue = { ok: false, data: actionError };
|
|
651
|
+
debug('Server action failed:', actionId, e);
|
|
605
652
|
}
|
|
606
|
-
returnValue = { ok: false, data: actionError };
|
|
607
|
-
debug('Server action failed:', actionId, e);
|
|
608
653
|
}
|
|
609
654
|
} else {
|
|
610
655
|
// Progressive enhancement (form submitted before JS loaded)
|
|
@@ -634,6 +679,16 @@ async function handleFarmRequest(request) {
|
|
|
634
679
|
if (request.signal.aborted) {
|
|
635
680
|
return new Response(null, { status: 499, headers: { 'Cache-Control': 'no-store' } });
|
|
636
681
|
}
|
|
682
|
+
// No client router here, so the redirect has to be a real HTTP
|
|
683
|
+
// redirect the browser follows on its own.
|
|
684
|
+
const formRedirect = getFarmRedirectError(e);
|
|
685
|
+
if (formRedirect) {
|
|
686
|
+
debug('Form action redirected:', formRedirect.url);
|
|
687
|
+
return new Response(null, {
|
|
688
|
+
status: formRedirect.status,
|
|
689
|
+
headers: { location: formRedirect.url, 'Cache-Control': 'no-store' },
|
|
690
|
+
});
|
|
691
|
+
}
|
|
637
692
|
const actionError = sanitizeServerActionError(e);
|
|
638
693
|
if (actionError.name === 'ServerActionError') {
|
|
639
694
|
console.error('[Farm.js] Form action failed:', e);
|
|
@@ -915,7 +970,7 @@ async function handler(request, context) {
|
|
|
915
970
|
dispatch: async (localRequest) =>
|
|
916
971
|
(await handleAPIRequest(localRequest)) ?? Response.json({ error: 'Not Found' }, { status: 404 }),
|
|
917
972
|
}, () => _runWithCurrentRequest(request, () =>
|
|
918
|
-
_runWithAfterRequest(request, () => handleFarmRequest(request), context)
|
|
973
|
+
_runWithAfterRequest(request, () => handleFarmRequest(request, context), context)
|
|
919
974
|
));
|
|
920
975
|
}
|
|
921
976
|
|
package/dist/rsc/index.d.ts
CHANGED
|
@@ -25,6 +25,7 @@ import { type Plugin, type UserConfig } from "vite";
|
|
|
25
25
|
import type { FarmRscPluginOptions, EntryContext } from "./types.js";
|
|
26
26
|
import type { FarmServerActionsConfig } from "@farm.js/core/server-action-security";
|
|
27
27
|
import type { FarmAPIConfig } from "@farm.js/core/api";
|
|
28
|
+
import type { FarmMiddlewareConfig } from "@farm.js/core/middleware";
|
|
28
29
|
import type { FarmServerConfig } from "@farm.js/core/internal/production-runtime";
|
|
29
30
|
import type { FarmLayerEntry, ResolvedFarmLayer } from "@farm.js/core/server";
|
|
30
31
|
export type { FarmRscPluginOptions, EntryContext };
|
|
@@ -40,6 +41,7 @@ export interface FarmRscConfig {
|
|
|
40
41
|
basePath?: string;
|
|
41
42
|
api?: FarmAPIConfig;
|
|
42
43
|
server?: FarmServerConfig;
|
|
44
|
+
middleware?: FarmMiddlewareConfig;
|
|
43
45
|
port?: number;
|
|
44
46
|
experimental?: {
|
|
45
47
|
/**
|
package/dist/rsc/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/rsc/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/rsc/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAIL,KAAK,MAAM,EACX,KAAK,UAAU,EAChB,MAAM,MAAM,CAAC;AAEd,OAAO,KAAK,EAAE,oBAAoB,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AACrE,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,sCAAsC,CAAC;AACpF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AACrE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,2CAA2C,CAAC;AAClF,OAAO,KAAK,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AA2D9E,YAAY,EAAE,oBAAoB,EAAE,YAAY,EAAE,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAExF,YAAY,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAC7D,OAAO,EAAE,OAAO,IAAI,KAAK,EAAE,MAAM,wBAAwB,CAAC;AAC1D,YAAY,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAGjE,MAAM,WAAW,aAAa;IAC5B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,SAAS,cAAc,EAAE,CAAC;IACpC,MAAM,CAAC,EAAE,SAAS,iBAAiB,EAAE,CAAC;IACtC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,GAAG,CAAC,EAAE,aAAa,CAAC;IACpB,MAAM,CAAC,EAAE,gBAAgB,CAAC;IAC1B,UAAU,CAAC,EAAE,oBAAoB,CAAC;IAClC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,YAAY,CAAC,EAAE;QACb;;;WAGG;QACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;QAC3B;;;WAGG;QACH,aAAa,CAAC,EAAE,OAAO,CAAC;QACxB;;;;;;;WAOG;QACH,iBAAiB,CAAC,EAAE,OAAO,CAAC;KAC7B,CAAC;IACF,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,aAAa,CAAC,EAAE,uBAAuB,CAAC;IACxC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,eAAe,CAAC,EAAE,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACjD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE;QACR,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,MAAM,CAAC,EAAE,MAAM,CAAC;KACjB,CAAC;IACF,gHAAgH;IAChH,OAAO,CAAC,EAAE,GAAG,EAAE,CAAC;CACjB;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,MAAM,GAAE,aAAkB,GAAG,UAAU,CAuDnE;AAuXD;;;;;GAKG;AACH,MAAM,CAAC,OAAO,UAAU,OAAO,CAAC,OAAO,GAAE,oBAAyB,GAAG,MAAM,EAAE,CA8yC5E"}
|
package/dist/rsc/index.js
CHANGED
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
* })
|
|
22
22
|
* ```
|
|
23
23
|
*/
|
|
24
|
-
import { parseAst } from "vite";
|
|
24
|
+
import { parseAst, version as viteVersion, } from "vite";
|
|
25
25
|
import { init as initModuleLexer, parse as parseModuleImports } from "es-module-lexer";
|
|
26
26
|
import { farmEnvironmentFunctionsPlugin } from "@farm.js/core/environment/vite";
|
|
27
27
|
import { generateClientCachePersistenceCode, resolveFarmClientCacheAdapterEntry, } from "@farm.js/core/vite";
|
|
@@ -35,6 +35,7 @@ import { transformAutomaticOptimizedBoundaries } from "./automatic-optimized-bou
|
|
|
35
35
|
import { resolveRscBuildOutputPath } from "./build-paths.js";
|
|
36
36
|
import { assertRscPackageCompatibility } from "./compatibility.js";
|
|
37
37
|
import { sendRscDevelopmentResponse } from "./dev-response.js";
|
|
38
|
+
import { loadRscMiddlewareConfigModule } from "./middleware-config-module.js";
|
|
38
39
|
import fs from "fs/promises";
|
|
39
40
|
import path from "path";
|
|
40
41
|
import { devServableFileExists } from "../dev-static.js";
|
|
@@ -46,7 +47,7 @@ const { farmApiPlugin, farmMiddlewarePlugin } = require_("@farm.js/core");
|
|
|
46
47
|
const { resolveServerActionsConfig, validateServerActionRequest, createServerActionRequestErrorResponse, } = require_("@farm.js/core/server-action-security");
|
|
47
48
|
const { normalizeFarmDeploymentId } = require_("@farm.js/core/deployment");
|
|
48
49
|
const { getFarmLayerAliases, getFarmSourceRoots, resolveFarmLayers } = require_("@farm.js/core/server");
|
|
49
|
-
const { searchParamsToObject, readNodeRequestBody, resolveFarmServerConfig, createFarmRequestBodyErrorResponse, } = require_("@farm.js/core/internal/production-runtime");
|
|
50
|
+
const { searchParamsToObject, readNodeRequestBody, resolveFarmServerConfig, resolveFarmI18nConfig, createFarmRequestBodyErrorResponse, } = require_("@farm.js/core/internal/production-runtime");
|
|
50
51
|
const { isFarmAPIPathname } = require_("@farm.js/core/api/runtime");
|
|
51
52
|
const { resolveFarmAPIConfig, resolveFarmAPIServerBasePath } = require_("@farm.js/core/api");
|
|
52
53
|
const { getResolvedEnv } = require_("@farm.js/core/env");
|
|
@@ -175,7 +176,58 @@ const VIRTUAL_CLIENT_ENTRY = "virtual:@farm.js/rsc/entry-client";
|
|
|
175
176
|
const VIRTUAL_HYDRATE_ENTRY = "virtual:@farm.js/rsc/hydrate";
|
|
176
177
|
const OPTIMIZED_BOUNDARY_ADAPTER = "@farm.js/plugin/rsc/optimized-boundary";
|
|
177
178
|
const STRATA_PACKAGE = "@farming-labs/strata";
|
|
179
|
+
const RSC_MIDDLEWARE_CONFIG_QUERY = "?farm-rsc-middleware";
|
|
178
180
|
const FARM_CORE_PACKAGE_ROOT = path.resolve(path.dirname(require_.resolve("@farm.js/core")), "..");
|
|
181
|
+
const FARM_CONFIG_FILENAMES = [
|
|
182
|
+
"farm.config.ts",
|
|
183
|
+
"farm.config.tsx",
|
|
184
|
+
"farm.config.mts",
|
|
185
|
+
"farm.config.cts",
|
|
186
|
+
"farm.config.js",
|
|
187
|
+
"farm.config.jsx",
|
|
188
|
+
"farm.config.mjs",
|
|
189
|
+
"farm.config.cjs",
|
|
190
|
+
"config.ts",
|
|
191
|
+
"config.tsx",
|
|
192
|
+
"config.mts",
|
|
193
|
+
"config.cts",
|
|
194
|
+
"config.js",
|
|
195
|
+
"config.jsx",
|
|
196
|
+
"config.mjs",
|
|
197
|
+
"config.cjs",
|
|
198
|
+
];
|
|
199
|
+
function hasFarmMiddlewareConfig(config) {
|
|
200
|
+
if (!config)
|
|
201
|
+
return false;
|
|
202
|
+
if (Array.isArray(config))
|
|
203
|
+
return config.length > 0;
|
|
204
|
+
const entry = config;
|
|
205
|
+
return Boolean(entry.matcher ||
|
|
206
|
+
entry.exclude ||
|
|
207
|
+
entry.runtime ||
|
|
208
|
+
entry.handler ||
|
|
209
|
+
(Array.isArray(entry.handlers) && entry.handlers.length > 0));
|
|
210
|
+
}
|
|
211
|
+
async function findFarmConfigPath(root) {
|
|
212
|
+
for (const fileName of FARM_CONFIG_FILENAMES) {
|
|
213
|
+
const candidate = path.join(root, fileName);
|
|
214
|
+
try {
|
|
215
|
+
if ((await fs.stat(candidate)).isFile())
|
|
216
|
+
return candidate;
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
// Continue checking supported config names.
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return null;
|
|
223
|
+
}
|
|
224
|
+
async function resolveMiddlewareConfigPaths(root, layers) {
|
|
225
|
+
const paths = (layers ?? []).flatMap((layer) => layer.configFile ? [path.resolve(layer.configFile)] : []);
|
|
226
|
+
const projectConfigPath = await findFarmConfigPath(root);
|
|
227
|
+
if (projectConfigPath)
|
|
228
|
+
paths.push(projectConfigPath);
|
|
229
|
+
return [...new Set(paths)];
|
|
230
|
+
}
|
|
179
231
|
function isOptimizedBoundaryModule(id) {
|
|
180
232
|
return (id === OPTIMIZED_BOUNDARY_ADAPTER ||
|
|
181
233
|
id === STRATA_PACKAGE ||
|
|
@@ -390,11 +442,40 @@ export default function farmRsc(options = {}) {
|
|
|
390
442
|
let bodySizeLimit = resolveFarmServerConfig(undefined).bodySizeLimit;
|
|
391
443
|
// Context passed to entry generators
|
|
392
444
|
let entryContext;
|
|
393
|
-
/** Set in config when RSC enabled; used by build plugin to run Nitro after client writeBundle. */
|
|
394
445
|
let rscBuildRoot;
|
|
446
|
+
const middlewareConfigModules = new Map();
|
|
395
447
|
// Store for debugging
|
|
396
448
|
const debug = options.debug ?? false;
|
|
397
449
|
const automaticDeploymentId = `build-${Date.now()}`;
|
|
450
|
+
const supportsBuildAppHook = Number(viteVersion.split(".")[0]) >= 7;
|
|
451
|
+
const runNitroAfterApplicationBuild = async (builder) => {
|
|
452
|
+
const nitroEnabled = builder.config?.plugins?.some((plugin) => plugin.name === "vite-plugin-nitro");
|
|
453
|
+
if (!nitroEnabled || !rscBuildRoot)
|
|
454
|
+
return;
|
|
455
|
+
const { runNitroFromBuildApp } = await import("./vite-plugin-nitro.js");
|
|
456
|
+
if (globalThis.__FARM_NITRO_PATHS) {
|
|
457
|
+
await runNitroFromBuildApp();
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
// Vite creates environment-specific plugin instances by default, so state
|
|
461
|
+
// captured by a Rollup hook is not guaranteed to be visible here. Resolve
|
|
462
|
+
// the final environment outputs directly when that state is unavailable.
|
|
463
|
+
const rscBuild = builder.environments.rsc?.config?.build;
|
|
464
|
+
const ssrBuild = builder.environments.ssr?.config?.build;
|
|
465
|
+
const clientBuild = builder.environments.client?.config?.build;
|
|
466
|
+
if (!rscBuild?.outDir || !ssrBuild?.outDir || !clientBuild?.outDir)
|
|
467
|
+
return;
|
|
468
|
+
const { buildRscNitro } = await import("./nitro-build.js");
|
|
469
|
+
const root = path.resolve(rscBuildRoot);
|
|
470
|
+
await buildRscNitro({
|
|
471
|
+
root,
|
|
472
|
+
rendererPath: resolveRscBuildOutputPath(root, rscBuild.outDir, "index.js"),
|
|
473
|
+
publicDir: resolveRscBuildOutputPath(root, clientBuild.outDir),
|
|
474
|
+
ssrPath: resolveRscBuildOutputPath(root, ssrBuild.outDir, "index.js"),
|
|
475
|
+
assetsDir: clientBuild.assetsDir,
|
|
476
|
+
preset: process.env.NITRO_PRESET || "vercel",
|
|
477
|
+
});
|
|
478
|
+
};
|
|
398
479
|
const getColors = () => {
|
|
399
480
|
try {
|
|
400
481
|
const pico = require_("picocolors");
|
|
@@ -452,6 +533,18 @@ export default function farmRsc(options = {}) {
|
|
|
452
533
|
};
|
|
453
534
|
return [
|
|
454
535
|
farmEnvironmentFunctionsPlugin(),
|
|
536
|
+
{
|
|
537
|
+
name: "@farm.js/plugin/rsc:middleware-config",
|
|
538
|
+
enforce: "pre",
|
|
539
|
+
resolveId(id) {
|
|
540
|
+
if (!id.endsWith(RSC_MIDDLEWARE_CONFIG_QUERY))
|
|
541
|
+
return null;
|
|
542
|
+
return id.replace(/\\/g, "/");
|
|
543
|
+
},
|
|
544
|
+
load(id) {
|
|
545
|
+
return middlewareConfigModules.get(id.replace(/\\/g, "/")) ?? null;
|
|
546
|
+
},
|
|
547
|
+
},
|
|
455
548
|
{
|
|
456
549
|
name: "@farm.js/plugin/rsc:core-runtime",
|
|
457
550
|
// Run after Vite/esbuild has lowered TS/JSX. es-module-lexer deliberately
|
|
@@ -511,6 +604,31 @@ export default function farmRsc(options = {}) {
|
|
|
511
604
|
});
|
|
512
605
|
Object.assign(c, layerResolution.config);
|
|
513
606
|
}
|
|
607
|
+
middlewareConfigModules.clear();
|
|
608
|
+
const middlewareConfigPaths = [];
|
|
609
|
+
if (hasFarmMiddlewareConfig(c.middleware)) {
|
|
610
|
+
const configPaths = await resolveMiddlewareConfigPaths(root, c.layers);
|
|
611
|
+
if (configPaths.length === 0) {
|
|
612
|
+
throw new Error("[Farm.js] RSC config middleware requires an importable farm.config file. " +
|
|
613
|
+
"Move the middleware to farm.config.ts or src/app/middleware.ts.");
|
|
614
|
+
}
|
|
615
|
+
for (const configPath of configPaths) {
|
|
616
|
+
const extracted = await loadRscMiddlewareConfigModule(configPath);
|
|
617
|
+
if (extracted.kind === "unsupported") {
|
|
618
|
+
throw new Error(`[Farm.js] Cannot extract RSC config middleware from ${configPath}: ${extracted.reason}. ` +
|
|
619
|
+
"Declare middleware directly in defineConfig({ middleware: ... }) or move it to src/app/middleware.ts.");
|
|
620
|
+
}
|
|
621
|
+
if (extracted.kind === "absent")
|
|
622
|
+
continue;
|
|
623
|
+
const moduleId = `${configPath.replace(/\\/g, "/")}${RSC_MIDDLEWARE_CONFIG_QUERY}`;
|
|
624
|
+
middlewareConfigModules.set(moduleId, extracted.code);
|
|
625
|
+
middlewareConfigPaths.push(moduleId);
|
|
626
|
+
}
|
|
627
|
+
if (middlewareConfigPaths.length === 0) {
|
|
628
|
+
throw new Error("[Farm.js] RSC config middleware could not be traced to an explicit middleware property. " +
|
|
629
|
+
"Declare middleware directly in defineConfig({ middleware: ... }) or move it to src/app/middleware.ts.");
|
|
630
|
+
}
|
|
631
|
+
}
|
|
514
632
|
// Read user's directory configuration
|
|
515
633
|
const api = await resolveFarmAPIConfig(c.api, {
|
|
516
634
|
root,
|
|
@@ -568,6 +686,15 @@ export default function farmRsc(options = {}) {
|
|
|
568
686
|
allowedOrigins: options.serverActions?.allowedOrigins ?? c.serverActions?.allowedOrigins,
|
|
569
687
|
}),
|
|
570
688
|
deploymentId,
|
|
689
|
+
// Resolved the same way core resolves it for the config, so RSC and
|
|
690
|
+
// non-RSC apps match middleware against the same pathname.
|
|
691
|
+
i18n: resolveFarmI18nConfig(c.i18n, {
|
|
692
|
+
root,
|
|
693
|
+
mode: env.command === "serve" ? "development" : "production",
|
|
694
|
+
basePath: c.basePath ?? "/",
|
|
695
|
+
}),
|
|
696
|
+
server: { trustProxy: resolveFarmServerConfig(c.server).trustProxy },
|
|
697
|
+
middlewareConfigPaths,
|
|
571
698
|
debug,
|
|
572
699
|
development: env.command === "serve",
|
|
573
700
|
clientCachePersistence: generateClientCachePersistenceCode(resolveFarmClientCacheAdapterEntry(root, c.cache)),
|
|
@@ -791,38 +918,38 @@ export default function farmRsc(options = {}) {
|
|
|
791
918
|
};
|
|
792
919
|
},
|
|
793
920
|
},
|
|
794
|
-
// Nitro: run after all environments (like @hiogawa/vite-plugin-nitro). If the runtime supports
|
|
795
|
-
// plugin buildApp order "post", this runs automatically; else use build script (see comment below).
|
|
796
921
|
{
|
|
797
|
-
name: "@farm.js/plugin/rsc:nitro-build",
|
|
922
|
+
name: "@farm.js/plugin/rsc:nitro-application-build",
|
|
923
|
+
enforce: "post",
|
|
798
924
|
apply: "build",
|
|
925
|
+
// @vitejs/plugin-rsc owns the Vite 6 builder callback. Wrap its final
|
|
926
|
+
// callback after config composition so Nitro starts only after the RSC,
|
|
927
|
+
// client, and SSR outputs have all been written.
|
|
928
|
+
config(config) {
|
|
929
|
+
const builderConfig = config.builder;
|
|
930
|
+
const buildApp = builderConfig?.buildApp;
|
|
931
|
+
if (typeof buildApp !== "function")
|
|
932
|
+
return;
|
|
933
|
+
return {
|
|
934
|
+
builder: {
|
|
935
|
+
...builderConfig,
|
|
936
|
+
async buildApp(builder) {
|
|
937
|
+
await buildApp(builder);
|
|
938
|
+
if (!supportsBuildAppHook) {
|
|
939
|
+
await runNitroAfterApplicationBuild(builder);
|
|
940
|
+
}
|
|
941
|
+
},
|
|
942
|
+
},
|
|
943
|
+
};
|
|
944
|
+
},
|
|
945
|
+
// Vite 7+ composes application build hooks directly. Keep the Vite 6
|
|
946
|
+
// wrapper above for the versions where this hook is not dispatched.
|
|
799
947
|
buildApp: {
|
|
800
948
|
order: "post",
|
|
801
|
-
|
|
802
|
-
if (
|
|
803
|
-
|
|
804
|
-
if (globalThis.__FARM_NITRO_PLUGIN_RAN)
|
|
805
|
-
return;
|
|
806
|
-
const root = path.resolve(rscBuildRoot);
|
|
807
|
-
if (globalThis.__FARM_NITRO_PATHS) {
|
|
808
|
-
const { runNitroFromBuildApp } = await import("./vite-plugin-nitro.js");
|
|
809
|
-
await runNitroFromBuildApp();
|
|
810
|
-
return;
|
|
949
|
+
async handler(builder) {
|
|
950
|
+
if (supportsBuildAppHook) {
|
|
951
|
+
await runNitroAfterApplicationBuild(builder);
|
|
811
952
|
}
|
|
812
|
-
const rscEnv = builder.environments?.rsc;
|
|
813
|
-
const ssrEnv = builder.environments?.ssr;
|
|
814
|
-
const clientEnv = builder.environments?.client;
|
|
815
|
-
if (!rscEnv || !ssrEnv || !clientEnv)
|
|
816
|
-
return;
|
|
817
|
-
const { buildRscNitro } = await import("./nitro-build.js");
|
|
818
|
-
await buildRscNitro({
|
|
819
|
-
root,
|
|
820
|
-
rendererPath: resolveRscBuildOutputPath(root, rscEnv.config.build.outDir, "index.js"),
|
|
821
|
-
publicDir: resolveRscBuildOutputPath(root, clientEnv.config.build.outDir),
|
|
822
|
-
ssrPath: resolveRscBuildOutputPath(root, ssrEnv.config.build.outDir, "index.js"),
|
|
823
|
-
assetsDir: clientEnv.config.build.assetsDir,
|
|
824
|
-
preset: process.env.NITRO_PRESET || "vercel",
|
|
825
|
-
});
|
|
826
953
|
},
|
|
827
954
|
},
|
|
828
955
|
},
|
|
@@ -922,6 +1049,12 @@ setServerCallback(async (id, args) => {
|
|
|
922
1049
|
if (!res.ok) throw new Error('Server action failed: ' + res.status);
|
|
923
1050
|
const p = await createFromReadableStream(res.body, { temporaryReferences: refs });
|
|
924
1051
|
if (p?.returnValue?.ok) return p.returnValue.data;
|
|
1052
|
+
// This entry hydrates a single page and has no client router, so a redirect
|
|
1053
|
+
// from the action becomes a full document navigation.
|
|
1054
|
+
if (p?.returnValue?.redirect?.url) {
|
|
1055
|
+
location.assign(p.returnValue.redirect.url);
|
|
1056
|
+
return;
|
|
1057
|
+
}
|
|
925
1058
|
throw createFarmServerFnTransportError(p?.returnValue?.data);
|
|
926
1059
|
});
|
|
927
1060
|
`
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
type AstNode = {
|
|
2
|
+
type: string;
|
|
3
|
+
start: number;
|
|
4
|
+
end: number;
|
|
5
|
+
[key: string]: unknown;
|
|
6
|
+
};
|
|
7
|
+
type ExtractionResult = {
|
|
8
|
+
kind: "module";
|
|
9
|
+
code: string;
|
|
10
|
+
} | {
|
|
11
|
+
kind: "absent";
|
|
12
|
+
} | {
|
|
13
|
+
kind: "unsupported";
|
|
14
|
+
reason: string;
|
|
15
|
+
};
|
|
16
|
+
export declare function extractRscMiddlewareConfigModule(source: string, program: AstNode): ExtractionResult;
|
|
17
|
+
export declare function loadRscMiddlewareConfigModule(configPath: string): Promise<ExtractionResult>;
|
|
18
|
+
export {};
|
|
19
|
+
//# sourceMappingURL=middleware-config-module.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware-config-module.d.ts","sourceRoot":"","sources":["../../src/rsc/middleware-config-module.ts"],"names":[],"mappings":"AAQA,KAAK,OAAO,GAAG;IACb,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC;IACZ,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB,CAAC;AASF,KAAK,gBAAgB,GACjB;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAChC;IAAE,IAAI,EAAE,QAAQ,CAAA;CAAE,GAClB;IAAE,IAAI,EAAE,aAAa,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AA6N5C,wBAAgB,gCAAgC,CAC9C,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,OAAO,GACf,gBAAgB,CA4IlB;AAiBD,wBAAsB,6BAA6B,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAejG"}
|