@vitejs/plugin-rsc 0.5.10 → 0.5.12

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 CHANGED
@@ -224,11 +224,13 @@ The plugin provides an additional helper for multi environment interaction.
224
224
 
225
225
  #### `import.meta.viteRsc.loadModule`
226
226
 
227
- - Type: `(environmentName: "ssr" | "rsc", entryName: string) => Promise<T>`
227
+ - Type: `(environmentName: "ssr" | "rsc", entryName?: string) => Promise<T>`
228
228
 
229
- This allows importing `ssr` environment module specified by `environments.ssr.build.rollupOptions.input[entryName]` inside `rsc` environment and vice versa.
229
+ This allows importing `ssr` environment module specified by `environments.ssr.build.rollupOptions.input[entryName]` inside `rsc` environment and vice versa. When `entryName` is omitted, the function automatically uses the single entry from the target environment's `rollupOptions.input`.
230
230
 
231
- During development, by default, this API assumes both `rsc` and `ssr` environments execute under the main Vite process. When enabling `rsc({ loadModuleDevProxy: true })` plugin option, the loaded module is implemented as a proxy with `fetch`-based RPC to call in node environment on the main Vite process, which for example, allows `rsc` environment inside cloudflare workers to access `ssr` environment on the main Vite process. This proxy mechanism uses [turbo-stream](https://github.com/jacob-ebey/turbo-stream) for serializing data types beyond JSON, with custom encoders/decoders to additionally support `Request` and `Response` instances.
231
+ During development, by default, this API assumes both `rsc` and `ssr` environments execute under the main Vite process as `RunnableDevEnvironment`. Internally, `loadModule` uses the global `__VITE_ENVIRONMENT_RUNNER_IMPORT__` function to import modules in the target environment (see [`__VITE_ENVIRONMENT_RUNNER_IMPORT__`](#__vite_environment_runner_import__) below).
232
+
233
+ When enabling `rsc({ loadModuleDevProxy: true })` plugin option, the loaded module is implemented as a proxy with `fetch`-based RPC to call in node environment on the main Vite process, which for example, allows `rsc` environment inside cloudflare workers to access `ssr` environment on the main Vite process. This proxy mechanism uses [turbo-stream](https://github.com/jacob-ebey/turbo-stream) for serializing data types beyond JSON, with custom encoders/decoders to additionally support `Request` and `Response` instances.
232
234
 
233
235
  During production build, this API will be rewritten into a static import of the specified entry of other environment build and the modules are executed inside the same runtime.
234
236
 
@@ -327,6 +329,35 @@ import.meta.hot.on('rsc:update', async () => {
327
329
  })
328
330
  ```
329
331
 
332
+ ### Global API
333
+
334
+ #### `__VITE_ENVIRONMENT_RUNNER_IMPORT__`
335
+
336
+ - Type: `(environmentName: string, id: string) => Promise<any>`
337
+
338
+ This global function provides a standardized way to import a module in a given environment during development. It is used internally by `import.meta.viteRsc.loadModule` to execute modules in the target environment.
339
+
340
+ By default, the plugin sets this global to import via the environment's module runner:
341
+
342
+ ```js
343
+ globalThis.__VITE_ENVIRONMENT_RUNNER_IMPORT__ = async (environmentName, id) => {
344
+ return server.environments[environmentName].runner.import(id)
345
+ }
346
+ ```
347
+
348
+ **Custom Environment Integration:**
349
+
350
+ Frameworks with custom environment setups (e.g., environments running in separate workers or with custom module loading) can override this global to provide their own module import logic.
351
+
352
+ ```js
353
+ // Custom logic to import module between multiple environments inside worker
354
+ globalThis.__VITE_ENVIRONMENT_RUNNER_IMPORT__ = async (environmentName, id) => {
355
+ return myWorkerRunners[environmentname].import(id)
356
+ }
357
+ ```
358
+
359
+ This allows `import.meta.viteRsc.loadModule` to work seamlessly with different runtime configurations without requiring changes to user code.
360
+
330
361
  ## Plugin API
331
362
 
332
363
  ### `@vitejs/plugin-rsc`
@@ -519,7 +550,7 @@ Types for global API are defined in `@vitejs/plugin-rsc/types`. For example, you
519
550
  ```ts
520
551
  import.meta.viteRsc.loadModule
521
552
  // ^^^^^^^^^^
522
- // <T>(environmentName: string, entryName: string) => Promise<T>
553
+ // <T>(environmentName: string, entryName?: string) => Promise<T>
523
554
  ```
524
555
 
525
556
  See also [Vite documentation](https://vite.dev/guide/api-hmr.html#intellisense-for-typescript) for `vite/client` types.
@@ -26,7 +26,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
26
26
  value: mod,
27
27
  enumerable: true
28
28
  }) : target, mod));
29
- var __toDynamicImportESM = (isNodeMode) => (mod) => __toESM(mod.default, isNodeMode);
30
29
 
31
30
  //#endregion
32
- export { __toDynamicImportESM as n, __commonJSMin as t };
31
+ export { __toESM as n, __commonJSMin as t };
@@ -1,5 +1,5 @@
1
- import { t as createDebug } from "./dist-BRSdGcl7.js";
2
- import { n as parseIdQuery } from "./shared-AtH_QTi7.js";
1
+ import { t as createDebug } from "./dist-DZUJDIM2.js";
2
+ import { n as parseIdQuery } from "./shared-Chot7h9j.js";
3
3
  import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -1,4 +1,4 @@
1
- import { n as memoize } from "../dist-BRSdGcl7.js";
1
+ import { n as memoize } from "../dist-DZUJDIM2.js";
2
2
  import { a as setInternalRequire, i as removeReferenceCacheTag } from "../shared-DEpnONZf.js";
3
3
 
4
4
  //#region src/core/browser.ts
@@ -1,3 +1,3 @@
1
- import { t as vitePluginRscCore } from "../plugin-D1MQNdps.js";
1
+ import { t as vitePluginRscCore } from "../plugin-B1AJWrMi.js";
2
2
 
3
3
  export { vitePluginRscCore as default };
package/dist/core/rsc.js CHANGED
@@ -1,3 +1,3 @@
1
- import { a as setRequireModule, i as loadServerAction, n as createServerDecodeClientManifest, r as createServerManifest, t as createClientManifest } from "../rsc-BRh4PjTs.js";
1
+ import { a as setRequireModule, i as loadServerAction, n as createServerDecodeClientManifest, r as createServerManifest, t as createClientManifest } from "../rsc-DRNoX2Q6.js";
2
2
 
3
3
  export { createClientManifest, createServerDecodeClientManifest, createServerManifest, loadServerAction, setRequireModule };
package/dist/core/ssr.js CHANGED
@@ -1,4 +1,4 @@
1
- import { n as memoize } from "../dist-BRSdGcl7.js";
1
+ import { n as memoize } from "../dist-DZUJDIM2.js";
2
2
  import { a as setInternalRequire, i as removeReferenceCacheTag } from "../shared-DEpnONZf.js";
3
3
 
4
4
  //#region src/core/ssr.ts
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import "./transforms-BcLQCXiC.js";
2
- import "./rpc-CRpYrgKq.js";
3
- import { r as vitePluginRsc, t as getPluginApi } from "./plugin-DNlyqBiD.js";
4
- import "./cjs-DHD_0drE.js";
1
+ import "./cjs-DH9Oa3zy.js";
2
+ import { r as vitePluginRsc, t as getPluginApi } from "./plugin-BY6tsuyx.js";
3
+ import "./transforms-D4jDIHgD.js";
4
+ import "./rpc-DbBe389F.js";
5
5
 
6
6
  export { vitePluginRsc as default, getPluginApi };
@@ -1,4 +1,4 @@
1
- import { t as __commonJSMin } from "./chunk-ezxmLbPQ.js";
1
+ import { t as __commonJSMin } from "./chunk-BFhhoFQb.js";
2
2
 
3
3
  //#region ../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js
4
4
  var require_picocolors = /* @__PURE__ */ __commonJSMin(((exports, module) => {
@@ -1,26 +1,26 @@
1
- import { n as __toDynamicImportESM } from "./chunk-ezxmLbPQ.js";
2
- import { t as vitePluginRscCore } from "./plugin-D1MQNdps.js";
3
- import { t as createDebug } from "./dist-BRSdGcl7.js";
4
- import { a as hasDirective, n as transformDirectiveProxyExport, o as transformWrapExport, s as findDirectives, t as transformServerActionServer } from "./transforms-BcLQCXiC.js";
5
- import { o as generateEncryptionKey, s as toBase64 } from "./encryption-utils-6p8t4Xqm.js";
6
- import { n as createRpcServer } from "./rpc-CRpYrgKq.js";
7
- import { t as cjsModuleRunnerPlugin } from "./cjs-DHD_0drE.js";
8
- import { i as toCssVirtual, n as parseIdQuery, r as parseReferenceValidationVirtual, t as parseCssVirtual } from "./shared-AtH_QTi7.js";
1
+ import { n as __toESM } from "./chunk-BFhhoFQb.js";
2
+ import { t as createDebug } from "./dist-DZUJDIM2.js";
3
+ import { t as vitePluginRscCore } from "./plugin-B1AJWrMi.js";
4
+ import { t as cjsModuleRunnerPlugin } from "./cjs-DH9Oa3zy.js";
5
+ import { i as toCssVirtual, n as parseIdQuery, r as parseReferenceValidationVirtual, t as parseCssVirtual } from "./shared-Chot7h9j.js";
6
+ import { a as hasDirective, n as transformDirectiveProxyExport, o as transformWrapExport, s as findDirectives, t as transformServerActionServer } from "./transforms-D4jDIHgD.js";
7
+ import { o as generateEncryptionKey, s as toBase64 } from "./encryption-utils-BPYvebX4.js";
8
+ import { n as createRpcServer } from "./rpc-DbBe389F.js";
9
9
  import { createRequire } from "node:module";
10
10
  import assert from "node:assert";
11
11
  import fs from "node:fs";
12
12
  import path from "node:path";
13
13
  import { fileURLToPath, pathToFileURL } from "node:url";
14
- import { toNodeHandler } from "srvx/node";
15
14
  import * as esModuleLexer from "es-module-lexer";
16
15
  import MagicString from "magic-string";
16
+ import { toNodeHandler } from "srvx/node";
17
+ import { stripLiteral } from "strip-literal";
17
18
  import * as vite from "vite";
18
19
  import { defaultServerConditions, isCSSRequest, isFileLoadingAllowed, normalizePath, parseAstAsync } from "vite";
19
20
  import { crawlFrameworkPkgs } from "vitefu";
20
21
  import { walk } from "estree-walker";
21
22
  import { stripVTControlCharacters } from "node:util";
22
23
  import { createHash } from "node:crypto";
23
- import { stripLiteral } from "strip-literal";
24
24
 
25
25
  //#region src/plugins/vite-utils.ts
26
26
  const VALID_ID_PREFIX = `/@id/`;
@@ -92,6 +92,128 @@ function evalValue(rawValue) {
92
92
  }
93
93
  const directRequestRE = /(\?|&)direct=?(?:&|$)/;
94
94
 
95
+ //#endregion
96
+ //#region src/plugins/find-source-map-url.ts
97
+ function vitePluginFindSourceMapURL() {
98
+ return [{
99
+ name: "rsc:findSourceMapURL",
100
+ apply: "serve",
101
+ configureServer(server) {
102
+ server.middlewares.use(async (req, res, next) => {
103
+ const url = new URL(req.url, `http://localhost`);
104
+ if (url.pathname === "/__vite_rsc_findSourceMapURL") {
105
+ let filename = url.searchParams.get("filename");
106
+ let environmentName = url.searchParams.get("environmentName");
107
+ try {
108
+ const map = await findSourceMapURL(server, filename, environmentName);
109
+ res.setHeader("content-type", "application/json");
110
+ if (!map) res.statusCode = 404;
111
+ res.end(JSON.stringify(map ?? {}));
112
+ } catch (e) {
113
+ next(e);
114
+ }
115
+ return;
116
+ }
117
+ next();
118
+ });
119
+ }
120
+ }];
121
+ }
122
+ async function findSourceMapURL(server, filename, environmentName) {
123
+ if (filename.startsWith("file://")) {
124
+ filename = slash(fileURLToPath(filename));
125
+ if (isFileLoadingAllowed(server.config, filename) && fs.existsSync(filename)) {
126
+ const content = fs.readFileSync(filename, "utf-8");
127
+ return {
128
+ version: 3,
129
+ sources: [filename],
130
+ sourcesContent: [content],
131
+ mappings: "AAAA" + ";AACA".repeat(content.split("\n").length)
132
+ };
133
+ }
134
+ return;
135
+ }
136
+ let mod;
137
+ let map;
138
+ if (environmentName === "Server") {
139
+ mod = server.environments.rsc.moduleGraph.getModuleById(filename);
140
+ map = mod?.transformResult?.map;
141
+ if (map && map.mappings) map = {
142
+ ...map,
143
+ mappings: ";;" + map.mappings
144
+ };
145
+ }
146
+ const base = server.config.base.slice(0, -1);
147
+ if (environmentName === "Client") try {
148
+ const url = new URL(filename).pathname.slice(base.length);
149
+ mod = server.environments.client.moduleGraph.urlToModuleMap.get(url);
150
+ map = mod?.transformResult?.map;
151
+ } catch (e) {}
152
+ if (mod && map) return {
153
+ ...map,
154
+ sources: [base + mod.url]
155
+ };
156
+ }
157
+
158
+ //#endregion
159
+ //#region src/plugins/resolved-id-proxy.ts
160
+ const RESOLVED_ID_PROXY_PREFIX = "virtual:vite-rsc/resolved-id/";
161
+ function toResolvedIdProxy(resolvedId) {
162
+ return RESOLVED_ID_PROXY_PREFIX + encodeURIComponent(resolvedId);
163
+ }
164
+ function withResolvedIdProxy(resolvedId) {
165
+ return resolvedId.startsWith("\0") ? toResolvedIdProxy(resolvedId) : resolvedId;
166
+ }
167
+ function fromResolvedIdProxy(source) {
168
+ if (!source.startsWith(RESOLVED_ID_PROXY_PREFIX)) return;
169
+ const clean = source.split("?")[0];
170
+ return decodeURIComponent(clean.slice(29));
171
+ }
172
+ /**
173
+ * Vite plugin that resolves proxy import specifiers to the original resolved IDs.
174
+ */
175
+ function vitePluginResolvedIdProxy() {
176
+ return {
177
+ name: "rsc:resolved-id-proxy",
178
+ resolveId: { handler(source) {
179
+ const originalId = fromResolvedIdProxy(source);
180
+ if (originalId !== void 0) return originalId;
181
+ } }
182
+ };
183
+ }
184
+
185
+ //#endregion
186
+ //#region src/plugins/scan.ts
187
+ function scanBuildStripPlugin({ manager }) {
188
+ return {
189
+ name: "rsc:scan-strip",
190
+ apply: "build",
191
+ enforce: "post",
192
+ async transform(code, _id, _options) {
193
+ if (!manager.isScanBuild) return;
194
+ return {
195
+ code: await transformScanBuildStrip(code),
196
+ map: { mappings: "" }
197
+ };
198
+ }
199
+ };
200
+ }
201
+ const importGlobRE = /\bimport\.meta\.glob(?:<\w+>)?\s*\(/g;
202
+ async function transformScanBuildStrip(code) {
203
+ const [imports] = esModuleLexer.parse(code);
204
+ let output = imports.map((e) => e.n && `import ${JSON.stringify(e.n)};\n`).filter(Boolean).join("");
205
+ if (importGlobRE.test(code)) {
206
+ walk(await parseAstAsync(code), { enter(node) {
207
+ if (node.type === "CallExpression" && node.callee.type === "MemberExpression" && node.callee.object.type === "MetaProperty" && node.callee.object.meta.type === "Identifier" && node.callee.object.meta.name === "import" && node.callee.object.property.type === "Identifier" && node.callee.object.property.name === "meta" && node.callee.property.type === "Identifier" && node.callee.property.name === "glob") {
208
+ const importMetaGlob = code.slice(node.start, node.end);
209
+ output += `console.log(${importMetaGlob});\n`;
210
+ }
211
+ } });
212
+ output += "";
213
+ }
214
+ return output;
215
+ }
216
+
95
217
  //#endregion
96
218
  //#region src/plugins/utils.ts
97
219
  function sortObject(o) {
@@ -128,10 +250,27 @@ function normalizeRelativePath(s) {
128
250
  s = normalizePath(s);
129
251
  return s[0] === "." ? s : "./" + s;
130
252
  }
131
- function getEntrySource(config, name = "index") {
253
+ function getEntrySource(config, name) {
132
254
  const input = config.build.rollupOptions.input;
133
- assert(typeof input === "object" && !Array.isArray(input) && name in input && typeof input[name] === "string", `[vite-rsc:getEntrySource] expected 'build.rollupOptions.input' to be an object with a '${name}' property that is a string, but got ${JSON.stringify(input)}`);
134
- return input[name];
255
+ if (!name) return getFallbackRollupEntry(input).source;
256
+ if (typeof input === "object" && !Array.isArray(input) && name in input && typeof input[name] === "string") return input[name];
257
+ throw new Error(`[vite-rsc:getEntrySource] expected 'build.rollupOptions.input' to be an object with a '${name}' property that is a string, but got ${JSON.stringify(input)}`);
258
+ }
259
+ function getFallbackRollupEntry(input = {}) {
260
+ const inputEntries = Object.entries(normalizeRollupOpitonsInput(input));
261
+ if (inputEntries.length === 1) {
262
+ const [name, source] = inputEntries[0];
263
+ return {
264
+ name,
265
+ source
266
+ };
267
+ }
268
+ throw new Error(`[vite-rsc] cannot determine fallback entry name from multiple entries, please specify the entry name explicitly`);
269
+ }
270
+ function normalizeRollupOpitonsInput(input = {}) {
271
+ if (typeof input === "string") input = [input];
272
+ if (Array.isArray(input)) return Object.fromEntries(input.map((file) => [path.basename(file).slice(0, -path.extname(file).length), file]));
273
+ return input;
135
274
  }
136
275
  function hashString(v) {
137
276
  return createHash("sha256").update(v).digest().toString("hex").slice(0, 12);
@@ -145,38 +284,6 @@ function getFetchHandlerExport(exports) {
145
284
  throw new Error("Invalid server handler entry");
146
285
  }
147
286
 
148
- //#endregion
149
- //#region src/plugins/scan.ts
150
- function scanBuildStripPlugin({ manager }) {
151
- return {
152
- name: "rsc:scan-strip",
153
- apply: "build",
154
- enforce: "post",
155
- async transform(code, _id, _options) {
156
- if (!manager.isScanBuild) return;
157
- return {
158
- code: await transformScanBuildStrip(code),
159
- map: { mappings: "" }
160
- };
161
- }
162
- };
163
- }
164
- const importGlobRE = /\bimport\.meta\.glob(?:<\w+>)?\s*\(/g;
165
- async function transformScanBuildStrip(code) {
166
- const [imports] = esModuleLexer.parse(code);
167
- let output = imports.map((e) => e.n && `import ${JSON.stringify(e.n)};\n`).filter(Boolean).join("");
168
- if (importGlobRE.test(code)) {
169
- walk(await parseAstAsync(code), { enter(node) {
170
- if (node.type === "CallExpression" && node.callee.type === "MemberExpression" && node.callee.object.type === "MetaProperty" && node.callee.object.meta.type === "Identifier" && node.callee.object.meta.name === "import" && node.callee.object.property.type === "Identifier" && node.callee.object.property.name === "meta" && node.callee.property.type === "Identifier" && node.callee.property.name === "glob") {
171
- const importMetaGlob = code.slice(node.start, node.end);
172
- output += `console.log(${importMetaGlob});\n`;
173
- }
174
- } });
175
- output += "";
176
- }
177
- return output;
178
- }
179
-
180
287
  //#endregion
181
288
  //#region src/plugins/validate-import.ts
182
289
  function validateImportPlugin() {
@@ -256,69 +363,6 @@ function validateImportChain(chain, environmentName, root) {
256
363
  throw error;
257
364
  }
258
365
 
259
- //#endregion
260
- //#region src/plugins/find-source-map-url.ts
261
- function vitePluginFindSourceMapURL() {
262
- return [{
263
- name: "rsc:findSourceMapURL",
264
- apply: "serve",
265
- configureServer(server) {
266
- server.middlewares.use(async (req, res, next) => {
267
- const url = new URL(req.url, `http://localhost`);
268
- if (url.pathname === "/__vite_rsc_findSourceMapURL") {
269
- let filename = url.searchParams.get("filename");
270
- let environmentName = url.searchParams.get("environmentName");
271
- try {
272
- const map = await findSourceMapURL(server, filename, environmentName);
273
- res.setHeader("content-type", "application/json");
274
- if (!map) res.statusCode = 404;
275
- res.end(JSON.stringify(map ?? {}));
276
- } catch (e) {
277
- next(e);
278
- }
279
- return;
280
- }
281
- next();
282
- });
283
- }
284
- }];
285
- }
286
- async function findSourceMapURL(server, filename, environmentName) {
287
- if (filename.startsWith("file://")) {
288
- filename = slash(fileURLToPath(filename));
289
- if (isFileLoadingAllowed(server.config, filename) && fs.existsSync(filename)) {
290
- const content = fs.readFileSync(filename, "utf-8");
291
- return {
292
- version: 3,
293
- sources: [filename],
294
- sourcesContent: [content],
295
- mappings: "AAAA" + ";AACA".repeat(content.split("\n").length)
296
- };
297
- }
298
- return;
299
- }
300
- let mod;
301
- let map;
302
- if (environmentName === "Server") {
303
- mod = server.environments.rsc.moduleGraph.getModuleById(filename);
304
- map = mod?.transformResult?.map;
305
- if (map && map.mappings) map = {
306
- ...map,
307
- mappings: ";;" + map.mappings
308
- };
309
- }
310
- const base = server.config.base.slice(0, -1);
311
- if (environmentName === "Client") try {
312
- const url = new URL(filename).pathname.slice(base.length);
313
- mod = server.environments.client.moduleGraph.urlToModuleMap.get(url);
314
- map = mod?.transformResult?.map;
315
- } catch (e) {}
316
- if (mod && map) return {
317
- ...map,
318
- sources: [base + mod.url]
319
- };
320
- }
321
-
322
366
  //#endregion
323
367
  //#region src/plugin.ts
324
368
  const isRolldownVite = "rolldownVersion" in vite;
@@ -400,13 +444,14 @@ function vitePluginRscMinimal(rscPluginOptions = {}, manager = new RscPluginMana
400
444
  }
401
445
  } }
402
446
  },
403
- scanBuildStripPlugin({ manager })
447
+ scanBuildStripPlugin({ manager }),
448
+ vitePluginResolvedIdProxy()
404
449
  ];
405
450
  }
406
451
  function vitePluginRsc(rscPluginOptions = {}) {
407
452
  const manager = new RscPluginManager();
408
453
  const buildApp = async (builder) => {
409
- const colors = await import("./picocolors-BxaHL81J.js").then(__toDynamicImportESM());
454
+ const colors = await import("./picocolors-kt7Y18A3.js").then((m) => /* @__PURE__ */ __toESM(m.default, 1));
410
455
  const logStep = (msg) => {
411
456
  builder.config.logger.info(colors.blue(msg));
412
457
  };
@@ -554,7 +599,12 @@ function vitePluginRsc(rscPluginOptions = {}) {
554
599
  if (rscPluginOptions.useBuildAppHook) await buildApp(builder);
555
600
  } },
556
601
  configureServer(server) {
557
- globalThis.__viteRscDevServer = server;
602
+ globalThis.__VITE_ENVIRONMENT_RUNNER_IMPORT__ = async function(environmentName, id) {
603
+ const environment$1 = server.environments[environmentName];
604
+ if (!environment$1) throw new Error(`[vite-rsc] unknown environment '${environmentName}'`);
605
+ if (!vite.isRunnableDevEnvironment(environment$1)) throw new Error(`[vite-rsc] environment '${environmentName}' is not runnable`);
606
+ return environment$1.runner.import(id);
607
+ };
558
608
  const oldSend = server.environments.client.hot.send;
559
609
  server.environments.client.hot.send = async function(...args) {
560
610
  const e = args[0];
@@ -698,8 +748,16 @@ function vitePluginRsc(rscPluginOptions = {}) {
698
748
  const source = getEntrySource(environment.config, entryName);
699
749
  const resolved = await environment.pluginContainer.resolveId(source);
700
750
  assert(resolved, `[vite-rsc] failed to resolve entry '${source}'`);
701
- replacement = `globalThis.__viteRscDevServer.environments[${JSON.stringify(environmentName)}].runner.import(${JSON.stringify(resolved.id)})`;
702
- } else replacement = JSON.stringify(`__vite_rsc_load_module:${this.environment.name}:${environmentName}:${entryName}`);
751
+ replacement = `globalThis.__VITE_ENVIRONMENT_RUNNER_IMPORT__(${JSON.stringify(environmentName)}, ${JSON.stringify(resolved.id)})`;
752
+ } else {
753
+ const environment = manager.config.environments[environmentName];
754
+ const targetName = entryName || getFallbackRollupEntry(environment.build.rollupOptions.input).name;
755
+ replacement = JSON.stringify(`__vite_rsc_load_module_start__:` + JSON.stringify({
756
+ fromEnv: this.environment.name,
757
+ toEnv: environmentName,
758
+ targetFileName: `${targetName}.js`
759
+ }) + `:__vite_rsc_load_module_end__`);
760
+ }
703
761
  const [start, end] = match.indices[0];
704
762
  s.overwrite(start, end, replacement);
705
763
  }
@@ -712,9 +770,10 @@ function vitePluginRsc(rscPluginOptions = {}) {
712
770
  if (!code.includes("__vite_rsc_load_module")) return;
713
771
  const { config } = manager;
714
772
  const s = new MagicString(code);
715
- for (const match of code.matchAll(/['"]__vite_rsc_load_module:(\w+):(\w+):(\w+)['"]/dg)) {
716
- const [fromEnv, toEnv, entryName] = match.slice(1);
717
- const importPath = normalizeRelativePath(path.relative(path.join(config.environments[fromEnv].build.outDir, chunk.fileName, ".."), path.join(config.environments[toEnv].build.outDir, `${entryName}.js`)));
773
+ for (const match of code.matchAll(/[`'"]__vite_rsc_load_module_start__:([\s\S]*?):__vite_rsc_load_module_end__[`'"]/dg)) {
774
+ const markerString = evalValue(match[0]);
775
+ const { fromEnv, toEnv, targetFileName } = JSON.parse(markerString.slice(31, -29));
776
+ const importPath = normalizeRelativePath(path.relative(path.join(config.environments[fromEnv].build.outDir, chunk.fileName, ".."), path.join(config.environments[toEnv].build.outDir, targetFileName)));
718
777
  const replacement = `(import(${JSON.stringify(importPath)}))`;
719
778
  const [start, end] = match.indices[0];
720
779
  s.overwrite(start, end, replacement);
@@ -732,7 +791,6 @@ function vitePluginRsc(rscPluginOptions = {}) {
732
791
  async function createHandler(url) {
733
792
  const { environmentName, entryName } = Object.fromEntries(url.searchParams);
734
793
  assert(environmentName);
735
- assert(entryName);
736
794
  const environment = server.environments[environmentName];
737
795
  const source = getEntrySource(environment.config, entryName);
738
796
  const resolvedEntry = await environment.pluginContainer.resolveId(source);
@@ -1032,7 +1090,7 @@ function vitePluginUseClient(useClientPluginOptions, manager) {
1032
1090
  };
1033
1091
  if (manager.isScanBuild) {
1034
1092
  let code$1 = ``;
1035
- for (const meta of Object.values(manager.clientReferenceMetaMap)) code$1 += `import ${JSON.stringify(meta.importId)};\n`;
1093
+ for (const meta of Object.values(manager.clientReferenceMetaMap)) code$1 += `import ${JSON.stringify(withResolvedIdProxy(meta.importId))};\n`;
1036
1094
  return {
1037
1095
  code: code$1,
1038
1096
  map: null
@@ -1075,7 +1133,7 @@ function vitePluginUseClient(useClientPluginOptions, manager) {
1075
1133
  for (const meta of metas) {
1076
1134
  const exports = meta.renderedExports.map((name$1) => `${name$1}: import_${meta.referenceKey}.${name$1},\n`).sort().join("");
1077
1135
  code += `
1078
- import * as import_${meta.referenceKey} from ${JSON.stringify(meta.importId)};
1136
+ import * as import_${meta.referenceKey} from ${JSON.stringify(withResolvedIdProxy(meta.importId))};
1079
1137
  export const export_${meta.referenceKey} = {${exports}};
1080
1138
  `;
1081
1139
  }
package/dist/plugin.d.ts CHANGED
@@ -112,6 +112,9 @@ type PluginApi = {
112
112
  declare function getPluginApi(config: Pick<ResolvedConfig, "plugins">): PluginApi | undefined;
113
113
  /** @experimental */
114
114
  declare function vitePluginRscMinimal(rscPluginOptions?: RscPluginOptions, manager?: RscPluginManager): Plugin[];
115
+ declare global {
116
+ function __VITE_ENVIRONMENT_RUNNER_IMPORT__(environmentName: string, id: string): Promise<any>;
117
+ }
115
118
  declare function vitePluginRsc(rscPluginOptions?: RscPluginOptions): Plugin[];
116
119
  declare class RuntimeAsset {
117
120
  runtime: string;
package/dist/plugin.js CHANGED
@@ -1,6 +1,6 @@
1
- import "./transforms-BcLQCXiC.js";
2
- import "./rpc-CRpYrgKq.js";
3
- import { i as vitePluginRscMinimal, n as transformRscCssExport, r as vitePluginRsc, t as getPluginApi } from "./plugin-DNlyqBiD.js";
4
- import "./cjs-DHD_0drE.js";
1
+ import "./cjs-DH9Oa3zy.js";
2
+ import { i as vitePluginRscMinimal, n as transformRscCssExport, r as vitePluginRsc, t as getPluginApi } from "./plugin-BY6tsuyx.js";
3
+ import "./transforms-D4jDIHgD.js";
4
+ import "./rpc-DbBe389F.js";
5
5
 
6
6
  export { vitePluginRsc as default, getPluginApi, transformRscCssExport, vitePluginRscMinimal };
@@ -1,3 +1,3 @@
1
- import { t as cjsModuleRunnerPlugin } from "../cjs-DHD_0drE.js";
1
+ import { t as cjsModuleRunnerPlugin } from "../cjs-DH9Oa3zy.js";
2
2
 
3
3
  export { cjsModuleRunnerPlugin };
package/dist/react/rsc.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as setRequireModule, i as loadServerAction, n as createServerDecodeClientManifest, r as createServerManifest, t as createClientManifest } from "../rsc-BRh4PjTs.js";
1
+ import { a as setRequireModule, i as loadServerAction, n as createServerDecodeClientManifest, r as createServerManifest, t as createClientManifest } from "../rsc-DRNoX2Q6.js";
2
2
  import * as ReactClient from "@vitejs/plugin-rsc/vendor/react-server-dom/client.edge";
3
3
  import * as ReactServer from "@vitejs/plugin-rsc/vendor/react-server-dom/server.edge";
4
4
 
@@ -1,4 +1,4 @@
1
- import { i as tinyassert, n as memoize } from "./dist-BRSdGcl7.js";
1
+ import { i as tinyassert, n as memoize } from "./dist-DZUJDIM2.js";
2
2
  import { a as setInternalRequire, i as removeReferenceCacheTag, n as SERVER_REFERENCE_PREFIX, r as createReferenceCacheTag, t as SERVER_DECODE_CLIENT_PREFIX } from "./shared-DEpnONZf.js";
3
3
  import * as ReactServer from "@vitejs/plugin-rsc/vendor/react-server-dom/server.edge";
4
4
 
package/dist/rsc.js CHANGED
@@ -1,5 +1,5 @@
1
- import { a as toReferenceValidationVirtual } from "./shared-AtH_QTi7.js";
2
- import { a as setRequireModule, i as loadServerAction, r as createServerManifest, t as createClientManifest } from "./rsc-BRh4PjTs.js";
1
+ import { a as toReferenceValidationVirtual } from "./shared-Chot7h9j.js";
2
+ import { a as setRequireModule, i as loadServerAction, r as createServerManifest, t as createClientManifest } from "./rsc-DRNoX2Q6.js";
3
3
  import { createClientTemporaryReferenceSet, createFromReadableStream, createTemporaryReferenceSet, decodeAction, decodeFormState, decodeReply, encodeReply, registerClientReference, registerServerReference, renderToReadableStream } from "./react/rsc.js";
4
4
  import { decryptActionBoundArgs, encryptActionBoundArgs } from "./utils/encryption-runtime.js";
5
5
  import serverReferences from "virtual:vite-rsc/server-references";
package/dist/ssr.js CHANGED
@@ -1,9 +1,9 @@
1
- import { a as toReferenceValidationVirtual, i as toCssVirtual } from "./shared-AtH_QTi7.js";
1
+ import { a as toReferenceValidationVirtual, i as toCssVirtual } from "./shared-Chot7h9j.js";
2
2
  import { createServerConsumerManifest, setRequireModule } from "./core/ssr.js";
3
3
  import { callServer, createFromReadableStream, createServerReference, findSourceMapURL } from "./react/ssr.js";
4
4
  import * as clientReferences from "virtual:vite-rsc/client-references";
5
- import assetsManifest from "virtual:vite-rsc/assets-manifest";
6
5
  import * as ReactDOM from "react-dom";
6
+ import assetsManifest from "virtual:vite-rsc/assets-manifest";
7
7
 
8
8
  //#region src/ssr.tsx
9
9
  initialize();
@@ -1,3 +1,3 @@
1
- import { a as hasDirective, c as transformHoistInlineDirective, i as getExportNames, n as transformDirectiveProxyExport, o as transformWrapExport, r as transformProxyExport, s as findDirectives, t as transformServerActionServer } from "../transforms-BcLQCXiC.js";
1
+ import { a as hasDirective, c as transformHoistInlineDirective, i as getExportNames, n as transformDirectiveProxyExport, o as transformWrapExport, r as transformProxyExport, s as findDirectives, t as transformServerActionServer } from "../transforms-D4jDIHgD.js";
2
2
 
3
3
  export { findDirectives, getExportNames, hasDirective, transformDirectiveProxyExport, transformHoistInlineDirective, transformProxyExport, transformServerActionServer, transformWrapExport };
@@ -1,4 +1,4 @@
1
- import { i as tinyassert } from "./dist-BRSdGcl7.js";
1
+ import { i as tinyassert } from "./dist-DZUJDIM2.js";
2
2
  import MagicString from "magic-string";
3
3
  import { walk } from "estree-walker";
4
4
  import { analyze, extract_names } from "periscopic";
@@ -1,6 +1,6 @@
1
- import { r as once } from "../dist-BRSdGcl7.js";
2
- import { a as fromBase64, i as encryptBuffer, n as concatArrayStream, r as decryptBuffer, t as arrayToStream } from "../encryption-utils-6p8t4Xqm.js";
3
- import "../rsc-BRh4PjTs.js";
1
+ import { r as once } from "../dist-DZUJDIM2.js";
2
+ import { a as fromBase64, i as encryptBuffer, n as concatArrayStream, r as decryptBuffer, t as arrayToStream } from "../encryption-utils-BPYvebX4.js";
3
+ import "../rsc-DRNoX2Q6.js";
4
4
  import { createFromReadableStream, renderToReadableStream } from "../react/rsc.js";
5
5
  import encryptionKeySource from "virtual:vite-rsc/encryption-key";
6
6
 
package/dist/utils/rpc.js CHANGED
@@ -1,3 +1,3 @@
1
- import { n as createRpcServer, t as createRpcClient } from "../rpc-CRpYrgKq.js";
1
+ import { n as createRpcServer, t as createRpcClient } from "../rpc-DbBe389F.js";
2
2
 
3
3
  export { createRpcClient, createRpcServer };
package/package.json CHANGED
@@ -1,21 +1,25 @@
1
1
  {
2
2
  "name": "@vitejs/plugin-rsc",
3
- "version": "0.5.10",
3
+ "version": "0.5.12",
4
4
  "description": "React Server Components (RSC) support for Vite.",
5
5
  "keywords": [
6
- "vite",
7
- "vite-plugin",
8
6
  "react",
9
7
  "react-server-components",
10
- "rsc"
8
+ "rsc",
9
+ "vite",
10
+ "vite-plugin"
11
11
  ],
12
12
  "homepage": "https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-rsc",
13
+ "license": "MIT",
13
14
  "repository": {
14
15
  "type": "git",
15
16
  "url": "git+https://github.com/vitejs/vite-plugin-react.git",
16
17
  "directory": "packages/plugin-rsc"
17
18
  },
18
- "license": "MIT",
19
+ "files": [
20
+ "dist",
21
+ "types"
22
+ ],
19
23
  "type": "module",
20
24
  "exports": {
21
25
  "./package.json": "./package.json",
@@ -24,10 +28,6 @@
24
28
  "./transforms": "./dist/transforms/index.js",
25
29
  "./*": "./dist/*.js"
26
30
  },
27
- "files": [
28
- "dist",
29
- "types"
30
- ],
31
31
  "scripts": {
32
32
  "test": "vitest",
33
33
  "test-e2e": "playwright test --project=chromium",
@@ -53,8 +53,8 @@
53
53
  "@playwright/test": "^1.57.0",
54
54
  "@tsconfig/strictest": "^2.0.8",
55
55
  "@types/estree": "^1.0.8",
56
- "@types/node": "^24.10.4",
57
- "@types/react": "^19.2.7",
56
+ "@types/node": "^24.10.7",
57
+ "@types/react": "^19.2.8",
58
58
  "@types/react-dom": "^19.2.3",
59
59
  "@vitejs/plugin-react": "workspace:*",
60
60
  "@vitejs/test-dep-cjs-and-esm": "./test-dep/cjs-and-esm",
@@ -63,7 +63,7 @@
63
63
  "react-dom": "^19.2.3",
64
64
  "react-server-dom-webpack": "^19.2.3",
65
65
  "tinyexec": "^1.0.2",
66
- "tsdown": "^0.18.4"
66
+ "tsdown": "^0.19.0"
67
67
  },
68
68
  "peerDependencies": {
69
69
  "react": "*",
package/types/index.d.ts CHANGED
@@ -2,7 +2,7 @@ declare global {
2
2
  interface ImportMeta {
3
3
  readonly viteRsc: {
4
4
  loadCss: (importer?: string) => import('react').ReactNode
5
- loadModule: <T>(environmentName: string, entryName: string) => Promise<T>
5
+ loadModule: <T>(environmentName: string, entryName?: string) => Promise<T>
6
6
  loadBootstrapScriptContent: (entryName: string) => Promise<string>
7
7
  }
8
8
  }
File without changes
File without changes
File without changes
File without changes