@farm.js/plugin 0.1.0-beta.99 → 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.
Files changed (36) hide show
  1. package/README.md +2 -2
  2. package/dist/api/index.d.ts +2 -0
  3. package/dist/api/index.d.ts.map +1 -1
  4. package/dist/api/index.js +43 -31
  5. package/dist/index.d.ts +1 -1
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/middleware/index.d.ts +2 -3
  9. package/dist/middleware/index.d.ts.map +1 -1
  10. package/dist/middleware/index.js +44 -10
  11. package/dist/middleware/matching.d.ts +8 -3
  12. package/dist/middleware/matching.d.ts.map +1 -1
  13. package/dist/middleware/matching.js +15 -7
  14. package/dist/observability/index.d.ts.map +1 -1
  15. package/dist/observability/index.js +7 -2
  16. package/dist/rsc/entries/client.d.ts.map +1 -1
  17. package/dist/rsc/entries/client.js +37 -2
  18. package/dist/rsc/entries/rsc.d.ts.map +1 -1
  19. package/dist/rsc/entries/rsc.js +77 -22
  20. package/dist/rsc/index.d.ts +2 -0
  21. package/dist/rsc/index.d.ts.map +1 -1
  22. package/dist/rsc/index.js +163 -30
  23. package/dist/rsc/middleware-config-module.d.ts +19 -0
  24. package/dist/rsc/middleware-config-module.d.ts.map +1 -0
  25. package/dist/rsc/middleware-config-module.js +355 -0
  26. package/dist/rsc/nitro-build.d.ts +2 -0
  27. package/dist/rsc/nitro-build.d.ts.map +1 -1
  28. package/dist/rsc/nitro-build.js +64 -39
  29. package/dist/rsc/server-fn-transform.d.ts.map +1 -1
  30. package/dist/rsc/server-fn-transform.js +177 -0
  31. package/dist/rsc/types.d.ts +20 -0
  32. package/dist/rsc/types.d.ts.map +1 -1
  33. package/dist/rsc/vite-plugin-nitro.d.ts +20 -7
  34. package/dist/rsc/vite-plugin-nitro.d.ts.map +1 -1
  35. package/dist/rsc/vite-plugin-nitro.js +51 -66
  36. package/package.json +5 -4
@@ -0,0 +1,355 @@
1
+ import path from "node:path";
2
+ function isNode(value) {
3
+ return Boolean(value &&
4
+ typeof value === "object" &&
5
+ typeof value.type === "string" &&
6
+ typeof value.start === "number" &&
7
+ typeof value.end === "number");
8
+ }
9
+ function bindingNames(pattern, names = []) {
10
+ if (!pattern)
11
+ return names;
12
+ if (pattern.type === "Identifier") {
13
+ names.push(pattern.name);
14
+ return names;
15
+ }
16
+ if (pattern.type === "RestElement") {
17
+ return bindingNames(pattern.argument, names);
18
+ }
19
+ if (pattern.type === "AssignmentPattern") {
20
+ return bindingNames(pattern.left, names);
21
+ }
22
+ if (pattern.type === "ArrayPattern") {
23
+ for (const element of pattern.elements ?? []) {
24
+ bindingNames(element, names);
25
+ }
26
+ return names;
27
+ }
28
+ if (pattern.type === "ObjectPattern") {
29
+ for (const property of pattern.properties ?? []) {
30
+ bindingNames(property.type === "RestElement"
31
+ ? property.argument
32
+ : property.value, names);
33
+ }
34
+ }
35
+ return names;
36
+ }
37
+ function isReferenceIdentifier(node, parent, key) {
38
+ if (!parent)
39
+ return true;
40
+ if ((parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") &&
41
+ key === "property" &&
42
+ parent.computed !== true) {
43
+ return false;
44
+ }
45
+ if ((parent.type === "Property" ||
46
+ parent.type === "PropertyDefinition" ||
47
+ parent.type === "MethodDefinition") &&
48
+ key === "key" &&
49
+ parent.computed !== true) {
50
+ return parent.shorthand === true;
51
+ }
52
+ if (parent.type === "VariableDeclarator")
53
+ return key !== "id";
54
+ if (parent.type === "FunctionDeclaration" ||
55
+ parent.type === "FunctionExpression" ||
56
+ parent.type === "ArrowFunctionExpression") {
57
+ return key !== "id" && key !== "params";
58
+ }
59
+ if (parent.type === "ClassDeclaration" || parent.type === "ClassExpression") {
60
+ return key !== "id";
61
+ }
62
+ if (parent.type === "CatchClause")
63
+ return key !== "param";
64
+ if (parent.type === "RestElement")
65
+ return false;
66
+ if (parent.type === "AssignmentPattern")
67
+ return key !== "left";
68
+ return ![
69
+ "ArrayPattern",
70
+ "BreakStatement",
71
+ "ContinueStatement",
72
+ "ExportSpecifier",
73
+ "ImportDefaultSpecifier",
74
+ "ImportNamespaceSpecifier",
75
+ "ImportSpecifier",
76
+ "LabeledStatement",
77
+ ].includes(parent.type);
78
+ }
79
+ function scopeBindings(node) {
80
+ const names = new Set();
81
+ if (node.type === "FunctionDeclaration" ||
82
+ node.type === "FunctionExpression" ||
83
+ node.type === "ArrowFunctionExpression") {
84
+ if (isNode(node.id))
85
+ bindingNames(node.id).forEach((name) => names.add(name));
86
+ for (const parameter of node.params ?? []) {
87
+ bindingNames(parameter).forEach((name) => names.add(name));
88
+ }
89
+ }
90
+ else if (node.type === "CatchClause" && isNode(node.param)) {
91
+ bindingNames(node.param).forEach((name) => names.add(name));
92
+ }
93
+ else if (node.type === "BlockStatement") {
94
+ for (const statement of node.body ?? []) {
95
+ const declaration = statement.type === "ExportNamedDeclaration" && isNode(statement.declaration)
96
+ ? statement.declaration
97
+ : statement;
98
+ if (declaration.type === "VariableDeclaration" && declaration.kind !== "var") {
99
+ for (const declarator of declaration.declarations ?? []) {
100
+ bindingNames(declarator.id).forEach((name) => names.add(name));
101
+ }
102
+ }
103
+ else if ((declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration") &&
104
+ isNode(declaration.id)) {
105
+ names.add(declaration.id.name);
106
+ }
107
+ }
108
+ }
109
+ return names;
110
+ }
111
+ function referencedTopLevelNames(node, candidates) {
112
+ const references = new Set();
113
+ const visit = (value, parent, key, scopes) => {
114
+ if (Array.isArray(value)) {
115
+ for (const child of value)
116
+ visit(child, parent, key, scopes);
117
+ return;
118
+ }
119
+ if (!isNode(value))
120
+ return;
121
+ const nodeScopes = [
122
+ ...scopes,
123
+ ...([
124
+ "ArrowFunctionExpression",
125
+ "BlockStatement",
126
+ "CatchClause",
127
+ "FunctionDeclaration",
128
+ "FunctionExpression",
129
+ ].includes(value.type)
130
+ ? [scopeBindings(value)]
131
+ : []),
132
+ ];
133
+ if (value.type === "Identifier") {
134
+ const name = value.name;
135
+ const shadowed = nodeScopes.some((scope) => scope.has(name));
136
+ if (candidates.has(name) && !shadowed && isReferenceIdentifier(value, parent, key)) {
137
+ references.add(name);
138
+ }
139
+ return;
140
+ }
141
+ for (const [childKey, child] of Object.entries(value)) {
142
+ if (childKey === "start" || childKey === "end" || childKey === "loc")
143
+ continue;
144
+ visit(child, value, childKey, nodeScopes);
145
+ }
146
+ };
147
+ visit(node, null, "", []);
148
+ return references;
149
+ }
150
+ function importBindingCode(statement, specifier, _source) {
151
+ const moduleSource = JSON.stringify(statement.source.value);
152
+ const local = specifier.local.name;
153
+ if (specifier.type === "ImportDefaultSpecifier") {
154
+ return `import ${local} from ${moduleSource};`;
155
+ }
156
+ if (specifier.type === "ImportNamespaceSpecifier") {
157
+ return `import * as ${local} from ${moduleSource};`;
158
+ }
159
+ const imported = specifier.imported;
160
+ const importedName = imported.type === "Identifier" ? imported.name : JSON.stringify(imported.value);
161
+ return `import { ${importedName}${importedName === local ? "" : ` as ${local}`} } from ${moduleSource};`;
162
+ }
163
+ function propertyName(property) {
164
+ if (property.computed === true)
165
+ return null;
166
+ const key = property.key;
167
+ if (key.type === "Identifier")
168
+ return key.name;
169
+ if (key.type === "Literal" && typeof key.value === "string")
170
+ return key.value;
171
+ return null;
172
+ }
173
+ function resolveConfigObject(node, variableInitializers, configHelpers, seen = new Set()) {
174
+ if (node.type === "ObjectExpression")
175
+ return node;
176
+ if (node.type === "CallExpression") {
177
+ const callee = node.callee;
178
+ const args = node.arguments ?? [];
179
+ if (callee.type === "Identifier" &&
180
+ configHelpers.has(callee.name) &&
181
+ args.length === 1) {
182
+ return resolveConfigObject(args[0], variableInitializers, configHelpers, seen);
183
+ }
184
+ return null;
185
+ }
186
+ if (node.type === "Identifier") {
187
+ const name = node.name;
188
+ if (seen.has(name))
189
+ return null;
190
+ const initializer = variableInitializers.get(name);
191
+ if (!initializer)
192
+ return null;
193
+ seen.add(name);
194
+ return resolveConfigObject(initializer, variableInitializers, configHelpers, seen);
195
+ }
196
+ return null;
197
+ }
198
+ export function extractRscMiddlewareConfigModule(source, program) {
199
+ const body = program.body ?? [];
200
+ const bindings = new Map();
201
+ const variableInitializers = new Map();
202
+ const configHelpers = new Set(["defineConfig", "defineFarmConfig"]);
203
+ let defaultExport = null;
204
+ let order = 0;
205
+ for (const statement of body) {
206
+ if (statement.type === "ImportDeclaration") {
207
+ const moduleName = statement.source.value;
208
+ for (const specifier of statement.specifiers ?? []) {
209
+ const local = specifier.local.name;
210
+ if (moduleName === "@farm.js/core" || moduleName === "@farm.js/core/config") {
211
+ const imported = specifier.imported;
212
+ const importedName = imported?.type === "Identifier" ? imported.name : undefined;
213
+ if (importedName === "defineConfig" || importedName === "defineFarmConfig") {
214
+ configHelpers.add(local);
215
+ }
216
+ }
217
+ bindings.set(local, {
218
+ names: [local],
219
+ order: order++,
220
+ render: () => importBindingCode(statement, specifier, source),
221
+ references: null,
222
+ });
223
+ }
224
+ continue;
225
+ }
226
+ if (statement.type === "ExportDefaultDeclaration") {
227
+ defaultExport = statement.declaration;
228
+ continue;
229
+ }
230
+ if (statement.type === "ExportNamedDeclaration") {
231
+ for (const specifier of statement.specifiers ?? []) {
232
+ const exported = specifier.exported;
233
+ if ((exported.type === "Identifier" && exported.name === "default") ||
234
+ (exported.type === "Literal" && exported.value === "default")) {
235
+ defaultExport = specifier.local;
236
+ }
237
+ }
238
+ }
239
+ const declaration = statement.type === "ExportNamedDeclaration" && isNode(statement.declaration)
240
+ ? statement.declaration
241
+ : statement;
242
+ if (declaration.type === "VariableDeclaration") {
243
+ for (const declarator of declaration.declarations ?? []) {
244
+ const names = bindingNames(declarator.id);
245
+ const initializer = isNode(declarator.init) ? declarator.init : null;
246
+ if (names.length === 1 && initializer)
247
+ variableInitializers.set(names[0], initializer);
248
+ const binding = {
249
+ names,
250
+ order: order++,
251
+ render: () => `${declaration.kind} ${source.slice(declarator.start, declarator.end)};`,
252
+ references: declarator,
253
+ };
254
+ for (const name of names)
255
+ bindings.set(name, binding);
256
+ }
257
+ continue;
258
+ }
259
+ if ((declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration") &&
260
+ isNode(declaration.id)) {
261
+ const name = declaration.id.name;
262
+ bindings.set(name, {
263
+ names: [name],
264
+ order: order++,
265
+ render: () => source.slice(declaration.start, declaration.end),
266
+ references: declaration,
267
+ });
268
+ }
269
+ }
270
+ if (!defaultExport) {
271
+ return { kind: "unsupported", reason: "the config has no default export" };
272
+ }
273
+ const configObject = resolveConfigObject(defaultExport, variableInitializers, configHelpers);
274
+ if (!configObject) {
275
+ return {
276
+ kind: "unsupported",
277
+ reason: "the default export is not a statically traceable defineConfig object",
278
+ };
279
+ }
280
+ const properties = configObject.properties ?? [];
281
+ let middlewareProperty = null;
282
+ let middlewareIndex = -1;
283
+ for (const [index, property] of properties.entries()) {
284
+ if (property.type === "Property" && propertyName(property) === "middleware") {
285
+ middlewareProperty = property;
286
+ middlewareIndex = index;
287
+ }
288
+ }
289
+ if (!middlewareProperty) {
290
+ if (properties.some((property) => property.type === "SpreadElement")) {
291
+ return {
292
+ kind: "unsupported",
293
+ reason: "middleware may be supplied through a config spread",
294
+ };
295
+ }
296
+ return { kind: "absent" };
297
+ }
298
+ if (properties.slice(middlewareIndex + 1).some((property) => property.type === "SpreadElement")) {
299
+ return {
300
+ kind: "unsupported",
301
+ reason: "a config spread after middleware may override it",
302
+ };
303
+ }
304
+ const middlewareValue = middlewareProperty.value;
305
+ const candidateNames = new Set(bindings.keys());
306
+ const selectedBindings = new Set();
307
+ const pending = [...referencedTopLevelNames(middlewareValue, candidateNames)];
308
+ while (pending.length > 0) {
309
+ const name = pending.pop();
310
+ const binding = bindings.get(name);
311
+ if (!binding || selectedBindings.has(binding))
312
+ continue;
313
+ selectedBindings.add(binding);
314
+ if (binding.references) {
315
+ for (const reference of referencedTopLevelNames(binding.references, candidateNames)) {
316
+ pending.push(reference);
317
+ }
318
+ }
319
+ }
320
+ const declarations = [...selectedBindings]
321
+ .sort((a, b) => a.order - b.order)
322
+ .map((binding) => binding.render());
323
+ const middlewareSource = source.slice(middlewareValue.start, middlewareValue.end);
324
+ return {
325
+ kind: "module",
326
+ code: `${declarations.join("\n")}${declarations.length ? "\n" : ""}export default { middleware: ${middlewareSource} };\n`,
327
+ };
328
+ }
329
+ function esbuildLoader(file) {
330
+ switch (path.extname(file)) {
331
+ case ".ts":
332
+ case ".mts":
333
+ case ".cts":
334
+ return "ts";
335
+ case ".tsx":
336
+ return "tsx";
337
+ case ".jsx":
338
+ return "jsx";
339
+ default:
340
+ return "js";
341
+ }
342
+ }
343
+ export async function loadRscMiddlewareConfigModule(configPath) {
344
+ const [{ readFile }, { parseAst, transformWithEsbuild }] = await Promise.all([
345
+ import("node:fs/promises"),
346
+ import("vite"),
347
+ ]);
348
+ const source = await readFile(configPath, "utf8");
349
+ const transformed = await transformWithEsbuild(source, configPath, {
350
+ format: "esm",
351
+ jsx: "automatic",
352
+ loader: esbuildLoader(configPath),
353
+ });
354
+ return extractRscMiddlewareConfigModule(transformed.code, parseAst(transformed.code));
355
+ }
@@ -8,6 +8,8 @@
8
8
  * self-contained even when the application does not install it directly.
9
9
  */
10
10
  export declare function registerRscNitroRuntimePackage(root: string, packageName: string, packageRoot: string): void;
11
+ /** @internal */
12
+ export declare function rewriteRscEntryImports(serverDir: string, serverDistDir: string): void;
11
13
  /**
12
14
  * Wait for the RSC plugin to write the assets manifest to dist/rsc (it may run after closeBundle(ssr)).
13
15
  * Polls until the file exists and size > MIN_MANIFEST_BYTES or timeout.
@@ -1 +1 @@
1
- {"version":3,"file":"nitro-build.d.ts","sourceRoot":"","sources":["../../src/rsc/nitro-build.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAwBH;;;GAGG;AACH,wBAAgB,8BAA8B,CAC5C,IAAI,EAAE,MAAM,EACZ,WAAW,EAAE,MAAM,EACnB,WAAW,EAAE,MAAM,GAClB,IAAI,CAKN;AAwFD;;;GAGG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,OAAO,GAAE;IAAE,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAO,GACxD,OAAO,CAAC,IAAI,CAAC,CA0Bf;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,OAAO,GAAE;IAAE,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAO,GACxD,OAAO,CAAC,IAAI,CAAC,CAgCf;AA0ED,MAAM,MAAM,oBAAoB,GAAG;IACjC,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,wBAAsB,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,IAAI,CAAC,CA8MhF"}
1
+ {"version":3,"file":"nitro-build.d.ts","sourceRoot":"","sources":["../../src/rsc/nitro-build.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAwBH;;;GAGG;AACH,wBAAgB,8BAA8B,CAC5C,IAAI,EAAE,MAAM,EACZ,WAAW,EAAE,MAAM,EACnB,WAAW,EAAE,MAAM,GAClB,IAAI,CAKN;AAcD,gBAAgB;AAChB,wBAAgB,sBAAsB,CAAC,SAAS,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,GAAG,IAAI,CA8BrF;AA4ED;;;GAGG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,OAAO,GAAE;IAAE,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAO,GACxD,OAAO,CAAC,IAAI,CAAC,CA0Bf;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,OAAO,GAAE;IAAE,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAO,GACxD,OAAO,CAAC,IAAI,CAAC,CAgCf;AAwFD,MAAM,MAAM,oBAAoB,GAAG;IACjC,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,wBAAsB,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,IAAI,CAAC,CAyLhF"}
@@ -39,6 +39,35 @@ function copyDir(src, dest, ignoredNames = new Set()) {
39
39
  copyFileSync(srcPath, destPath);
40
40
  }
41
41
  }
42
+ /** @internal */
43
+ export function rewriteRscEntryImports(serverDir, serverDistDir) {
44
+ const entryChunkPaths = [];
45
+ const findEntryChunks = (dir) => {
46
+ if (!existsSync(dir))
47
+ return;
48
+ for (const name of readdirSync(dir)) {
49
+ const candidate = path.join(dir, name);
50
+ if (statSync(candidate).isDirectory())
51
+ findEntryChunks(candidate);
52
+ else if (name === "rsc-entry.mjs")
53
+ entryChunkPaths.push(candidate);
54
+ }
55
+ };
56
+ for (const chunksDir of ["chunks", "_chunks", "_build"]) {
57
+ findEntryChunks(path.join(serverDir, chunksDir));
58
+ }
59
+ for (const entryChunkPath of entryChunkPaths) {
60
+ let code = readFileSync(entryChunkPath, "utf-8");
61
+ const relativeImport = (target) => {
62
+ const relative = path.relative(path.dirname(entryChunkPath), target).replace(/\\/g, "/");
63
+ return relative.startsWith(".") ? relative : `./${relative}`;
64
+ };
65
+ // Match any path that ends with dist/rsc/index.js or dist/ssr/index.js (minified, no spaces)
66
+ code = code.replace(/(["'`])[^"'`]*?dist\/rsc\/index\.js\1/g, JSON.stringify(relativeImport(path.join(serverDistDir, "rsc", "index.js"))));
67
+ code = code.replace(/(["'`])[^"'`]*?dist\/ssr\/index\.js\1/g, JSON.stringify(relativeImport(path.join(serverDistDir, "ssr", "index.js"))));
68
+ writeFileSync(entryChunkPath, code, "utf-8");
69
+ }
70
+ }
42
71
  function detectBundledRscRuntimes(rendererPath) {
43
72
  const packages = new Map();
44
73
  const rendererDir = path.dirname(path.resolve(rendererPath));
@@ -194,7 +223,8 @@ const handler = getFetchHandler(entryExports);
194
223
 
195
224
  function createRscRequest(event) {
196
225
  const node = event.node;
197
- if (!node?.req || !node?.res) return event.req;
226
+ const request = event.req?._request || event.req;
227
+ if (!node?.req || !node?.res) return request;
198
228
 
199
229
  const controller = new AbortController();
200
230
  const cleanup = () => {
@@ -216,12 +246,25 @@ function createRscRequest(event) {
216
246
  node.res.once("finish", cleanup);
217
247
  if (node.req.aborted) abort();
218
248
 
219
- return new Request(event.req, { signal: controller.signal });
249
+ return new Request(request, { signal: controller.signal });
250
+ }
251
+
252
+ // The peer address the server adapter already knows; the rebuilt Request has
253
+ // no socket. Mirrors h3's getRequestIP without the forwarded header, which only
254
+ // trustProxy may honor.
255
+ function resolveClientAddress(event) {
256
+ try {
257
+ return event.req?.context?.clientAddress || event.req?.ip ||
258
+ event.node?.req?.socket?.remoteAddress || undefined;
259
+ } catch {
260
+ return undefined;
261
+ }
220
262
  }
221
263
 
222
264
  export default defineEventHandler(async (event) => {
223
265
  const response = await handler(createRscRequest(event), {
224
266
  waitUntil: (promise) => event.waitUntil(promise),
267
+ clientAddress: resolveClientAddress(event),
225
268
  });
226
269
  // H3's prepared headers override Response headers. Keep both the runtime's
227
270
  // fields (e.g. Accept-Encoding from static middleware) and the app's fields.
@@ -241,7 +284,7 @@ export default defineEventHandler(async (event) => {
241
284
  }
242
285
  export async function buildRscNitro(options) {
243
286
  const { rendererPath, publicDir, ssrPath, assetsDir, root, outputDir = path.join(root, ".output"), preset = "vercel", } = options;
244
- const { build, copyPublicAssets, createNitro, prepare } = await import("nitro");
287
+ const { build, copyPublicAssets, createNitro, prepare } = await import("nitro/builder");
245
288
  console.log(`[FARM] Building RSC server with Nitro (preset: ${preset})...`);
246
289
  const buildDir = path.join(root, ".nitro");
247
290
  const serverDir = path.join(outputDir, "server");
@@ -263,23 +306,28 @@ export async function buildRscNitro(options) {
263
306
  }
264
307
  const config = {
265
308
  preset,
309
+ // The RSC plugin supports Vite 6+, while Nitro's beta Vite builder follows
310
+ // its own Vite 8 peer range. The prebuilt renderer works with Rolldown and
311
+ // keeps the app's Vite version out of Nitro's production build contract.
312
+ builder: "rolldown",
266
313
  rootDir: root,
267
- srcDir: root,
314
+ serverDir: root,
268
315
  buildDir,
269
316
  dev: false,
317
+ alias: {
318
+ h3: runtimeRequire.resolve("h3"),
319
+ },
270
320
  output: {
271
321
  dir: outputDir,
272
322
  serverDir,
273
323
  publicDir: publicOutDir,
274
324
  },
275
325
  publicAssets,
276
- renderer: { entry: entryPath },
326
+ renderer: { handler: entryPath },
277
327
  // The prebuilt RSC/SSR bundles are copied after Nitro finishes, so Nitro's
278
328
  // module graph cannot otherwise see their bare package imports. Trace both
279
329
  // entry points explicitly to keep node-server output self-contained.
280
- externals: {
281
- traceInclude: [rendererPath, ...(ssrPath ? [ssrPath] : [])],
282
- },
330
+ traceDeps: [rendererPath, ...(ssrPath ? [ssrPath] : [])],
283
331
  // Externalize rsc/ssr so we don't bundle (they reference Vite-generated manifest). We copy dist into server output after build.
284
332
  rollupConfig: {
285
333
  external: (id) => {
@@ -316,33 +364,9 @@ export async function buildRscNitro(options) {
316
364
  mkdirSync(rscDestDir, { recursive: true });
317
365
  writeFileSync(manifestDest, "export default { serverResources: {}, clientReferenceDeps: {} };", "utf-8");
318
366
  }
319
- // Nitro may group the entry under chunks/build or chunks/_ depending on the
320
- // selected builder. Find it by name and make copied-dist imports relative to
321
- // the emitted chunk so the output survives being moved away from the project.
322
- const entryChunkPaths = [];
323
- const findEntryChunks = (dir) => {
324
- if (!existsSync(dir))
325
- return;
326
- for (const name of readdirSync(dir)) {
327
- const candidate = path.join(dir, name);
328
- if (statSync(candidate).isDirectory())
329
- findEntryChunks(candidate);
330
- else if (name === "rsc-entry.mjs")
331
- entryChunkPaths.push(candidate);
332
- }
333
- };
334
- findEntryChunks(path.join(serverDir, "chunks"));
335
- for (const entryChunkPath of entryChunkPaths) {
336
- let code = readFileSync(entryChunkPath, "utf-8");
337
- const relativeImport = (target) => {
338
- const relative = path.relative(path.dirname(entryChunkPath), target).replace(/\\/g, "/");
339
- return relative.startsWith(".") ? relative : `./${relative}`;
340
- };
341
- // Match any path that ends with dist/rsc/index.js or dist/ssr/index.js (minified, no spaces)
342
- code = code.replace(/(["'`])[^"'`]*?dist\/rsc\/index\.js\1/g, JSON.stringify(relativeImport(path.join(serverDistDir, "rsc", "index.js"))));
343
- code = code.replace(/(["'`])[^"'`]*?dist\/ssr\/index\.js\1/g, JSON.stringify(relativeImport(path.join(serverDistDir, "ssr", "index.js"))));
344
- writeFileSync(entryChunkPath, code, "utf-8");
345
- }
367
+ // Nitro may group the entry differently by builder. Make copied-dist imports
368
+ // relative to the emitted chunk so output survives moving away from the project.
369
+ rewriteRscEntryImports(serverDir, serverDistDir);
346
370
  // Patch SSR bundle: inject production client CSS href and bootstrap script so HTML has styles and hydration works
347
371
  const ssrIndexPath = path.join(serverDistDir, "ssr", "index.js");
348
372
  const manifestPath = path.join(serverDistDir, "rsc", MANIFEST_FILENAME);
@@ -385,13 +409,14 @@ export async function buildRscNitro(options) {
385
409
  }
386
410
  }
387
411
  if (existsSync(ssrIndexPath)) {
388
- const assetsDir = path.join(publicDir, "assets");
412
+ const assetsDirName = assetsDir ?? "assets";
413
+ const assetsRoot = path.join(publicDir, assetsDirName);
389
414
  let clientCssHref = "";
390
- if (existsSync(assetsDir)) {
391
- const files = readdirSync(assetsDir);
415
+ if (existsSync(assetsRoot)) {
416
+ const files = readdirSync(assetsRoot);
392
417
  const cssFile = files.find((f) => f.endsWith(".css"));
393
418
  if (cssFile)
394
- clientCssHref = "/assets/" + cssFile;
419
+ clientCssHref = `/${assetsDirName}/${cssFile}`;
395
420
  }
396
421
  try {
397
422
  let ssrCode = readFileSync(ssrIndexPath, "utf-8");
@@ -1 +1 @@
1
- {"version":3,"file":"server-fn-transform.d.ts","sourceRoot":"","sources":["../../src/rsc/server-fn-transform.ts"],"names":[],"mappings":"AAOA,MAAM,MAAM,2BAA2B,GAAG;IACxC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,EAAE,CAAC;CACnB,CAAC;AAEF,wBAAgB,sBAAsB,CACpC,IAAI,EAAE,MAAM,EACZ,EAAE,EAAE,MAAM,GACT,2BAA2B,GAAG,IAAI,CAiCpC"}
1
+ {"version":3,"file":"server-fn-transform.d.ts","sourceRoot":"","sources":["../../src/rsc/server-fn-transform.ts"],"names":[],"mappings":"AAkBA,MAAM,MAAM,2BAA2B,GAAG;IACxC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,EAAE,CAAC;CACnB,CAAC;AAEF,wBAAgB,sBAAsB,CACpC,IAAI,EAAE,MAAM,EACZ,EAAE,EAAE,MAAM,GACT,2BAA2B,GAAG,IAAI,CAoDpC"}